diff --git a/README.md b/README.md index 298ffa8..81bb534 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ nvm install nvm use ``` -For første leveranse kan frontend kjøres alene fordi oppskrifter og autentisering foreløpig er mocket: +Oppskriftsvisningen kan kjøres med frontend alene. Innlogging og registrering krever API og PostgreSQL: ```bash npm run dev:web @@ -59,6 +59,22 @@ Copy-Item .env.example .env Ikke legg `.env`, passord, tokens eller andre hemmeligheter i Git. +## Authentication + +Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing still uses mock data. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user. + +Session tokens are bearer credentials stored in localStorage to restore login after refresh or reopening the browser. They expire after seven days and are deleted server-side on successful logout. Temporary API or network errors preserve the local token for a later restoration attempt; only a confirmed invalid or expired session clears it. + +Security trade-off: localStorage is readable by JavaScript on the same origin. An XSS vulnerability could steal a token and let an attacker impersonate its owner until expiry or revocation. This prototype accepts that limitation; production deployment should use HTTPS and consider Secure, HttpOnly, SameSite cookies with appropriate CSRF protection. HttpOnly cookies prevent JavaScript from reading the session credential. + +### Protected routes + +`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the token. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server. + +## Database + +Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen utvider autentiseringen og er klar for CRUD i neste steg. + ## Nyttige kommandoer | Kommando | Bruk | @@ -103,8 +119,8 @@ Oppskrifter kan være offentlige eller private. Offentlige oppskrifter finnes gj | `/cookbook` | My Cookbook: lagrede og egenproduserte oppskrifter | | `/recipes/:id` | Detaljvisning av én oppskrift | | `/recipes/new` | Skjema for å opprette en oppskrift | -| `/login` | Mock innlogging | -| `/register` | Mock registrering | +| `/login` | Innlogging via GraphQL | +| `/register` | Registrering via GraphQL | ### Viktige brukerreiser diff --git a/apps/api/migrations/0001_familiar_shocker.sql b/apps/api/migrations/0001_familiar_shocker.sql new file mode 100644 index 0000000..a46fbef --- /dev/null +++ b/apps/api/migrations/0001_familiar_shocker.sql @@ -0,0 +1,16 @@ +CREATE TABLE "project2"."sessions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" uuid NOT NULL, + "expires_at" timestamp with time zone NOT NULL +); +--> statement-breakpoint +CREATE TABLE "project2"."users" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "name" text NOT NULL, + "email" text NOT NULL, + "password_hash" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "project2"."sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "users_email_unique" ON "project2"."users" USING btree ("email"); \ No newline at end of file diff --git a/apps/api/migrations/0002_recipe_model.sql b/apps/api/migrations/0002_recipe_model.sql new file mode 100644 index 0000000..5065027 --- /dev/null +++ b/apps/api/migrations/0002_recipe_model.sql @@ -0,0 +1,105 @@ +-- Existing placeholder recipes need a deliberate author/content backfill. +-- Stop before changing tables rather than inventing ownership or losing data. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM "project2"."recipes") THEN + RAISE EXCEPTION 'Recipe migration requires an empty legacy recipes table. Back up existing rows and prepare an explicit author/content backfill before retrying.'; + END IF; +END $$; +--> statement-breakpoint +CREATE TABLE "project2"."ratings" ( + "user_id" uuid NOT NULL, + "recipe_id" uuid NOT NULL, + "score" integer NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "ratings_user_id_recipe_id_pk" PRIMARY KEY("user_id","recipe_id"), + CONSTRAINT "ratings_score_valid" CHECK ("project2"."ratings"."score" BETWEEN 1 AND 5) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_ingredients" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "recipe_id" uuid NOT NULL, + "name" text NOT NULL, + "amount" numeric(12, 4) NOT NULL, + "unit" text NOT NULL, + "note" text, + "position" integer NOT NULL, + CONSTRAINT "recipe_ingredients_name_not_blank" CHECK (length(trim("project2"."recipe_ingredients"."name")) > 0), + CONSTRAINT "recipe_ingredients_amount_positive" CHECK ("project2"."recipe_ingredients"."amount" > 0 AND "project2"."recipe_ingredients"."amount" <> 'NaN'::numeric), + CONSTRAINT "recipe_ingredients_position_positive" CHECK ("project2"."recipe_ingredients"."position" > 0) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_instructions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "recipe_id" uuid NOT NULL, + "text" text NOT NULL, + "position" integer NOT NULL, + CONSTRAINT "recipe_instructions_text_not_blank" CHECK (length(trim("project2"."recipe_instructions"."text")) > 0), + CONSTRAINT "recipe_instructions_position_positive" CHECK ("project2"."recipe_instructions"."position" > 0) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_tags" ( + "recipe_id" uuid NOT NULL, + "tag" text NOT NULL, + CONSTRAINT "recipe_tags_recipe_id_tag_pk" PRIMARY KEY("recipe_id","tag"), + CONSTRAINT "recipe_tags_normalized" CHECK (length("project2"."recipe_tags"."tag") > 0 AND "project2"."recipe_tags"."tag" = lower(trim("project2"."recipe_tags"."tag"))) +); +--> statement-breakpoint +CREATE TABLE "project2"."saved_recipes" ( + "user_id" uuid NOT NULL, + "recipe_id" uuid NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "saved_recipes_user_id_recipe_id_pk" PRIMARY KEY("user_id","recipe_id") +); +--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "author_id" uuid NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "description" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "image_url" text;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "category" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "cuisine" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "difficulty" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "visibility" text DEFAULT 'private' NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "prep_minutes" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "cook_minutes" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "servings" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "created_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "updated_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."ratings" ADD CONSTRAINT "ratings_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."ratings" ADD CONSTRAINT "ratings_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_ingredients" ADD CONSTRAINT "recipe_ingredients_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_instructions" ADD CONSTRAINT "recipe_instructions_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_tags" ADD CONSTRAINT "recipe_tags_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."saved_recipes" ADD CONSTRAINT "saved_recipes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."saved_recipes" ADD CONSTRAINT "saved_recipes_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "ratings_recipe_idx" ON "project2"."ratings" USING btree ("recipe_id");--> statement-breakpoint +CREATE UNIQUE INDEX "recipe_ingredients_recipe_position_unique" ON "project2"."recipe_ingredients" USING btree ("recipe_id","position");--> statement-breakpoint +CREATE UNIQUE INDEX "recipe_instructions_recipe_position_unique" ON "project2"."recipe_instructions" USING btree ("recipe_id","position");--> statement-breakpoint +CREATE INDEX "saved_recipes_recipe_idx" ON "project2"."saved_recipes" USING btree ("recipe_id");--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_author_id_users_id_fk" FOREIGN KEY ("author_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "recipes_author_idx" ON "project2"."recipes" USING btree ("author_id");--> statement-breakpoint +CREATE INDEX "recipes_public_created_idx" ON "project2"."recipes" USING btree ("created_at","id") WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_title_not_blank" CHECK (length(trim("project2"."recipes"."title")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_category_not_blank" CHECK (length(trim("project2"."recipes"."category")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_cuisine_not_blank" CHECK (length(trim("project2"."recipes"."cuisine")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_difficulty_valid" CHECK ("project2"."recipes"."difficulty" IN ('easy', 'medium', 'hard'));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_visibility_valid" CHECK ("project2"."recipes"."visibility" IN ('public', 'private'));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_prep_minutes_nonnegative" CHECK ("project2"."recipes"."prep_minutes" >= 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_cook_minutes_nonnegative" CHECK ("project2"."recipes"."cook_minutes" >= 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_servings_positive" CHECK ("project2"."recipes"."servings" > 0); +--> statement-breakpoint +-- Database triggers also cover writes made through raw SQL (as in auth). +CREATE FUNCTION "project2"."touch_updated_at"() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + NEW.updated_at = clock_timestamp(); + RETURN NEW; +END $$; +--> statement-breakpoint +CREATE TRIGGER recipes_touch_updated_at +BEFORE UPDATE ON "project2"."recipes" +FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); +--> statement-breakpoint +CREATE TRIGGER ratings_touch_updated_at +BEFORE UPDATE ON "project2"."ratings" +FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); diff --git a/apps/api/migrations/0003_recipe_review.sql b/apps/api/migrations/0003_recipe_review.sql new file mode 100644 index 0000000..df53def --- /dev/null +++ b/apps/api/migrations/0003_recipe_review.sql @@ -0,0 +1,10 @@ +ALTER TABLE "project2"."recipes" DROP CONSTRAINT "recipes_category_not_blank";--> statement-breakpoint +ALTER TABLE "project2"."recipes" ALTER COLUMN "cuisine" DROP NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "source_recipe_id" uuid;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_source_recipe_id_recipes_id_fk" FOREIGN KEY ("source_recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "recipes_source_idx" ON "project2"."recipes" USING btree ("source_recipe_id");--> statement-breakpoint +-- Normalize known category labels without guessing mappings for unknown values. +-- Unknown categories abort the migration and require an explicit correction. +UPDATE "project2"."recipes" SET "category" = lower(trim("category")) +WHERE "category" <> lower(trim("category"));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_category_valid" CHECK ("project2"."recipes"."category" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')); diff --git a/apps/api/migrations/meta/0001_snapshot.json b/apps/api/migrations/meta/0001_snapshot.json new file mode 100644 index 0000000..dd8ec84 --- /dev/null +++ b/apps/api/migrations/meta/0001_snapshot.json @@ -0,0 +1,149 @@ +{ + "id": "8106c561-4f83-4ec4-9119-840e77bd557d", + "prevId": "fa9889d1-8b19-437d-8360-333cd24d5aea", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/0002_snapshot.json b/apps/api/migrations/meta/0002_snapshot.json new file mode 100644 index 0000000..742398e --- /dev/null +++ b/apps/api/migrations/meta/0002_snapshot.json @@ -0,0 +1,700 @@ +{ + "id": "078adb6f-bfdc-42b6-9e70-e621fc612161", + "prevId": "8106c561-4f83-4ec4-9119-840e77bd557d", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_not_blank": { + "name": "recipes_category_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"category\")) > 0" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/0003_snapshot.json b/apps/api/migrations/meta/0003_snapshot.json new file mode 100644 index 0000000..ef92bf5 --- /dev/null +++ b/apps/api/migrations/meta/0003_snapshot.json @@ -0,0 +1,731 @@ +{ + "id": "c0ecbb19-5a20-4d7a-808d-836ae2992c9e", + "prevId": "078adb6f-bfdc-42b6-9e70-e621fc612161", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_recipe_id": { + "name": "source_recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_source_idx": { + "name": "recipes_source_idx", + "columns": [ + { + "expression": "source_recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "recipes_source_recipe_id_recipes_id_fk": { + "name": "recipes_source_recipe_id_recipes_id_fk", + "tableFrom": "recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["source_recipe_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_valid": { + "name": "recipes_category_valid", + "value": "\"project2\".\"recipes\".\"category\" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index 5e9ab2c..4d08ec8 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -8,6 +8,27 @@ "when": 1790582041612, "tag": "0000_glorious_squadron_sinister", "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1791418622259, + "tag": "0001_familiar_shocker", + "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1791729925525, + "tag": "0002_recipe_model", + "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1791796199161, + "tag": "0003_recipe_review", + "breakpoints": true } ] } diff --git a/apps/api/package.json b/apps/api/package.json index 0869dd7..2f379ff 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -3,11 +3,12 @@ "private": true, "type": "module", "scripts": { - "dev": "tsx --env-file-if-exists=../../.env watch src/server.ts", - "build": "tsc && cp src/schema.graphql dist/schema.graphql", + "dev": "tsx watch --env-file-if-exists=../../.env src/server.ts", + "build": "tsc && node -e \"require('node:fs').copyFileSync('src/schema.graphql', 'dist/schema.graphql')\"", "start": "node --env-file-if-exists=../../.env dist/server.js" }, "dependencies": { + "argon2": "0.45.1", "drizzle-orm": "0.45.2", "graphql": "16.12.0", "graphql-yoga": "5.16.2", diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 1100b34..0294e69 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,6 +1,8 @@ import { readFileSync } from 'node:fs'; import { createSchema, createYoga } from 'graphql-yoga'; + import type { Resolvers } from './generated.js'; +import { authResolvers } from './features/auth/authResolvers.js'; export const app = createYoga({ schema: createSchema({ @@ -8,7 +10,15 @@ export const app = createYoga({ new URL('./schema.graphql', import.meta.url), 'utf8', ), - resolvers: { Query: { health: () => 'ok' } } satisfies Resolvers, + resolvers: { + Query: { + health: () => 'ok', + ...authResolvers.Query, + }, + Mutation: { + ...authResolvers.Mutation, + }, + } satisfies Resolvers, }), graphqlEndpoint: '/graphql', }); diff --git a/apps/api/src/db/migrate.ts b/apps/api/src/db/migrate.ts index 9f29dfd..1491bbb 100644 --- a/apps/api/src/db/migrate.ts +++ b/apps/api/src/db/migrate.ts @@ -2,5 +2,10 @@ import { drizzle } from 'drizzle-orm/node-postgres'; import { migrate } from 'drizzle-orm/node-postgres/migrator'; import { db } from './client.js'; -await migrate(drizzle(db), { migrationsFolder: 'apps/api/migrations' }); -await db.end(); +try { + // The original migrations reference project2 without creating it. + await db.query('CREATE SCHEMA IF NOT EXISTS project2'); + await migrate(drizzle(db), { migrationsFolder: 'apps/api/migrations' }); +} finally { + await db.end(); +} diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 5c8837c..cc6c5f3 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -1,8 +1,212 @@ -import { pgSchema, text, uuid } from 'drizzle-orm/pg-core'; +import { sql } from 'drizzle-orm'; +import { + type AnyPgColumn, + check, + index, + integer, + numeric, + primaryKey, + pgSchema, + text, + timestamp, + uniqueIndex, + uuid, +} from 'drizzle-orm/pg-core'; const project2 = pgSchema('project2'); -export const recipes = project2.table('recipes', { +export const users = project2.table( + 'users', + { + id: uuid().primaryKey().defaultRandom(), + name: text().notNull(), + email: text().notNull(), + passwordHash: text('password_hash').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [uniqueIndex('users_email_unique').on(table.email)], +); + +export const sessions = project2.table('sessions', { id: uuid().primaryKey().defaultRandom(), - title: text().notNull(), + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), }); + +// Each recipe belongs to one user. Ingredient and instruction rows belong to +// the recipe and are removed automatically when that recipe is deleted. +export const recipes = project2.table( + 'recipes', + { + id: uuid().primaryKey().defaultRandom(), + authorId: uuid('author_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + sourceRecipeId: uuid('source_recipe_id').references( + (): AnyPgColumn => recipes.id, + { onDelete: 'set null' }, + ), + title: text().notNull(), + description: text().notNull(), + imageUrl: text('image_url'), + category: text({ + enum: ['breakfast', 'lunch', 'dinner', 'dessert', 'soup'], + }).notNull(), + cuisine: text(), + difficulty: text({ enum: ['easy', 'medium', 'hard'] }).notNull(), + visibility: text({ enum: ['public', 'private'] }) + .notNull() + .default('private'), + prepMinutes: integer('prep_minutes').notNull(), + cookMinutes: integer('cook_minutes').notNull(), + servings: integer().notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + index('recipes_author_idx').on(table.authorId), + index('recipes_source_idx').on(table.sourceRecipeId), + index('recipes_public_created_idx') + .on(table.createdAt, table.id) + .where(sql`${table.visibility} = 'public'`), + check('recipes_title_not_blank', sql`length(trim(${table.title})) > 0`), + check( + 'recipes_category_valid', + sql`${table.category} IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')`, + ), + check('recipes_cuisine_not_blank', sql`length(trim(${table.cuisine})) > 0`), + check( + 'recipes_difficulty_valid', + sql`${table.difficulty} IN ('easy', 'medium', 'hard')`, + ), + check( + 'recipes_visibility_valid', + sql`${table.visibility} IN ('public', 'private')`, + ), + check('recipes_prep_minutes_nonnegative', sql`${table.prepMinutes} >= 0`), + check('recipes_cook_minutes_nonnegative', sql`${table.cookMinutes} >= 0`), + check('recipes_servings_positive', sql`${table.servings} > 0`), + ], +); + +export const recipeIngredients = project2.table( + 'recipe_ingredients', + { + id: uuid().primaryKey().defaultRandom(), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + name: text().notNull(), + // PostgreSQL numeric preserves decimal quantities; Drizzle returns strings. + amount: numeric({ precision: 12, scale: 4 }).notNull(), + unit: text().notNull(), + note: text(), + position: integer().notNull(), + }, + (table) => [ + uniqueIndex('recipe_ingredients_recipe_position_unique').on( + table.recipeId, + table.position, + ), + check( + 'recipe_ingredients_name_not_blank', + sql`length(trim(${table.name})) > 0`, + ), + check( + 'recipe_ingredients_amount_positive', + sql`${table.amount} > 0 AND ${table.amount} <> 'NaN'::numeric`, + ), + check('recipe_ingredients_position_positive', sql`${table.position} > 0`), + ], +); + +export const recipeInstructions = project2.table( + 'recipe_instructions', + { + id: uuid().primaryKey().defaultRandom(), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + text: text().notNull(), + position: integer().notNull(), + }, + (table) => [ + uniqueIndex('recipe_instructions_recipe_position_unique').on( + table.recipeId, + table.position, + ), + check( + 'recipe_instructions_text_not_blank', + sql`length(trim(${table.text})) > 0`, + ), + check('recipe_instructions_position_positive', sql`${table.position} > 0`), + ], +); + +export const recipeTags = project2.table( + 'recipe_tags', + { + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + tag: text().notNull(), + }, + (table) => [ + primaryKey({ columns: [table.recipeId, table.tag] }), + check( + 'recipe_tags_normalized', + sql`length(${table.tag}) > 0 AND ${table.tag} = lower(trim(${table.tag}))`, + ), + ], +); + +export const savedRecipes = project2.table( + 'saved_recipes', + { + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.recipeId] }), + index('saved_recipes_recipe_idx').on(table.recipeId), + ], +); + +export const ratings = project2.table( + 'ratings', + { + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + score: integer().notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.recipeId] }), + index('ratings_recipe_idx').on(table.recipeId), + check('ratings_score_valid', sql`${table.score} BETWEEN 1 AND 5`), + ], +); diff --git a/apps/api/src/features/auth/authRepository.test.ts b/apps/api/src/features/auth/authRepository.test.ts new file mode 100644 index 0000000..9697703 --- /dev/null +++ b/apps/api/src/features/auth/authRepository.test.ts @@ -0,0 +1,74 @@ +import type { Pool, PoolClient } from 'pg'; +import { describe, expect, it, vi } from 'vitest'; +import { createAuthRepository } from './authRepository.js'; + +const user = { id: 'user-123', name: 'Hasan', email: 'hasan@example.com' }; + +function setup(failure?: Error | { code: string; constraint: string }) { + let persistedUser = false; + const query = vi.fn(async (sql: string) => { + if (sql.includes('INSERT INTO project2.users')) { + if (failure && 'code' in failure) throw failure; + persistedUser = true; + return { rows: [user] }; + } + if (sql.includes('INSERT INTO project2.sessions')) { + if (failure) throw failure; + return { rows: [{ id: 'session-123' }] }; + } + if (sql === 'ROLLBACK') persistedUser = false; + return { rows: [] }; + }); + const release = vi.fn(); + const client = { query, release } as unknown as PoolClient; + const pool = { + connect: vi.fn(async () => client), + query: vi.fn(), + } as unknown as Pool; + return { + repository: createAuthRepository(pool), + query, + release, + pool, + hasUser: () => persistedUser, + }; +} + +describe('atomic registration', () => { + it('commits user and session on the same connection', async () => { + const { repository, query, release, pool } = setup(); + const expiresAt = new Date(); + await expect( + repository.createUserWithSession('Hasan', user.email, 'hash', expiresAt), + ).resolves.toEqual({ user, sessionToken: 'session-123' }); + expect(query.mock.calls.map(([sql]) => sql.trim().split(/\s+/)[0])).toEqual( + ['BEGIN', 'INSERT', 'INSERT', 'COMMIT'], + ); + expect(pool.query).not.toHaveBeenCalled(); + expect(release).toHaveBeenCalledOnce(); + }); + + it('rolls back and releases the connection when session creation fails', async () => { + const failure = new Error('Session insert failed'); + const { repository, query, release, hasUser } = setup(failure); + await expect( + repository.createUserWithSession('Hasan', user.email, 'hash', new Date()), + ).rejects.toBe(failure); + expect(query).toHaveBeenLastCalledWith('ROLLBACK'); + expect(query).not.toHaveBeenCalledWith('COMMIT'); + expect(hasUser()).toBe(false); + expect(release).toHaveBeenCalledOnce(); + }); + + it('handles concurrent registration of the same email', async () => { + const { repository, query, release } = setup({ + code: '23505', + constraint: 'users_email_unique', + }); + await expect( + repository.createUserWithSession('Hasan', user.email, 'hash', new Date()), + ).rejects.toThrow('An account with this email already exists.'); + expect(query).toHaveBeenLastCalledWith('ROLLBACK'); + expect(release).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/api/src/features/auth/authRepository.ts b/apps/api/src/features/auth/authRepository.ts new file mode 100644 index 0000000..67ce794 --- /dev/null +++ b/apps/api/src/features/auth/authRepository.ts @@ -0,0 +1,179 @@ +import { GraphQLError } from 'graphql'; +import type { Pool } from 'pg'; + +import { db } from '../../db/client.js'; + +export interface AuthUserRecord { + id: string; + name: string; + email: string; + passwordHash: string; +} + +export interface PublicUser { + id: string; + name: string; + email: string; +} + +interface UserRow { + id: string; + name: string; + email: string; + password_hash: string; +} + +interface SessionUserRow { + id: string; + name: string; + email: string; +} + +export interface AuthRepository { + findUserByEmail(email: string): Promise; + + createUser( + name: string, + email: string, + passwordHash: string, + ): Promise; + + createUserWithSession( + name: string, + email: string, + passwordHash: string, + expiresAt: Date, + ): Promise<{ user: PublicUser; sessionToken: string }>; + + createSession(userId: string, expiresAt: Date): Promise; + + findUserBySession(sessionToken: string): Promise; + + deleteSession(sessionToken: string): Promise; +} + +export function createAuthRepository( + pool: Pool = db, + executor: Pick = pool, +): AuthRepository { + return { + async findUserByEmail(email) { + const result = await executor.query( + ` + SELECT id, name, email, password_hash + FROM project2.users + WHERE email = $1 + LIMIT 1 + `, + [email], + ); + + const user = result.rows[0]; + + if (!user) { + return null; + } + + return { + id: user.id, + name: user.name, + email: user.email, + passwordHash: user.password_hash, + }; + }, + + async createUser(name, email, passwordHash) { + const result = await executor.query( + ` + INSERT INTO project2.users (name, email, password_hash) + VALUES ($1, $2, $3) + RETURNING id, name, email + `, + [name, email, passwordHash], + ); + + const user = result.rows[0]; + + if (!user) { + throw new Error('User could not be created.'); + } + + return user; + }, + + async createUserWithSession(name, email, passwordHash, expiresAt) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const repository = createAuthRepository(pool, client); + const user = await repository.createUser(name, email, passwordHash); + const sessionToken = await repository.createSession(user.id, expiresAt); + await client.query('COMMIT'); + return { user, sessionToken }; + } catch (error) { + await client.query('ROLLBACK'); + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === '23505' && + 'constraint' in error && + error.constraint === 'users_email_unique' + ) { + throw new GraphQLError('An account with this email already exists.'); + } + throw error; + } finally { + client.release(); + } + }, + + async createSession(userId, expiresAt) { + const result = await executor.query<{ id: string }>( + ` + INSERT INTO project2.sessions (user_id, expires_at) + VALUES ($1, $2) + RETURNING id + `, + [userId, expiresAt], + ); + + const session = result.rows[0]; + + if (!session) { + throw new Error('Session could not be created.'); + } + + return session.id; + }, + + async findUserBySession(sessionToken) { + const result = await executor.query( + ` + SELECT users.id, users.name, users.email + FROM project2.sessions AS sessions + JOIN project2.users AS users + ON users.id = sessions.user_id + WHERE sessions.id = $1 + AND sessions.expires_at > now() + LIMIT 1 + `, + [sessionToken], + ); + + return result.rows[0] ?? null; + }, + + async deleteSession(sessionToken) { + await executor.query( + ` + DELETE FROM project2.sessions + WHERE id = $1 + `, + [sessionToken], + ); + }, + }; +} + +export const authRepository = createAuthRepository(); diff --git a/apps/api/src/features/auth/authResolvers.ts b/apps/api/src/features/auth/authResolvers.ts new file mode 100644 index 0000000..97452d0 --- /dev/null +++ b/apps/api/src/features/auth/authResolvers.ts @@ -0,0 +1,30 @@ +import { authService } from './authService.js'; + +export const authResolvers = { + Query: { + currentUser: (_parent: unknown, args: { sessionToken: string }) => + authService.currentUser(args.sessionToken), + }, + + Mutation: { + register: ( + _parent: unknown, + args: { + name: string; + email: string; + password: string; + }, + ) => authService.register(args.name, args.email, args.password), + + login: ( + _parent: unknown, + args: { + email: string; + password: string; + }, + ) => authService.login(args.email, args.password), + + signOut: (_parent: unknown, args: { sessionToken: string }) => + authService.signOut(args.sessionToken), + }, +}; diff --git a/apps/api/src/features/auth/authService.test.ts b/apps/api/src/features/auth/authService.test.ts new file mode 100644 index 0000000..7f5c456 --- /dev/null +++ b/apps/api/src/features/auth/authService.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { createAuthService, type PasswordHasher } from './authService.js'; + +import type { + AuthRepository, + AuthUserRecord, + PublicUser, +} from './authRepository.js'; + +const publicUser: PublicUser = { + id: 'user-123', + name: 'Hasan', + email: 'hasan@example.com', +}; + +const storedUser: AuthUserRecord = { + ...publicUser, + passwordHash: 'hashed:secret123', +}; + +function createRepository( + overrides: Partial = {}, +): AuthRepository { + return { + findUserByEmail: vi.fn(async () => null), + createUserWithSession: vi.fn(async () => ({ + user: publicUser, + sessionToken: 'session-123', + })), + createUser: vi.fn(async () => publicUser), + createSession: vi.fn(async () => 'session-123'), + findUserBySession: vi.fn(async () => null), + deleteSession: vi.fn(async () => undefined), + ...overrides, + }; +} + +function createPasswordHasher(): PasswordHasher { + return { + hash: vi.fn(async (password) => `hashed:${password}`), + + verify: vi.fn( + async (passwordHash, password) => passwordHash === `hashed:${password}`, + ), + }; +} + +describe('authService', () => { + it('registers a user and returns a session', async () => { + const repository = createRepository(); + const passwordHasher = createPasswordHasher(); + + const service = createAuthService(repository, passwordHasher); + + const result = await service.register( + ' Hasan ', + ' HASAN@EXAMPLE.COM ', + 'secret123', + ); + + expect(result).toEqual({ + user: publicUser, + sessionToken: 'session-123', + }); + + expect(repository.createUserWithSession).toHaveBeenCalledWith( + 'Hasan', + 'hasan@example.com', + 'hashed:secret123', + expect.any(Date), + ); + }); + + it('rejects registration when the email already exists', async () => { + const repository = createRepository({ + findUserByEmail: vi.fn(async () => storedUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect( + service.register('Hasan', 'hasan@example.com', 'secret123'), + ).rejects.toThrow('An account with this email already exists.'); + + expect(repository.createUserWithSession).not.toHaveBeenCalled(); + expect(repository.createSession).not.toHaveBeenCalled(); + }); + + it('logs in with the correct password', async () => { + const repository = createRepository({ + findUserByEmail: vi.fn(async () => storedUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + const result = await service.login('HASAN@EXAMPLE.COM', 'secret123'); + + expect(result).toEqual({ + user: publicUser, + sessionToken: 'session-123', + }); + + expect(repository.createSession).toHaveBeenCalled(); + }); + + it('rejects login with an incorrect password', async () => { + const repository = createRepository({ + findUserByEmail: vi.fn(async () => storedUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect( + service.login('hasan@example.com', 'wrong-password'), + ).rejects.toThrow('Invalid email or password.'); + + expect(repository.createSession).not.toHaveBeenCalled(); + }); + + it('restores the current user from a session', async () => { + const repository = createRepository({ + findUserBySession: vi.fn(async () => publicUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect(service.currentUser('session-123')).resolves.toEqual( + publicUser, + ); + + expect(repository.findUserBySession).toHaveBeenCalledWith('session-123'); + }); + + it('deletes the session when signing out', async () => { + const repository = createRepository(); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect(service.signOut('session-123')).resolves.toBe(true); + + expect(repository.deleteSession).toHaveBeenCalledWith('session-123'); + }); +}); diff --git a/apps/api/src/features/auth/authService.ts b/apps/api/src/features/auth/authService.ts new file mode 100644 index 0000000..f151da2 --- /dev/null +++ b/apps/api/src/features/auth/authService.ts @@ -0,0 +1,132 @@ +import { GraphQLError } from 'graphql'; +import { hash, verify } from 'argon2'; + +import { + authRepository, + type AuthRepository, + type PublicUser, +} from './authRepository.js'; + +const SESSION_DURATION_MS = 7 * 24 * 60 * 60 * 1000; + +export interface AuthPayload { + user: PublicUser; + sessionToken: string; +} + +export interface PasswordHasher { + hash(password: string): Promise; + verify(passwordHash: string, password: string): Promise; +} + +const argonPasswordHasher: PasswordHasher = { + hash, + verify, +}; + +export interface AuthService { + register(name: string, email: string, password: string): Promise; + + login(email: string, password: string): Promise; + + currentUser(sessionToken: string): Promise; + + signOut(sessionToken: string): Promise; +} + +export function createAuthService( + repository: AuthRepository = authRepository, + passwordHasher: PasswordHasher = argonPasswordHasher, +): AuthService { + return { + async register(name, email, password) { + const normalizedName = name.trim(); + const normalizedEmail = email.trim().toLowerCase(); + + if (normalizedName.length < 2) { + throw new GraphQLError('Name must contain at least 2 characters.'); + } + + if (!normalizedEmail.includes('@')) { + throw new GraphQLError('Enter a valid email address.'); + } + + if (password.length < 6) { + throw new GraphQLError('Password must contain at least 6 characters.'); + } + + const existingUser = await repository.findUserByEmail(normalizedEmail); + + if (existingUser) { + throw new GraphQLError('An account with this email already exists.'); + } + + const passwordHash = await passwordHasher.hash(password); + + const expiresAt = new Date(Date.now() + SESSION_DURATION_MS); + const { user, sessionToken } = await repository.createUserWithSession( + normalizedName, + normalizedEmail, + passwordHash, + expiresAt, + ); + + return { + user, + sessionToken, + }; + }, + + async login(email, password) { + const normalizedEmail = email.trim().toLowerCase(); + + const user = await repository.findUserByEmail(normalizedEmail); + + if (!user) { + throw new GraphQLError('Invalid email or password.'); + } + + const passwordIsCorrect = await passwordHasher.verify( + user.passwordHash, + password, + ); + + if (!passwordIsCorrect) { + throw new GraphQLError('Invalid email or password.'); + } + + const expiresAt = new Date(Date.now() + SESSION_DURATION_MS); + + const sessionToken = await repository.createSession(user.id, expiresAt); + + return { + user: { + id: user.id, + name: user.name, + email: user.email, + }, + sessionToken, + }; + }, + + async currentUser(sessionToken) { + if (!sessionToken.trim()) { + return null; + } + + return repository.findUserBySession(sessionToken); + }, + + async signOut(sessionToken) { + if (!sessionToken.trim()) { + return false; + } + + await repository.deleteSession(sessionToken); + + return true; + }, + }; +} + +export const authService = createAuthService(); diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index f8645bc..8d4e30c 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -2,6 +2,9 @@ import type { GraphQLResolveInfo } from 'graphql'; export type Maybe = T | null; export type InputMaybe = Maybe; +export type RequireFields = Omit & { + [P in K]-?: NonNullable; +}; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: { input: string; output: string }; @@ -11,9 +14,49 @@ export type Scalars = { Float: { input: number; output: number }; }; +export type User = { + __typename?: 'User'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; + email: Scalars['String']['output']; +}; + +export type AuthPayload = { + __typename?: 'AuthPayload'; + user: User; + sessionToken: Scalars['String']['output']; +}; + export type Query = { __typename?: 'Query'; health: Scalars['String']['output']; + currentUser?: Maybe; +}; + +export type QueryCurrentUserArgs = { + sessionToken: Scalars['String']['input']; +}; + +export type Mutation = { + __typename?: 'Mutation'; + register: AuthPayload; + login: AuthPayload; + signOut: Scalars['Boolean']['output']; +}; + +export type MutationRegisterArgs = { + name: Scalars['String']['input']; + email: Scalars['String']['input']; + password: Scalars['String']['input']; +}; + +export type MutationLoginArgs = { + email: Scalars['String']['input']; + password: Scalars['String']['input']; +}; + +export type MutationSignOutArgs = { + sessionToken: Scalars['String']['input']; }; export type ResolverTypeWrapper = Promise | T; @@ -135,26 +178,87 @@ export type DirectiveResolverFn< /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { - Query: ResolverTypeWrapper>; + User: ResolverTypeWrapper; + ID: ResolverTypeWrapper; String: ResolverTypeWrapper; + AuthPayload: ResolverTypeWrapper; + Query: ResolverTypeWrapper>; + Mutation: ResolverTypeWrapper>; Boolean: ResolverTypeWrapper; }; /** Mapping between all available schema types and the resolvers parents */ export type ResolversParentTypes = { - Query: Record; + User: User; + ID: Scalars['ID']['output']; String: Scalars['String']['output']; + AuthPayload: AuthPayload; + Query: Record; + Mutation: Record; Boolean: Scalars['Boolean']['output']; }; +export type UserResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['User'] = ResolversParentTypes['User'], +> = { + id?: Resolver; + name?: Resolver; + email?: Resolver; +}; + +export type AuthPayloadResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['AuthPayload'] = ResolversParentTypes['AuthPayload'], +> = { + user?: Resolver; + sessionToken?: Resolver; +}; + export type QueryResolvers< ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query'], > = { health?: Resolver; + currentUser?: Resolver< + Maybe, + ParentType, + ContextType, + RequireFields + >; +}; + +export type MutationResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation'], +> = { + register?: Resolver< + ResolversTypes['AuthPayload'], + ParentType, + ContextType, + RequireFields + >; + login?: Resolver< + ResolversTypes['AuthPayload'], + ParentType, + ContextType, + RequireFields + >; + signOut?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; }; export type Resolvers = { + User?: UserResolvers; + AuthPayload?: AuthPayloadResolvers; Query?: QueryResolvers; + Mutation?: MutationResolvers; }; diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index 6cf08a8..c2cb462 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -1,3 +1,21 @@ +type User { + id: ID! + name: String! + email: String! +} + +type AuthPayload { + user: User! + sessionToken: String! +} + type Query { health: String! + currentUser(sessionToken: String!): User +} + +type Mutation { + register(name: String!, email: String!, password: String!): AuthPayload! + login(email: String!, password: String!): AuthPayload! + signOut(sessionToken: String!): Boolean! } diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index acd747d..eb0b9c4 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,37 +1,40 @@ +import { useEffect } from 'react'; +import { useAppStore } from './store'; + import { Route, Routes } from 'react-router-dom'; import AppShell from './components/shell/AppShell/AppShell'; -import RouteDestination from './components/RouteDestination/RouteDestination'; import LoginPage from './features/auth/LoginPage'; import RegisterPage from './features/auth/RegisterPage'; +import RequireAuth from './features/auth/RequireAuth'; import ExplorePage from './features/explore/ExplorePage'; - -const pages = [ - ['/cookbook', 'My Cookbook'], - ['/recipes/new', 'Add Recipe'], -] as const; +import CookbookPage from './features/cookbook/CookbookPage'; +import RecipeCreatePage from './features/recipes/RecipeCreatePage'; +import RecipeDetailPage from './features/recipe-detail/RecipeDetailPage'; +import NotFoundPage from './features/not-found/NotFoundPage'; export function App() { + const restoreSession = useAppStore((state) => state.restoreSession); + + useEffect(() => { + void restoreSession(); + }, [restoreSession]); + return ( }> } /> - - {pages.map(([path, title]) => ( - } - /> - ))} - } - /> + }> + } /> + } /> + + } /> } /> } /> + + } /> ); diff --git a/apps/web/src/assets/illustrations/not-found-chef-hat.png b/apps/web/src/assets/illustrations/not-found-chef-hat.png new file mode 100644 index 0000000..e12b2d4 Binary files /dev/null and b/apps/web/src/assets/illustrations/not-found-chef-hat.png differ diff --git a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx index 9aa4e3e..9d7584c 100644 --- a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx +++ b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx @@ -1,5 +1,5 @@ import { useState, type ComponentPropsWithoutRef, type ReactNode } from 'react'; -import { Link } from 'react-router-dom'; +import { Link, useLocation } from 'react-router-dom'; import fallbackRecipeImage from '../../../assets/recipe-fallback.png'; import { HeartIcon } from '../../../icons/actions'; @@ -109,6 +109,8 @@ export default function RecipeCard({ className = '', ...articleProps }: RecipeCardProps) { + const location = useLocation(); + const [confirmUnsaveOpen, setConfirmUnsaveOpen] = useState(false); const classes = ['recipe-card', className].filter(Boolean).join(' '); @@ -152,6 +154,11 @@ export default function RecipeCard({ size="sm" aria-pressed={saved} onClick={handleSaveButtonClick} + aria-label={ + saved + ? `Remove ${title} from My Cookbook` + : `Save ${title} to My Cookbook` + } >

- + {title}

diff --git a/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.css b/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.css new file mode 100644 index 0000000..02572d3 --- /dev/null +++ b/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.css @@ -0,0 +1,79 @@ +@layer components { + .recipe-rating-input { + margin: 0; + padding: 0; + + border: 0; + } + + .recipe-rating-input__legend { + margin-block-end: var(--space-3); + + color: var(--color-text-primary); + + font-size: var(--font-size-sm); + font-weight: var(--font-weight-semibold); + } + + .recipe-rating-input__options { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + } + + .recipe-rating-input__option { + position: relative; + + display: inline-flex; + align-items: center; + justify-content: center; + + width: var(--target-size-min); + height: var(--target-size-min); + + color: var(--color-brand-primary); + background-color: var(--color-surface); + + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-md); + + cursor: pointer; + + transition: + color var(--duration-fast) var(--ease-standard), + background-color var(--duration-fast) var(--ease-standard), + border-color var(--duration-fast) var(--ease-standard), + box-shadow var(--duration-fast) var(--ease-standard); + } + + .recipe-rating-input__option:hover { + background-color: var(--color-surface-hover); + border-color: var(--color-brand-primary); + } + + .recipe-rating-input__option:has(.recipe-rating-input__control:checked) { + background-color: var(--color-brand-accent-soft); + border-color: var(--color-brand-primary); + } + + .recipe-rating-input__option:has( + .recipe-rating-input__control:focus-visible + ) { + outline: var(--border-width-medium) solid var(--color-focus-ring); + outline-offset: 2px; + } + + .recipe-rating-input__control { + position: absolute; + + width: 1px; + height: 1px; + + opacity: 0; + pointer-events: none; + } + + .recipe-rating-input__star { + display: inline-flex; + } +} diff --git a/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.tsx b/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.tsx new file mode 100644 index 0000000..a279813 --- /dev/null +++ b/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.tsx @@ -0,0 +1,61 @@ +import { StarIcon } from '../../../icons/rating'; +import { Icon } from '../../ui/Icon/Icon'; + +import './RecipeRatingInput.css'; + +export type RecipeRatingInputProps = { + value: number; + onChange: (value: number) => void; + name?: string; + label?: string; +}; + +const STAR_VALUES = [1, 2, 3, 4, 5] as const; + +/** + * Accessible 1–5 star input used when a user rates a recipe. + * + * The native radio inputs keep normal form and keyboard semantics while the + * labels provide the visual star controls. + */ +export default function RecipeRatingInput({ + value, + onChange, + name = 'recipe-rating', + label = 'Your rating', +}: RecipeRatingInputProps) { + return ( +
+ {label} + +
+ {STAR_VALUES.map((starValue) => ( + + ))} +
+
+ ); +} diff --git a/apps/web/src/components/recipe/__tests__/RecipeCard.test.tsx b/apps/web/src/components/recipe/__tests__/RecipeCard.test.tsx index 6e7103e..ac78a8b 100644 --- a/apps/web/src/components/recipe/__tests__/RecipeCard.test.tsx +++ b/apps/web/src/components/recipe/__tests__/RecipeCard.test.tsx @@ -1,7 +1,7 @@ import { type ComponentProps } from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { MemoryRouter } from 'react-router-dom'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { describe, expect, it, vi } from 'vitest'; import RecipeCard from '../RecipeCard/RecipeCard'; @@ -34,6 +34,16 @@ function renderRecipeCard(props: ComponentProps) { ); } +function LocationStateProbe() { + const location = useLocation(); + + return ( + + {JSON.stringify(location.state)} + + ); +} + describe('RecipeCard', () => { it('exposes the recipe link and accessible rating summary', () => { renderRecipeCard(baseProps); @@ -51,6 +61,32 @@ describe('RecipeCard', () => { ).toBeTruthy(); }); + it('keeps the exact browse URL as recipe navigation state', async () => { + const user = userEvent.setup(); + + render( + + + } /> + + } /> + + , + ); + + await user.click( + screen.getByRole('link', { + name: 'Spaghetti Carbonara', + }), + ); + + expect(screen.getByTestId('recipe-location-state').textContent).toBe( + JSON.stringify({ + from: '/?q=pasta&category=dinner&page=2', + }), + ); + }); + it('renders structured cooking time and servings metadata', () => { renderRecipeCard(baseProps); @@ -73,7 +109,7 @@ describe('RecipeCard', () => { }); const saveButton = screen.getByRole('button', { - name: 'Save', + name: /^Save .* to My Cookbook$/, }); await user.tab(); @@ -97,7 +133,7 @@ describe('RecipeCard', () => { }); const saveButton = screen.getByRole('button', { - name: 'Save', + name: /^Save .* to My Cookbook$/, }); expect(saveButton.getAttribute('aria-pressed')).toBe('false'); @@ -121,7 +157,7 @@ describe('RecipeCard', () => { }); const savedButton = screen.getByRole('button', { - name: 'Saved', + name: /^Remove .* from My Cookbook$/, }); expect(savedButton.getAttribute('aria-pressed')).toBe('true'); @@ -156,7 +192,7 @@ describe('RecipeCard', () => { await user.click( screen.getByRole('button', { - name: 'Saved', + name: /^Remove .* from My Cookbook$/, }), ); @@ -174,13 +210,13 @@ describe('RecipeCard', () => { expect( screen.queryByRole('button', { - name: 'Save', + name: /^Save .* to My Cookbook$/, }), ).toBeNull(); expect( screen.queryByRole('button', { - name: 'Saved', + name: /^Remove .* from My Cookbook$/, }), ).toBeNull(); }); @@ -201,7 +237,7 @@ describe('RecipeCard', () => { expect( screen.queryByRole('button', { - name: 'Saved', + name: /^Remove .* from My Cookbook$/, }), ).toBeNull(); }); diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.css b/apps/web/src/components/shell/SiteHeader/SiteHeader.css index 89a550b..9dabf39 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.css +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.css @@ -19,30 +19,10 @@ display: inline-flex; flex: 0 0 auto; align-items: center; - gap: var(--space-3); - color: var(--color-text-primary); - font-size: var(--font-size-lg); - font-weight: var(--font-weight-bold); + margin-right: var(--space-3); text-decoration: none; } - .brand:hover { - color: var(--color-text-primary); - } - - .brand__mark { - display: grid; - flex: 0 0 auto; - place-items: center; - width: 2.25rem; - height: 2.25rem; - border-radius: var(--radius-md); - color: var(--color-text-inverse); - background-color: var(--color-brand-primary); - font-family: Georgia, serif; - font-size: var(--font-size-xl); - } - .site-header__controls { display: flex; flex: 1 1 auto; @@ -56,7 +36,7 @@ .account-navigation { display: flex; align-items: center; - gap: var(--space-2); + gap: var(--space-4); } .primary-navigation__link, @@ -180,6 +160,6 @@ display: inline-flex; align-items: center; gap: var(--space-2); - font-weight: 600; + font-weight: var(--font-weight-semibold); } } diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx new file mode 100644 index 0000000..37844c4 --- /dev/null +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx @@ -0,0 +1,117 @@ +import '@testing-library/jest-dom/vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { MemoryRouter } from 'react-router-dom'; + +import { signOutUser } from '../../../features/auth/authApi'; +import { useAppStore } from '../../../store'; +import SiteHeader from './SiteHeader'; + +vi.mock('../../../features/auth/authApi', () => ({ + loginUser: vi.fn(), + registerUser: vi.fn(), + getCurrentUser: vi.fn(), + signOutUser: vi.fn(), +})); + +const authenticatedUser = { + id: 'user-123', + name: 'Hasan', + email: 'hasan@example.com', +}; + +function renderHeader() { + return render( + + + , + ); +} + +describe('SiteHeader authentication', () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + + useAppStore.setState({ + currentUser: null, + }); + }); + + it('shows login and registration links when signed out', () => { + renderHeader(); + + expect( + screen.getByRole('link', { + name: 'Log in', + }), + ).toBeInTheDocument(); + + expect( + screen.getByRole('link', { + name: 'Register', + }), + ).toBeInTheDocument(); + + expect( + screen.queryByRole('button', { + name: 'Sign out', + }), + ).not.toBeInTheDocument(); + }); + + it('shows the current user when signed in', () => { + useAppStore.setState({ + currentUser: authenticatedUser, + }); + + renderHeader(); + + expect(screen.getByText('Hasan')).toBeInTheDocument(); + + expect( + screen.getByRole('button', { + name: 'Sign out', + }), + ).toBeInTheDocument(); + + expect( + screen.queryByRole('link', { + name: 'Log in', + }), + ).not.toBeInTheDocument(); + }); + + it('updates the header after signing out', async () => { + localStorage.setItem('recipe-platform-session-token', 'session-123'); + + useAppStore.setState({ + currentUser: authenticatedUser, + }); + + vi.mocked(signOutUser).mockResolvedValue(true); + + const user = userEvent.setup(); + + renderHeader(); + + await user.click( + screen.getByRole('button', { + name: 'Sign out', + }), + ); + + await waitFor(() => { + expect( + screen.getByRole('link', { + name: 'Log in', + }), + ).toBeInTheDocument(); + }); + + expect(signOutUser).toHaveBeenCalledWith('session-123'); + + expect(useAppStore.getState().currentUser).toBeNull(); + }); +}); diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx index d32c1b4..6b68e13 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx @@ -12,11 +12,14 @@ import { useAppStore } from '../../../store'; import Button from '../../ui/Button/Button'; import IconButton from '../../ui/IconButton/IconButton'; import './SiteHeader.css'; +import LogoMark from '../../brand/LogoMark/LogoMark'; +import LinkButton from '../../ui/LinkButton/LinkButton'; +import { Icon } from '../../ui/Icon/Icon'; const pages = [ - ['/', 'Explore', HomeIcon], - ['/cookbook', 'My Cookbook', CookbookIcon], - ['/recipes/new', 'Add Recipe', AddRecipeIcon], + { to: '/', label: 'Explore', icon: HomeIcon }, + { to: '/cookbook', label: 'My Cookbook', icon: CookbookIcon }, + { to: '/recipes/new', label: 'Add Recipe', icon: AddRecipeIcon }, ] as const; function SiteHeader() { @@ -28,8 +31,8 @@ function SiteHeader() { const closeMenu = () => setMenuOpen(false); - const handleSignOut = () => { - signOut(); + const handleSignOut = async () => { + await signOut(); closeMenu(); navigate('/'); }; @@ -37,11 +40,13 @@ function SiteHeader() { return (
- - - Recipe Platform + + - +
diff --git a/apps/web/src/components/ui/LinkButton/LinkButton.tsx b/apps/web/src/components/ui/LinkButton/LinkButton.tsx new file mode 100644 index 0000000..a1365af --- /dev/null +++ b/apps/web/src/components/ui/LinkButton/LinkButton.tsx @@ -0,0 +1,46 @@ +import type { ReactNode } from 'react'; +import { NavLink, type NavLinkProps } from 'react-router-dom'; + +import type { ButtonSize, ButtonVariant } from '../Button/Button'; +import '../Button/Button.css'; + +export type LinkButtonProps = Omit & { + children: ReactNode; + variant?: ButtonVariant; + size?: ButtonSize; + wide?: boolean; + className?: string; + activeClassName?: string; +}; + +function LinkButton({ + children, + variant = 'primary', + size = 'md', + wide = false, + className = '', + activeClassName = '', + ...props +}: LinkButtonProps) { + return ( + + [ + 'button', + `button--${variant}`, + `button--${size}`, + wide && 'button--wide', + className, + isActive && activeClassName, + ] + .filter(Boolean) + .join(' ') + } + {...props} + > + {children} + + ); +} + +export default LinkButton; diff --git a/apps/web/src/components/ui/Select/Select.css b/apps/web/src/components/ui/Select/Select.css index 9a409b2..dee784e 100644 --- a/apps/web/src/components/ui/Select/Select.css +++ b/apps/web/src/components/ui/Select/Select.css @@ -82,6 +82,12 @@ box-shadow var(--duration-fast) var(--ease-standard); } + .select__control--with-leading-icon { + padding-inline-start: calc( + var(--space-3) + var(--icon-size-sm) + var(--space-2) + ); + } + .select--full .select__control { width: 100%; } @@ -118,6 +124,24 @@ cursor: not-allowed; } + /* Leading icon */ + + .select__leading-icon { + position: absolute; + z-index: 1; + top: 50%; + left: var(--space-3); + + width: var(--icon-size-sm); + height: var(--icon-size-sm); + + color: var(--color-icon-secondary); + + pointer-events: none; + + transform: translateY(-50%); + } + /* Chevron */ .select__icon { diff --git a/apps/web/src/components/ui/Select/Select.tsx b/apps/web/src/components/ui/Select/Select.tsx index dbaa696..99bfa95 100644 --- a/apps/web/src/components/ui/Select/Select.tsx +++ b/apps/web/src/components/ui/Select/Select.tsx @@ -1,6 +1,8 @@ -import type { ComponentPropsWithRef, ReactNode } from 'react'; +import type { ComponentPropsWithRef, ComponentType, ReactNode } from 'react'; import { ChevronDownIcon } from '../../../icons/navigation'; +import type { IconProps as SvgIconProps } from '../../../icons/types'; + import { Icon } from '../Icon/Icon'; import { FieldError, FieldHelp, RequiredMarker } from '../internal/FieldText'; import { useFieldA11y } from '../internal/fieldA11y'; @@ -13,6 +15,8 @@ export type SelectProps = Omit< 'size' | 'width' > & { label: ReactNode; + labelVisuallyHidden?: boolean; + leadingIcon?: ComponentType; helpText?: ReactNode; error?: ReactNode; children: ReactNode; @@ -21,6 +25,8 @@ export type SelectProps = Omit< function Select({ label, + labelVisuallyHidden = false, + leadingIcon: LeadingIcon, helpText, error, children, @@ -40,8 +46,10 @@ function Select({ }); const wrapperClasses = ['select', `select--${width}`].join(' '); + const selectClasses = [ 'select__control', + LeadingIcon && 'select__control--with-leading-icon', error && 'select__control--error', className, ] @@ -50,12 +58,27 @@ function Select({ return (
-
diff --git a/apps/web/src/features/auth/RegisterPage.tsx b/apps/web/src/features/auth/RegisterPage.tsx index 74e9d00..239fc72 100644 --- a/apps/web/src/features/auth/RegisterPage.tsx +++ b/apps/web/src/features/auth/RegisterPage.tsx @@ -1,9 +1,11 @@ import { useState, type FormEvent } from 'react'; -import { Link, useNavigate } from 'react-router-dom'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; import Button from '../../components/ui/Button/Button'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; import Field from '../../components/ui/Field/Field'; import { useAppStore } from '../../store'; +import { getAuthReturnPath } from './authNavigation'; import './AuthPage.css'; interface RegisterErrors { @@ -15,6 +17,8 @@ interface RegisterErrors { function RegisterPage() { const navigate = useNavigate(); + const location = useLocation(); + const returnPath = getAuthReturnPath(location.state); const register = useAppStore((state) => state.register); const [name, setName] = useState(''); @@ -23,8 +27,13 @@ function RegisterPage() { const [confirmPassword, setConfirmPassword] = useState(''); const [errors, setErrors] = useState({}); - const handleSubmit = (event: FormEvent) => { + const [submitError, setSubmitError] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleSubmit = async (event: FormEvent) => { event.preventDefault(); + if (isSubmitting) return; + setSubmitError(''); const nextErrors: RegisterErrors = {}; @@ -56,8 +65,19 @@ function RegisterPage() { return; } - register(name.trim(), email.trim()); - navigate('/'); + setIsSubmitting(true); + try { + await register(name.trim(), email.trim(), password); + navigate(returnPath, { replace: true }); + } catch (error) { + setSubmitError( + error instanceof Error + ? error.message + : 'Something went wrong. Please try again.', + ); + } finally { + setIsSubmitting(false); + } }; return ( @@ -66,7 +86,7 @@ function RegisterPage() {

Recipe Platform

Register

- Create a mock account to save and manage recipes. + Create an account to save and manage recipes.

@@ -115,17 +135,25 @@ function RegisterPage() { onChange={(event) => setConfirmPassword(event.target.value)} /> -

- Already have an account? Log in -

- -

- This prototype uses mock authentication. Do not enter a real password. + Already have an account?{' '} + + Log in +

diff --git a/apps/web/src/features/auth/RequireAuth.test.tsx b/apps/web/src/features/auth/RequireAuth.test.tsx new file mode 100644 index 0000000..3422aea --- /dev/null +++ b/apps/web/src/features/auth/RequireAuth.test.tsx @@ -0,0 +1,163 @@ +import '@testing-library/jest-dom/vitest'; +import { StrictMode } from 'react'; +import { act, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, useLocation } from 'react-router-dom'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { App } from '../../App'; +import { useAppStore } from '../../store'; +import { getCurrentUser, loginUser, registerUser } from './authApi'; + +vi.mock('./authApi', () => ({ + getCurrentUser: vi.fn(), + loginUser: vi.fn(), + registerUser: vi.fn(), + signOutUser: vi.fn(), +})); +const user = { id: 'user-123', name: 'Hasan', email: 'hasan@example.com' }; +const tokenKey = 'recipe-platform-session-token'; +function LocationProbe() { + const location = useLocation(); + return ( + + {location.pathname + location.search + location.hash} + + ); +} +function renderApp(path: string) { + return render( + + + + + + , + ); +} +function pendingSession() { + let resolve!: (value: typeof user | null) => void; + const promise = new Promise((done) => { + resolve = done; + }); + vi.mocked(getCurrentUser).mockReturnValue(promise); + return resolve; +} +beforeEach(() => { + vi.resetAllMocks(); + localStorage.clear(); + useAppStore.setState({ currentUser: null, sessionStatus: 'restoring' }); +}); +describe('protected routes with session restoration', () => { + it.each(['/cookbook', '/recipes/new'])( + 'redirects a logged-out visitor from %s', + async (path) => { + renderApp(path); + expect( + await screen.findByRole('heading', { name: 'Log in' }), + ).toBeInTheDocument(); + expect(screen.getByTestId('location')).toHaveTextContent('/login'); + }, + ); + it.each([ + ['/cookbook', 'My Cookbook'], + ['/recipes/new', 'Add Recipe'], + ])( + 'waits on refresh of %s and renders after validation', + async (path, title) => { + localStorage.setItem(tokenKey, 'valid-token'); + const resolve = pendingSession(); + renderApp(path!); + expect(screen.getByText('Restoring your session...')).toHaveTextContent( + 'Restoring your session', + ); + expect( + screen.queryByRole('heading', { name: 'Log in' }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole('heading', { name: title }), + ).not.toBeInTheDocument(); + expect(screen.getByTestId('location')).toHaveTextContent(path!); + await act(async () => resolve(user)); + expect( + await screen.findByRole('heading', { name: title }), + ).toBeInTheDocument(); + expect(useAppStore.getState().sessionStatus).toBe('authenticated'); + }, + ); + it('redirects only after the API confirms expiry', async () => { + localStorage.setItem(tokenKey, 'expired-token'); + const resolve = pendingSession(); + renderApp('/cookbook'); + expect(screen.getByTestId('location')).toHaveTextContent('/cookbook'); + await act(async () => resolve(null)); + expect( + await screen.findByRole('heading', { name: 'Log in' }), + ).toBeInTheDocument(); + expect(localStorage.getItem(tokenKey)).toBeNull(); + }); + it('keeps the token and protected URL during an outage and permits retry', async () => { + localStorage.setItem(tokenKey, 'valid-token'); + vi.mocked(getCurrentUser).mockRejectedValue(new Error('Offline')); + renderApp('/recipes/new'); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Unable to restore your session', + ); + expect(screen.getByTestId('location')).toHaveTextContent('/recipes/new'); + expect( + screen.queryByRole('heading', { name: 'Add Recipe' }), + ).not.toBeInTheDocument(); + expect(localStorage.getItem(tokenKey)).toBe('valid-token'); + vi.mocked(getCurrentUser).mockResolvedValue(user); + await userEvent + .setup() + .click(screen.getByRole('button', { name: 'Try again' })); + expect( + await screen.findByRole('heading', { name: 'Add Recipe' }), + ).toBeInTheDocument(); + }); + it.each([false, true])( + 'returns to the requested URL after authentication (register=%s)', + async (register) => { + vi.mocked(loginUser).mockResolvedValue({ + user, + sessionToken: 'new-token', + }); + vi.mocked(registerUser).mockResolvedValue({ + user, + sessionToken: 'new-token', + }); + const interaction = userEvent.setup(); + renderApp('/cookbook?view=saved#recipes'); + await screen.findByRole('heading', { name: 'Log in' }); + if (register) { + const links = screen.getAllByRole('link', { name: 'Register' }); + await interaction.click(links[links.length - 1]!); + await interaction.type(screen.getByLabelText(/^Name/), 'Hasan'); + await interaction.type( + screen.getByLabelText(/^Confirm password/), + 'secret123', + ); + } + await interaction.type(screen.getByLabelText(/^Email/), user.email); + await interaction.type(screen.getByLabelText(/^Password/), 'secret123'); + await interaction.click( + screen.getByRole('button', { name: register ? 'Register' : 'Log in' }), + ); + expect( + await screen.findByRole('heading', { name: 'My Cookbook' }), + ).toBeInTheDocument(); + expect(screen.getByTestId('location')).toHaveTextContent( + '/cookbook?view=saved#recipes', + ); + }, + ); + it('leaves Explore public during session restoration', () => { + localStorage.setItem(tokenKey, 'valid-token'); + pendingSession(); + renderApp('/'); + expect( + screen.getByRole('searchbox', { name: 'Search recipes' }), + ).toBeInTheDocument(); + expect(screen.getByTestId('location')).toHaveTextContent('/'); + }); +}); diff --git a/apps/web/src/features/auth/RequireAuth.tsx b/apps/web/src/features/auth/RequireAuth.tsx new file mode 100644 index 0000000..b1c8dcb --- /dev/null +++ b/apps/web/src/features/auth/RequireAuth.tsx @@ -0,0 +1,33 @@ +import { Navigate, Outlet, useLocation } from 'react-router-dom'; +import Button from '../../components/ui/Button/Button'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; +import { useAppStore } from '../../store'; + +export default function RequireAuth() { + const location = useLocation(); + const sessionStatus = useAppStore((state) => state.sessionStatus); + const currentUser = useAppStore((state) => state.currentUser); + const restoreSession = useAppStore((state) => state.restoreSession); + + if (sessionStatus === 'restoring') { + return

Restoring your session...

; + } + if (sessionStatus === 'error') { + return ( +
+ + Unable to restore your session. Check your connection and try again. + + +
+ ); + } + if (sessionStatus === 'authenticated' && currentUser) return ; + return ( + + ); +} diff --git a/apps/web/src/features/auth/authApi.test.ts b/apps/web/src/features/auth/authApi.test.ts new file mode 100644 index 0000000..6838268 --- /dev/null +++ b/apps/web/src/features/auth/authApi.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { getCurrentUser, loginUser, registerUser } from './authApi'; + +afterEach(() => vi.unstubAllGlobals()); +const requests = [ + () => loginUser('a@example.com', 'secret123'), + () => registerUser('Hasan', 'a@example.com', 'secret123'), +]; + +describe('authentication API errors', () => { + it.each(requests)('translates network failures', async (request) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockRejectedValue(new TypeError('Failed to fetch')), + ); + await expect(request()).rejects.toThrow( + 'Unable to connect. Check your connection and try again.', + ); + }); + it.each(requests)('translates HTTP failures', async (request) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response('', { status: 503 })), + ); + await expect(request()).rejects.toThrow( + 'Authentication is temporarily unavailable. Please try again.', + ); + }); + it.each([ + 'Invalid email or password.', + 'An account with this email already exists.', + ])('preserves expected API errors: %s', async (message) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(Response.json({ errors: [{ message }] })), + ); + await expect(loginUser('a@example.com', 'secret123')).rejects.toThrow( + message, + ); + }); + it('does not expose internal server messages', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + Response.json({ + errors: [{ message: 'Database connection details' }], + }), + ), + ); + await expect(loginUser('a@example.com', 'secret123')).rejects.toThrow( + 'Authentication is temporarily unavailable. Please try again.', + ); + }); + it('rejects GraphQL errors even when currentUser is null', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + Response.json({ + data: { currentUser: null }, + errors: [{ message: 'Database unavailable' }], + }), + ), + ); + await expect(getCurrentUser('session-123')).rejects.toThrow(); + }); +}); diff --git a/apps/web/src/features/auth/authApi.ts b/apps/web/src/features/auth/authApi.ts new file mode 100644 index 0000000..9b732ca --- /dev/null +++ b/apps/web/src/features/auth/authApi.ts @@ -0,0 +1,176 @@ +import type { User } from '../../types/user'; + +const GRAPHQL_URL = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; + +interface GraphQLResponse { + data?: TData; + errors?: Array<{ + message: string; + }>; +} + +interface AuthPayload { + user: User; + sessionToken: string; +} + +async function graphqlRequest( + query: string, + variables: Record, +): Promise { + let response: Response; + try { + response = await fetch(GRAPHQL_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query, + variables, + }), + }); + } catch { + throw new Error('Unable to connect. Check your connection and try again.'); + } + + if (!response.ok) { + throw new Error( + 'Authentication is temporarily unavailable. Please try again.', + ); + } + + const result = (await response.json()) as GraphQLResponse; + + const error = result.errors?.[0]; + + if (error) { + const expectedMessages = [ + 'Invalid email or password.', + 'An account with this email already exists.', + 'Name must contain at least 2 characters.', + 'Enter a valid email address.', + 'Password must contain at least 6 characters.', + ]; + throw new Error( + expectedMessages.includes(error.message) + ? error.message + : 'Authentication is temporarily unavailable. Please try again.', + ); + } + + if (!result.data) { + throw new Error('Authentication response did not contain data.'); + } + + return result.data; +} + +export async function registerUser( + name: string, + email: string, + password: string, +): Promise { + const data = await graphqlRequest<{ + register: AuthPayload; + }>( + ` + mutation Register( + $name: String! + $email: String! + $password: String! + ) { + register( + name: $name + email: $email + password: $password + ) { + sessionToken + user { + id + name + email + } + } + } + `, + { + name, + email, + password, + }, + ); + + return data.register; +} + +export async function loginUser( + email: string, + password: string, +): Promise { + const data = await graphqlRequest<{ + login: AuthPayload; + }>( + ` + mutation Login( + $email: String! + $password: String! + ) { + login(email: $email, password: $password) { + sessionToken + user { + id + name + email + } + } + } + `, + { + email, + password, + }, + ); + + return data.login; +} + +export async function getCurrentUser( + sessionToken: string, +): Promise { + const data = await graphqlRequest<{ + currentUser: User | null; + }>( + ` + query CurrentUser($sessionToken: String!) { + currentUser(sessionToken: $sessionToken) { + id + name + email + } + } + `, + { + sessionToken, + }, + ); + + return data.currentUser; +} + +export async function signOutUser(sessionToken: string): Promise { + const data = await graphqlRequest<{ + signOut: boolean; + }>( + ` + mutation SignOut($sessionToken: String!) { + signOut(sessionToken: $sessionToken) + } + `, + { + sessionToken, + }, + ); + + return data.signOut; +} diff --git a/apps/web/src/features/auth/authNavigation.test.ts b/apps/web/src/features/auth/authNavigation.test.ts new file mode 100644 index 0000000..ac187dc --- /dev/null +++ b/apps/web/src/features/auth/authNavigation.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { getAuthReturnPath } from './authNavigation'; +describe('authentication return navigation', () => { + it.each([ + null, + {}, + { from: 'https://example.com' }, + { from: '//example.com' }, + { from: '/login' }, + { from: '/cookbook\\evil' }, + ])('falls back for unsafe or unsupported state %j', (state) => { + expect(getAuthReturnPath(state)).toBe('/'); + }); + it.each(['/cookbook?view=saved#recipes', '/recipes/new'])( + 'preserves protected destination %s', + (from) => { + expect(getAuthReturnPath({ from })).toBe(from); + }, + ); +}); diff --git a/apps/web/src/features/auth/authNavigation.ts b/apps/web/src/features/auth/authNavigation.ts new file mode 100644 index 0000000..2d4ef38 --- /dev/null +++ b/apps/web/src/features/auth/authNavigation.ts @@ -0,0 +1,9 @@ +// Only return to known protected routes. Never navigate to a supplied origin. +export function getAuthReturnPath(state: unknown): string { + if (typeof state !== 'object' || state === null || !('from' in state)) + return '/'; + const from = state.from; + if (typeof from !== 'string' || from.includes('\\')) return '/'; + const pathname = from.split(/[?#]/)[0]; + return pathname === '/cookbook' || pathname === '/recipes/new' ? from : '/'; +} diff --git a/apps/web/src/features/cookbook/CookbookControls.css b/apps/web/src/features/cookbook/CookbookControls.css new file mode 100644 index 0000000..e0de5fb --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookControls.css @@ -0,0 +1,182 @@ +@layer components { + .cookbook-controls { + padding: var(--space-3); + + background-color: var(--color-surface-raised); + + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-lg); + } + + /* + * Desktop intentionally follows Explore's toolbar structure: + * one horizontal fieldset with sorting pushed to the right. + */ + .cookbook-controls__desktop { + display: flex; + flex-wrap: nowrap; + align-items: center; + gap: var(--space-3); + + min-width: 0; + margin: 0; + padding: 0; + + border: 0; + } + + .cookbook-controls__desktop-control { + flex: 0 0 auto; + + min-width: 0; + } + + .cookbook-controls__desktop-control--sort { + margin-inline-start: auto; + } + + .cookbook-controls__select { + width: 13.5rem; + min-width: 0; + + background-color: var(--color-surface-raised); + border-color: var(--color-border-input); + border-radius: var(--radius-lg); + } + + .cookbook-controls__select:hover:not(:disabled) { + background-color: var(--color-surface-hover); + border-color: var(--color-border-input-hover); + } + + /* + * Scope is intentionally slightly narrower than Category/Cooking time. + * It remains available, but does not dominate the toolbar. + */ + .cookbook-controls__select--scope { + width: 11.5rem; + } + + .cookbook-controls__select--sort { + width: 15.5rem; + } + + .cookbook-controls__custom-time-input { + width: 9rem; + + background-color: var(--color-surface-raised); + border-color: var(--color-border-input); + border-radius: var(--radius-lg); + } + + /* + * Like Explore, mobile/narrow layouts expose only Filter and Sort. + */ + .cookbook-controls__mobile { + display: none; + } + + .cookbook-controls__sheet-content { + display: flex; + flex-direction: column; + gap: var(--space-6); + } + + .cookbook-controls__filter-group { + display: flex; + flex-direction: column; + gap: var(--space-3); + + min-width: 0; + margin: 0; + padding: 0; + + border: 0; + } + + .cookbook-controls__filter-legend { + margin-block-end: var(--space-1); + padding: 0; + + color: var(--color-text-primary); + + font-size: var(--font-size-sm); + font-weight: var(--font-weight-semibold); + line-height: var(--line-height-snug); + } + + .cookbook-controls__chips { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + } + + .cookbook-controls__custom-time { + max-width: 22rem; + } + + .cookbook-controls__sheet-actions { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-3); + + width: 100%; + } + + .cookbook-controls__sheet-actions--single { + grid-template-columns: minmax(0, 1fr); + } + + .cookbook-controls__sheet-action { + width: 100%; + } + + /* + * Same visual separator before Sort as Explore. + * + * Cookbook has one additional desktop select, so its desktop toolbar + * switches to the compact version a little earlier than Explore. + */ + @media (min-width: 72.0625rem) { + .cookbook-controls__desktop-control--sort { + position: relative; + + padding-inline-start: var(--space-5); + } + + .cookbook-controls__desktop-control--sort::before { + content: ''; + + position: absolute; + top: 15%; + bottom: 15%; + left: 0; + + width: var(--border-width-thin); + + background-color: var(--color-border-divider); + } + } + + @media (max-width: 72rem) { + .cookbook-controls { + padding: var(--space-3); + } + + .cookbook-controls__desktop { + display: none; + } + + .cookbook-controls__mobile { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-3); + } + + .cookbook-controls__mobile-button { + width: 100%; + min-width: 0; + min-height: var(--target-size-min); + } + } +} diff --git a/apps/web/src/features/cookbook/CookbookControls.tsx b/apps/web/src/features/cookbook/CookbookControls.tsx new file mode 100644 index 0000000..1f6d7bf --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookControls.tsx @@ -0,0 +1,466 @@ +import { useState } from 'react'; + +import Button from '../../components/ui/Button/Button'; +import Field from '../../components/ui/Field/Field'; +import FilterChip from '../../components/ui/FilterChip/FilterChip'; +import { Icon } from '../../components/ui/Icon/Icon'; +import Radio from '../../components/ui/Radio/Radio'; +import RadioGroup from '../../components/ui/Radio/RadioGroup'; +import Select from '../../components/ui/Select/Select'; +import Sheet from '../../components/ui/Sheet/Sheet'; +import { FilterIcon, SortIcon } from '../../icons/actions'; +import { CookbookIcon } from '../../icons/navigation'; +import { CategoriesIcon, CookingTimeIcon } from '../../icons/recipe'; +import { + DEFAULT_RECIPE_FILTER_STATE, + RECIPE_CATEGORY_OPTIONS, + RECIPE_COOKING_TIME_OPTIONS, + countActiveRecipeFilters, + type RecipeCategory, + type RecipeCookingTime, + type RecipeFilterState, +} from '../../lib/recipeBrowse/recipeBrowse'; + +import { + COOKBOOK_SCOPE_OPTIONS, + COOKBOOK_SORT_OPTIONS, + getCookbookSortLabel, + type CookbookBrowseState, + type CookbookScope, + type CookbookSort, +} from './cookbookBrowseState'; +import './CookbookControls.css'; + +export type CookbookControlsProps = { + scope: CookbookScope; + browseState: CookbookBrowseState; + onScopeChange: (scope: CookbookScope) => void; + onBrowseStateChange: (value: CookbookBrowseState) => void; + onFiltersChange: (scope: CookbookScope, value: CookbookBrowseState) => void; +}; + +function parseCustomMaxMinutes(value: string) { + if (value.trim() === '') { + return null; + } + + const parsed = Number(value); + + return Number.isInteger(parsed) && parsed > 0 ? parsed : null; +} + +function getScopeSelectLabel(scope: CookbookScope) { + switch (scope) { + case 'saved': + return 'Recipes: Saved'; + + case 'created': + return 'Recipes: Created'; + + case 'all': + return 'Recipes: All'; + } +} + +function CookbookControls({ + scope, + browseState, + onScopeChange, + onBrowseStateChange, + onFiltersChange, +}: CookbookControlsProps) { + const [filterSheetOpen, setFilterSheetOpen] = useState(false); + const [sortSheetOpen, setSortSheetOpen] = useState(false); + + const [scopeDraft, setScopeDraft] = useState(scope); + + const [filterDraft, setFilterDraft] = useState({ + category: browseState.category, + cookingTime: browseState.cookingTime, + customMaxMinutes: browseState.customMaxMinutes, + }); + + const [sortDraft, setSortDraft] = useState(browseState.sort); + const [showCustomTimeError, setShowCustomTimeError] = useState(false); + + const activeFilterCount = + countActiveRecipeFilters(browseState) + (scope === 'all' ? 0 : 1); + + const currentSortLabel = getCookbookSortLabel(browseState.sort); + + function updateBrowseState(patch: Partial) { + onBrowseStateChange({ + ...browseState, + ...patch, + }); + } + + function handleDesktopCookingTimeChange(cookingTime: RecipeCookingTime) { + updateBrowseState({ + cookingTime, + customMaxMinutes: + cookingTime === 'custom' ? browseState.customMaxMinutes : null, + }); + } + + function handleDesktopCustomMaxChange(rawValue: string) { + updateBrowseState({ + cookingTime: 'custom', + customMaxMinutes: parseCustomMaxMinutes(rawValue), + }); + } + + function openFilterSheet() { + setScopeDraft(scope); + + setFilterDraft({ + category: browseState.category, + cookingTime: browseState.cookingTime, + customMaxMinutes: browseState.customMaxMinutes, + }); + + setShowCustomTimeError(false); + setFilterSheetOpen(true); + } + + function handleDraftCookingTimeChange(cookingTime: RecipeCookingTime) { + setFilterDraft((current) => ({ + ...current, + cookingTime, + customMaxMinutes: + cookingTime === 'custom' ? current.customMaxMinutes : null, + })); + + setShowCustomTimeError(false); + } + + function handleApplyFilters() { + if ( + filterDraft.cookingTime === 'custom' && + filterDraft.customMaxMinutes === null + ) { + setShowCustomTimeError(true); + return; + } + + onFiltersChange(scopeDraft, { + ...browseState, + ...filterDraft, + }); + + setFilterSheetOpen(false); + } + + function handleClearFilters() { + setScopeDraft('all'); + + setFilterDraft({ + ...DEFAULT_RECIPE_FILTER_STATE, + }); + + setShowCustomTimeError(false); + } + + function openSortSheet() { + setSortDraft(browseState.sort); + setSortSheetOpen(true); + } + + function handleApplySort() { + updateBrowseState({ + sort: sortDraft, + }); + + setSortSheetOpen(false); + } + + return ( + <> +
+
+ Cookbook filters and sorting + +
+ +
+ +
+ +
+ +
+ +
+ + {browseState.cookingTime === 'custom' && ( +
+ + handleDesktopCustomMaxChange(event.currentTarget.value) + } + /> +
+ )} + +
+ +
+
+ +
+ + + +
+
+ + setFilterSheetOpen(false)} + footer={ +
+ + + +
+ } + > +
+
+ + Recipes + + +
+ {COOKBOOK_SCOPE_OPTIONS.map((option) => ( + setScopeDraft(option.value)} + > + {option.label} + + ))} +
+
+ +
+ + Category + + +
+ {RECIPE_CATEGORY_OPTIONS.map((option) => ( + + setFilterDraft((current) => ({ + ...current, + category: option.value, + })) + } + > + {option.label} + + ))} +
+
+ +
+ + Cooking time + + +
+ {RECIPE_COOKING_TIME_OPTIONS.map((option) => ( + handleDraftCookingTimeChange(option.value)} + > + {option.label} + + ))} +
+ + {filterDraft.cookingTime === 'custom' && ( +
+ { + const customMaxMinutes = parseCustomMaxMinutes( + event.currentTarget.value, + ); + + setFilterDraft((current) => ({ + ...current, + cookingTime: 'custom', + customMaxMinutes, + })); + + setShowCustomTimeError(false); + }} + /> +
+ )} +
+
+
+ + setSortSheetOpen(false)} + footer={ +
+ +
+ } + > + + {COOKBOOK_SORT_OPTIONS.map((option) => ( + setSortDraft(option.value)} + /> + ))} + +
+ + ); +} + +export default CookbookControls; diff --git a/apps/web/src/features/cookbook/CookbookPage.css b/apps/web/src/features/cookbook/CookbookPage.css new file mode 100644 index 0000000..4ee1844 --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookPage.css @@ -0,0 +1,87 @@ +@layer components { + .cookbook-page { + display: flex; + flex-direction: column; + gap: var(--space-8); + + padding-block: var(--space-10) var(--space-16); + } + + .cookbook-page__header { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-2); + + max-width: 48rem; + margin-inline: auto; + + text-align: center; + } + + .cookbook-page__subtitle { + color: var(--color-text-secondary); + + font-size: var(--font-size-lg); + line-height: var(--line-height-relaxed); + } + + .cookbook-page__search-form { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: end; + gap: var(--space-3); + + width: min(100%, 52rem); + margin-inline: auto; + } + + .cookbook-page__results { + display: flex; + flex-direction: column; + gap: var(--space-6); + } + + .cookbook-page__result-count { + color: var(--color-text-secondary); + + font-size: var(--font-size-sm); + font-weight: var(--font-weight-medium); + } + + .cookbook-page__grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--space-6); + } + + .cookbook-page__pagination { + margin-block-start: var(--space-2); + } + + @media (max-width: 65rem) { + .cookbook-page__grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + } + + @media (max-width: 44rem) { + .cookbook-page { + gap: var(--space-6); + + padding-block: var(--space-8) var(--space-12); + } + + .cookbook-page__search-form { + grid-template-columns: 1fr; + } + + .cookbook-page__search-button { + width: 100%; + } + + .cookbook-page__grid { + grid-template-columns: 1fr; + } + } +} diff --git a/apps/web/src/features/cookbook/CookbookPage.test.tsx b/apps/web/src/features/cookbook/CookbookPage.test.tsx new file mode 100644 index 0000000..3b6348c --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookPage.test.tsx @@ -0,0 +1,425 @@ +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, useLocation } from 'react-router-dom'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { INITIAL_SAVED_RECIPE_IDS, useAppStore } from '../../store'; + +import CookbookPage from './CookbookPage'; + +const scrollToMock = vi.fn(); + +function LocationProbe() { + const location = useLocation(); + + return
{location.search}
; +} + +function renderCookbookPage(initialEntry = '/cookbook') { + return render( + + + + , + ); +} + +describe('CookbookPage', () => { + beforeEach(() => { + scrollToMock.mockClear(); + + useAppStore.setState({ + savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], + }); + + Object.defineProperty(window, 'scrollTo', { + value: scrollToMock, + writable: true, + }); + }); + + it('shows All by default', () => { + renderCookbookPage(); + + expect( + screen.getByRole('heading', { + name: 'My Cookbook', + }), + ).toBeTruthy(); + + expect( + screen.getByText(/recipes found/i, { + selector: '.cookbook-page__result-count', + }), + ).toBeTruthy(); + + expect( + ( + screen.getByRole('combobox', { + name: 'Recipe source', + }) as HTMLSelectElement + ).value, + ).toBe('all'); + }); + + it('switches to Saved and writes the scope to the URL', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Recipe source', + }), + 'saved', + ); + + expect(screen.getByText('4 recipes found')).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?view=saved', + ); + }); + + it('shows private owned recipes in Created', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Recipe source', + }), + 'created', + ); + + expect( + screen.getByRole('link', { + name: 'Simple tomato soup', + }), + ).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Slow-cooked lamb and vegetable stew', + }), + ).toBeTruthy(); + }); + + it('searches Cookbook and writes search to the URL', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + const searchInput = screen.getByRole('searchbox', { + name: 'Search cookbook recipes', + }); + + await user.type(searchInput, 'lentils'); + + await user.click( + screen.getByRole('button', { + name: 'Search', + }), + ); + + expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Red lentil soup', + }), + ).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?q=lentils', + ); + }); + + it('restores scope, filters, and sort from the URL', () => { + renderCookbookPage( + '/cookbook?view=created&category=dinner&sort=alphabetical', + ); + + expect( + ( + screen.getByRole('combobox', { + name: 'Recipe source', + }) as HTMLSelectElement + ).value, + ).toBe('created'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Category', + }) as HTMLSelectElement + ).value, + ).toBe('dinner'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Sort by', + }) as HTMLSelectElement + ).value, + ).toBe('alphabetical'); + }); + + it('does not add Save, Unsave, or Edit actions to cookbook cards', () => { + renderCookbookPage(); + + const firstCard = screen.getAllByRole('article')[0]; + + expect(firstCard).toBeTruthy(); + + if (!firstCard) { + return; + } + + expect( + within(firstCard).queryByRole('button', { + name: /Save .* to My Cookbook/i, + }), + ).toBeNull(); + + expect( + within(firstCard).queryByRole('button', { + name: /Remove .* from My Cookbook/i, + }), + ).toBeNull(); + + expect( + within(firstCard).queryByRole('button', { + name: /Edit/i, + }), + ).toBeNull(); + }); + + it('shows recipe source choices inside the filter sheet', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + expect( + screen.getByRole('button', { + name: 'All', + }), + ).toBeTruthy(); + + expect( + screen.getByRole('button', { + name: 'Saved', + }), + ).toBeTruthy(); + + expect( + screen.getByRole('button', { + name: 'Created', + }), + ).toBeTruthy(); + }); + + it('counts a non-default recipe source as an active filter', () => { + renderCookbookPage('/cookbook?view=saved'); + + expect( + screen.getByRole('button', { + name: 'Filters (1)', + hidden: true, + }), + ).toBeTruthy(); + }); + + it('applies mobile filters to the results and URL', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Soup', + }), + ); + + await user.click( + screen.getByRole('button', { + name: '30 min or less', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Simple tomato soup', + }), + ).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?category=soup&time=lte30', + ); + }); + + it('discards mobile filter changes when closed without Apply', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Created', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Dinner', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Close filters', + }), + ); + + expect(screen.getByText('9 recipes found')).toBeTruthy(); + expect(screen.getByTestId('location-search').textContent).toBe(''); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + expect( + screen.getByRole('button', { name: 'All' }).getAttribute('aria-pressed'), + ).toBe('true'); + + expect( + screen + .getByRole('button', { name: 'Created' }) + .getAttribute('aria-pressed'), + ).toBe('false'); + + expect( + screen + .getByRole('button', { name: 'All categories' }) + .getAttribute('aria-pressed'), + ).toBe('true'); + + expect( + screen + .getByRole('button', { name: 'Dinner' }) + .getAttribute('aria-pressed'), + ).toBe('false'); + }); + + it('prevents Apply when custom cooking time is invalid', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Custom maximum', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect( + screen.getByText('Enter a maximum cooking time before applying filters.'), + ).toBeTruthy(); + + expect(screen.getByText('9 recipes found')).toBeTruthy(); + expect(screen.getByTestId('location-search').textContent).toBe(''); + }); + + it('clears mobile filters and applies the cleared state', async () => { + const user = userEvent.setup(); + + renderCookbookPage('/cookbook?view=created&category=soup&time=lte30'); + + expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Simple tomato soup', + }), + ).toBeTruthy(); + + await user.click( + screen.getByRole('button', { + name: 'Filters (3)', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Clear filters', + }), + ); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?view=created&category=soup&time=lte30', + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect(screen.getByText('9 recipes found')).toBeTruthy(); + expect(screen.getByTestId('location-search').textContent).toBe(''); + + expect( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ).toBeTruthy(); + }); +}); diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx new file mode 100644 index 0000000..a6796ad --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookPage.tsx @@ -0,0 +1,349 @@ +import { useEffect, useMemo, useRef, useState, type SubmitEvent } from 'react'; +import { useSearchParams } from 'react-router-dom'; + +import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; +import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps'; +import Button from '../../components/ui/Button/Button'; +import EmptyState from '../../components/ui/EmptyState/EmptyState'; +import Field from '../../components/ui/Field/Field'; +import LinkButton from '../../components/ui/LinkButton/LinkButton'; +import Pagination from '../../components/ui/Pagination/Pagination'; +import { CookbookIcon, SearchIcon } from '../../icons/navigation'; +import { + DEFAULT_RECIPE_FILTER_STATE, + RECIPE_PAGE_SIZE, +} from '../../lib/recipeBrowse/recipeBrowse'; +import { useAppStore } from '../../store'; + +import CookbookControls from './CookbookControls'; +import { + countActiveCookbookFilters, + getCookbookQueryFilters, + type CookbookBrowseState, + type CookbookScope, +} from './cookbookBrowseState'; +import { + createCookbookSearchParams, + readCookbookUrlState, + type CookbookUrlState, +} from './cookbookUrlState'; +import { getMockCookbookResult } from './mockCookbookQuery'; +import './CookbookPage.css'; + +function CookbookPage() { + const searchInputRef = useRef(null); + + const [searchParams, setSearchParams] = useSearchParams(); + + const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); + + const { scope, search, browseState, page } = useMemo( + () => readCookbookUrlState(searchParams), + [searchParams], + ); + + const [searchInput, setSearchInput] = useState(search); + + const queryFilters = getCookbookQueryFilters(browseState); + + const result = getMockCookbookResult({ + scope, + search, + savedRecipeIds, + ...queryFilters, + page, + pageSize: RECIPE_PAGE_SIZE, + }); + + const activeFilterCount = countActiveCookbookFilters(browseState); + + const hasSearch = search.length > 0; + const hasActiveFilters = activeFilterCount > 0; + const hasSearchOrFilters = hasSearch || hasActiveFilters; + + useEffect(() => { + setSearchInput(search); + }, [search]); + + /** + * paginate() normalizes invalid/out-of-range pages. + * Keep the URL synchronized with that normalized result. + */ + useEffect(() => { + if (result.page === page) { + return; + } + + setSearchParams( + createCookbookSearchParams({ + scope, + search, + browseState, + page: result.page, + }), + { + replace: true, + }, + ); + }, [browseState, page, result.page, scope, search, setSearchParams]); + + function updateUrlState(nextState: CookbookUrlState, replace = false) { + setSearchParams(createCookbookSearchParams(nextState), { + replace, + }); + } + + function handleSearchSubmit(event: SubmitEvent) { + event.preventDefault(); + + updateUrlState({ + scope, + search: searchInput, + browseState, + page: 1, + }); + } + + function handleScopeChange(nextScope: CookbookScope) { + updateUrlState({ + scope: nextScope, + search, + browseState, + page: 1, + }); + } + + function handleBrowseStateChange(nextBrowseState: CookbookBrowseState) { + const replaceCurrentEntry = + browseState.cookingTime === 'custom' && + nextBrowseState.cookingTime === 'custom'; + + updateUrlState( + { + scope, + search, + browseState: nextBrowseState, + page: 1, + }, + replaceCurrentEntry, + ); + } + + /* + * Mobile Filters applies scope, category, and cooking time together. + * Keeping this as one URL update avoids one filter change overwriting + * another when Apply filters is pressed. + */ + function handleFiltersChange( + nextScope: CookbookScope, + nextBrowseState: CookbookBrowseState, + ) { + const replaceCurrentEntry = + browseState.cookingTime === 'custom' && + nextBrowseState.cookingTime === 'custom'; + + updateUrlState( + { + scope: nextScope, + search, + browseState: nextBrowseState, + page: 1, + }, + replaceCurrentEntry, + ); + } + + function handleClearResultCriteria() { + const nextBrowseState: CookbookBrowseState = { + ...DEFAULT_RECIPE_FILTER_STATE, + sort: browseState.sort, + }; + + setSearchInput(''); + + updateUrlState({ + scope, + search: '', + browseState: nextBrowseState, + page: 1, + }); + + requestAnimationFrame(() => { + searchInputRef.current?.focus(); + }); + } + + function handlePageChange(nextPage: number) { + updateUrlState({ + scope, + search, + browseState, + page: nextPage, + }); + + window.scrollTo({ + top: 0, + left: 0, + behavior: 'auto', + }); + } + + let emptyStateTitle = 'Your cookbook is empty'; + + let emptyStateDescription = + 'Save recipes from Explore or create your own recipe to build your cookbook.'; + + let emptyStateAction = ( + <> + Explore recipes + + + Add recipe + + + ); + + if (hasSearchOrFilters) { + emptyStateTitle = hasSearch + ? `No cookbook recipes found for “${search}”` + : 'No cookbook recipes found with these filters'; + + emptyStateDescription = + 'Try changing your search or filters, or clear them to see more recipes.'; + + let clearActionLabel = 'Clear filters'; + + if (hasSearch && hasActiveFilters) { + clearActionLabel = 'Clear search and filters'; + } else if (hasSearch) { + clearActionLabel = 'Clear search'; + } + + emptyStateAction = ( + + ); + } else if (scope === 'saved') { + emptyStateTitle = 'No saved recipes yet'; + + emptyStateDescription = 'Recipes you save from Explore will appear here.'; + + emptyStateAction = Explore recipes; + } else if (scope === 'created') { + emptyStateTitle = 'No created recipes yet'; + + emptyStateDescription = 'Recipes you create will appear here.'; + + emptyStateAction = Add recipe; + } + + return ( +
+
+

My Cookbook

+ +

+ Your saved and created recipes, all in one place. +

+
+ +
+ { + const value = event.currentTarget.value; + + setSearchInput(value); + + /** + * Match the current Explore behavior: + * clearing a submitted search immediately clears it from the URL. + */ + if (value === '' && search !== '') { + updateUrlState({ + scope, + search: '', + browseState, + page: 1, + }); + } + }} + /> + + + + +
+

+ Cookbook recipe results +

+ + + +

+ {result.totalItems} {result.totalItems === 1 ? 'recipe' : 'recipes'}{' '} + found + + {search ? ` for “${search}”` : ''} + + {result.pageCount > 0 + ? `. Page ${result.page} of ${result.pageCount}.` + : '.'} + +

+ + {result.totalItems > 0 ? ( + <> +
+ {result.items.map((recipe) => ( + + ))} +
+ +
+ +
+ + ) : ( + + )} +
+
+ ); +} + +export default CookbookPage; diff --git a/apps/web/src/features/cookbook/cookbookBrowseState.ts b/apps/web/src/features/cookbook/cookbookBrowseState.ts new file mode 100644 index 0000000..725ab93 --- /dev/null +++ b/apps/web/src/features/cookbook/cookbookBrowseState.ts @@ -0,0 +1,64 @@ +import { + DEFAULT_RECIPE_FILTER_STATE, + countActiveRecipeFilters, + getRecipeQueryFilters, + type RecipeFilterState, + type RecipeQueryFilters, +} from '../../lib/recipeBrowse/recipeBrowse'; + +export const COOKBOOK_SCOPE_OPTIONS = [ + { value: 'all', label: 'All' }, + { value: 'saved', label: 'Saved' }, + { value: 'created', label: 'Created' }, +] as const; + +export type CookbookScope = (typeof COOKBOOK_SCOPE_OPTIONS)[number]['value']; + +export const COOKBOOK_SORT_OPTIONS = [ + { value: 'recently-updated', label: 'Recently updated' }, + { value: 'cooking-time', label: 'Cooking time' }, + { value: 'alphabetical', label: 'A–Z' }, +] as const; + +export type CookbookSort = (typeof COOKBOOK_SORT_OPTIONS)[number]['value']; + +export type CookbookBrowseState = RecipeFilterState & { + sort: CookbookSort; +}; + +export type CookbookQueryFilters = RecipeQueryFilters & { + sort: CookbookSort; +}; + +export const DEFAULT_COOKBOOK_BROWSE_STATE: CookbookBrowseState = { + ...DEFAULT_RECIPE_FILTER_STATE, + sort: 'recently-updated', +}; + +export function isCookbookScope(value: string | null): value is CookbookScope { + return COOKBOOK_SCOPE_OPTIONS.some((option) => option.value === value); +} + +export function isCookbookSort(value: string | null): value is CookbookSort { + return COOKBOOK_SORT_OPTIONS.some((option) => option.value === value); +} + +export function getCookbookQueryFilters( + state: CookbookBrowseState, +): CookbookQueryFilters { + return { + ...getRecipeQueryFilters(state), + sort: state.sort, + }; +} + +export function countActiveCookbookFilters(state: CookbookBrowseState) { + return countActiveRecipeFilters(state); +} + +export function getCookbookSortLabel(sort: CookbookSort) { + return ( + COOKBOOK_SORT_OPTIONS.find((option) => option.value === sort)?.label ?? + 'Recently updated' + ); +} diff --git a/apps/web/src/features/cookbook/cookbookUrlState.test.ts b/apps/web/src/features/cookbook/cookbookUrlState.test.ts new file mode 100644 index 0000000..2f077ec --- /dev/null +++ b/apps/web/src/features/cookbook/cookbookUrlState.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_COOKBOOK_BROWSE_STATE } from './cookbookBrowseState'; +import { + createCookbookSearchParams, + readCookbookUrlState, +} from './cookbookUrlState'; + +describe('Cookbook URL state', () => { + it('uses default state for an empty URL', () => { + expect(readCookbookUrlState(new URLSearchParams())).toEqual({ + scope: 'all', + search: '', + browseState: DEFAULT_COOKBOOK_BROWSE_STATE, + page: 1, + }); + }); + + it('reads scope, search, filters, sort, and page', () => { + const state = readCookbookUrlState( + new URLSearchParams( + 'view=saved&q=soup&category=dinner&time=lte60&sort=cooking-time&page=2', + ), + ); + + expect(state).toEqual({ + scope: 'saved', + search: 'soup', + browseState: { + category: 'dinner', + cookingTime: 'lte60', + customMaxMinutes: null, + sort: 'cooking-time', + }, + page: 2, + }); + }); + + it('omits defaults when writing URL state', () => { + const params = createCookbookSearchParams({ + scope: 'all', + search: '', + browseState: DEFAULT_COOKBOOK_BROWSE_STATE, + page: 1, + }); + + expect(params.toString()).toBe(''); + }); + + it('writes non-default state', () => { + const params = createCookbookSearchParams({ + scope: 'created', + search: ' cake ', + browseState: { + category: 'dessert', + cookingTime: 'custom', + customMaxMinutes: 75, + sort: 'alphabetical', + }, + page: 2, + }); + + expect(params.toString()).toBe( + 'view=created&q=cake&category=dessert&time=custom&maxTime=75&sort=alphabetical&page=2', + ); + }); + + it('restores written state', () => { + const params = createCookbookSearchParams({ + scope: 'saved', + search: 'soup', + browseState: { + category: 'soup', + cookingTime: 'lte60', + customMaxMinutes: null, + sort: 'cooking-time', + }, + page: 2, + }); + + expect(readCookbookUrlState(params)).toEqual({ + scope: 'saved', + search: 'soup', + browseState: { + category: 'soup', + cookingTime: 'lte60', + customMaxMinutes: null, + sort: 'cooking-time', + }, + page: 2, + }); + }); +}); diff --git a/apps/web/src/features/cookbook/cookbookUrlState.ts b/apps/web/src/features/cookbook/cookbookUrlState.ts new file mode 100644 index 0000000..3078b9d --- /dev/null +++ b/apps/web/src/features/cookbook/cookbookUrlState.ts @@ -0,0 +1,116 @@ +import { + isRecipeCategory, + isRecipeCookingTime, +} from '../../lib/recipeBrowse/recipeBrowse'; + +import { + DEFAULT_COOKBOOK_BROWSE_STATE, + isCookbookScope, + isCookbookSort, + type CookbookBrowseState, + type CookbookScope, +} from './cookbookBrowseState'; + +export type CookbookUrlState = { + scope: CookbookScope; + search: string; + browseState: CookbookBrowseState; + page: number; +}; + +function parsePositiveInteger(value: string | null) { + if (!value) { + return null; + } + + const parsed = Number(value); + + return Number.isInteger(parsed) && parsed > 0 ? parsed : null; +} + +export function readCookbookUrlState( + searchParams: URLSearchParams, +): CookbookUrlState { + const scopeParam = searchParams.get('view'); + const categoryParam = searchParams.get('category'); + const cookingTimeParam = searchParams.get('time'); + const sortParam = searchParams.get('sort'); + + const scope = isCookbookScope(scopeParam) ? scopeParam : 'all'; + + const category = isRecipeCategory(categoryParam) + ? categoryParam + : DEFAULT_COOKBOOK_BROWSE_STATE.category; + + const cookingTime = isRecipeCookingTime(cookingTimeParam) + ? cookingTimeParam + : DEFAULT_COOKBOOK_BROWSE_STATE.cookingTime; + + const sort = isCookbookSort(sortParam) + ? sortParam + : DEFAULT_COOKBOOK_BROWSE_STATE.sort; + + const customMaxMinutes = + cookingTime === 'custom' + ? parsePositiveInteger(searchParams.get('maxTime')) + : null; + + return { + scope, + + search: (searchParams.get('q') ?? '').trim(), + + browseState: { + category, + cookingTime, + customMaxMinutes, + sort, + }, + + page: parsePositiveInteger(searchParams.get('page')) ?? 1, + }; +} + +export function createCookbookSearchParams({ + scope, + search, + browseState, + page, +}: CookbookUrlState) { + const searchParams = new URLSearchParams(); + + const trimmedSearch = search.trim(); + + if (scope !== 'all') { + searchParams.set('view', scope); + } + + if (trimmedSearch) { + searchParams.set('q', trimmedSearch); + } + + if (browseState.category !== 'all') { + searchParams.set('category', browseState.category); + } + + if (browseState.cookingTime !== 'any') { + searchParams.set('time', browseState.cookingTime); + + if ( + browseState.cookingTime === 'custom' && + browseState.customMaxMinutes !== null + ) { + searchParams.set('maxTime', String(browseState.customMaxMinutes)); + } + } + + if (browseState.sort !== 'recently-updated') { + searchParams.set('sort', browseState.sort); + } + + if (page > 1) { + searchParams.set('page', String(page)); + } + + return searchParams; +} diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.test.ts b/apps/web/src/features/cookbook/mockCookbookQuery.test.ts new file mode 100644 index 0000000..123eaa3 --- /dev/null +++ b/apps/web/src/features/cookbook/mockCookbookQuery.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it } from 'vitest'; + +import { INITIAL_SAVED_RECIPE_IDS } from '../../store'; + +import { getMockCookbookResult, type CookbookQuery } from './mockCookbookQuery'; + +function createQuery(overrides: Partial = {}): CookbookQuery { + return { + scope: 'all', + search: '', + savedRecipeIds: INITIAL_SAVED_RECIPE_IDS, + category: null, + maxCookingMinutes: null, + sort: 'recently-updated', + page: 1, + pageSize: 50, + ...overrides, + }; +} + +describe('getMockCookbookResult', () => { + it('returns the union of saved and created recipes for All', () => { + const result = getMockCookbookResult(createQuery()); + + expect(result.totalItems).toBe(9); + + expect( + result.items.every( + (recipe) => + recipe.isCreatedByCurrentUser || + INITIAL_SAVED_RECIPE_IDS.includes(recipe.id), + ), + ).toBe(true); + }); + + it('returns only runtime saved recipes for Saved', () => { + const result = getMockCookbookResult( + createQuery({ + scope: 'saved', + savedRecipeIds: ['salmon-pasta'], + }), + ); + + expect(result.items.map((recipe) => recipe.id)).toEqual(['salmon-pasta']); + }); + + it('returns only current-user recipes for Created', () => { + const result = getMockCookbookResult( + createQuery({ + scope: 'created', + }), + ); + + expect(result.items.every((recipe) => recipe.isCreatedByCurrentUser)).toBe( + true, + ); + }); + + it('includes current-user private recipes in Created', () => { + const result = getMockCookbookResult( + createQuery({ + scope: 'created', + }), + ); + + expect(result.items.map((recipe) => recipe.id)).toEqual( + expect.arrayContaining(['tomato-soup', 'lamb-stew']), + ); + }); + + it('uses the same ingredient search behavior as Explore', () => { + const result = getMockCookbookResult( + createQuery({ + search: 'red lentils', + }), + ); + + expect(result.items.map((recipe) => recipe.id)).toContain('lentil-soup'); + }); + + it('filters by category', () => { + const result = getMockCookbookResult( + createQuery({ + category: 'dinner', + }), + ); + + expect(result.items.every((recipe) => recipe.category === 'Dinner')).toBe( + true, + ); + }); + + it('filters by maximum cooking time', () => { + const result = getMockCookbookResult( + createQuery({ + maxCookingMinutes: 30, + }), + ); + + expect( + result.items.every( + (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 30, + ), + ).toBe(true); + }); + + it('sorts recently updated by updatedAt descending', () => { + const result = getMockCookbookResult( + createQuery({ + sort: 'recently-updated', + }), + ); + + for (let index = 1; index < result.items.length; index += 1) { + const previous = result.items[index - 1]; + const current = result.items[index]; + + if (!previous || !current) { + continue; + } + + expect(Date.parse(previous.updatedAt)).toBeGreaterThanOrEqual( + Date.parse(current.updatedAt), + ); + } + }); + + it('sorts cooking time shortest first', () => { + const result = getMockCookbookResult( + createQuery({ + sort: 'cooking-time', + }), + ); + + for (let index = 1; index < result.items.length; index += 1) { + const previous = result.items[index - 1]; + const current = result.items[index]; + + if (!previous || !current) { + continue; + } + + const previousMinutes = previous.prepMinutes + previous.cookMinutes; + const currentMinutes = current.prepMinutes + current.cookMinutes; + + expect(previousMinutes).toBeLessThanOrEqual(currentMinutes); + } + }); + + it('sorts alphabetically', () => { + const result = getMockCookbookResult( + createQuery({ + sort: 'alphabetical', + }), + ); + + const titles = result.items.map((recipe) => recipe.title); + + expect(titles).toEqual([...titles].sort((a, b) => a.localeCompare(b))); + }); + + it('paginates after scope, filtering, and sorting', () => { + const firstPage = getMockCookbookResult( + createQuery({ + page: 1, + pageSize: 6, + }), + ); + + const secondPage = getMockCookbookResult( + createQuery({ + page: 2, + pageSize: 6, + }), + ); + + expect(firstPage.totalItems).toBe(9); + expect(firstPage.items).toHaveLength(6); + expect(secondPage.items).toHaveLength(3); + }); +}); diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.ts b/apps/web/src/features/cookbook/mockCookbookQuery.ts new file mode 100644 index 0000000..2a3d823 --- /dev/null +++ b/apps/web/src/features/cookbook/mockCookbookQuery.ts @@ -0,0 +1,101 @@ +import { recipes } from '../../data/recipes'; +import { paginate, type PageResult } from '../../lib/pagination/paginate'; +import { + filterRecipesByBrowseCriteria, + getRecipeTotalMinutes, + type RecipeQueryFilters, +} from '../../lib/recipeBrowse/recipeBrowse'; +import type { Recipe } from '../../types/recipe'; + +import type { CookbookScope, CookbookSort } from './cookbookBrowseState'; + +export type CookbookQuery = RecipeQueryFilters & { + scope: CookbookScope; + search: string; + savedRecipeIds: readonly string[]; + sort: CookbookSort; + page: number; + pageSize: number; +}; + +export type CookbookResult = PageResult; + +function compareRecentlyUpdated(a: Recipe, b: Recipe) { + const dateDifference = Date.parse(b.updatedAt) - Date.parse(a.updatedAt); + + if (dateDifference !== 0) { + return dateDifference; + } + + return a.title.localeCompare(b.title); +} + +function compareCookingTime(a: Recipe, b: Recipe) { + const timeDifference = getRecipeTotalMinutes(a) - getRecipeTotalMinutes(b); + + if (timeDifference !== 0) { + return timeDifference; + } + + return compareRecentlyUpdated(a, b); +} + +function compareAlphabetical(a: Recipe, b: Recipe) { + const titleDifference = a.title.localeCompare(b.title); + + if (titleDifference !== 0) { + return titleDifference; + } + + return compareRecentlyUpdated(a, b); +} + +const sortComparators: Record number> = + { + 'recently-updated': compareRecentlyUpdated, + 'cooking-time': compareCookingTime, + alphabetical: compareAlphabetical, + }; + +function sortRecipes(items: readonly Recipe[], sort: CookbookSort) { + return [...items].sort(sortComparators[sort]); +} + +export function getMockCookbookResult({ + scope, + search, + savedRecipeIds, + category, + maxCookingMinutes, + sort, + page, + pageSize, +}: CookbookQuery): CookbookResult { + const savedIds = new Set(savedRecipeIds); + + const scopedRecipes = recipes.filter((recipe) => { + const isSaved = savedIds.has(recipe.id); + const isCreated = recipe.isCreatedByCurrentUser; + + switch (scope) { + case 'saved': + return isSaved; + + case 'created': + return isCreated; + + case 'all': + return isSaved || isCreated; + } + }); + + const filteredRecipes = filterRecipesByBrowseCriteria(scopedRecipes, { + search, + category, + maxCookingMinutes, + }); + + const sortedRecipes = sortRecipes(filteredRecipes, sort); + + return paginate(sortedRecipes, page, pageSize); +} diff --git a/apps/web/src/features/explore/ExploreControls.css b/apps/web/src/features/explore/ExploreControls.css new file mode 100644 index 0000000..e7ab09d --- /dev/null +++ b/apps/web/src/features/explore/ExploreControls.css @@ -0,0 +1,161 @@ +@layer components { + .explore-controls { + padding: var(--space-3); + + background-color: var(--color-surface-raised); + + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-lg); + } + + .explore-controls__desktop { + display: flex; + flex-wrap: nowrap; + align-items: center; + gap: var(--space-3); + + min-width: 0; + margin: 0; + padding: 0; + + border: 0; + } + + .explore-controls__desktop-control { + flex: 0 0 auto; + + min-width: 0; + } + + .explore-controls__desktop-control--sort { + margin-inline-start: auto; + } + + .explore-controls__select { + width: 13.5rem; + min-width: 0; + + background-color: var(--color-surface-raised); + border-color: var(--color-border-input); + border-radius: var(--radius-lg); + } + + .explore-controls__select:hover:not(:disabled) { + background-color: var(--color-surface-hover); + border-color: var(--color-border-input-hover); + } + + .explore-controls__select--sort { + width: 18rem; + } + + .explore-controls__custom-time-input { + width: 9rem; + + background-color: var(--color-surface-raised); + border-color: var(--color-border-input); + border-radius: var(--radius-lg); + } + + .explore-controls__mobile { + display: none; + } + + .explore-controls__sheet-content { + display: flex; + flex-direction: column; + gap: var(--space-6); + } + + .explore-controls__filter-group { + display: flex; + flex-direction: column; + gap: var(--space-3); + + min-width: 0; + margin: 0; + padding: 0; + + border: 0; + } + + .explore-controls__filter-legend { + margin-block-end: var(--space-1); + padding: 0; + + color: var(--color-text-primary); + + font-size: var(--font-size-sm); + font-weight: var(--font-weight-semibold); + line-height: var(--line-height-snug); + } + + .explore-controls__chips { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + } + + .explore-controls__custom-time { + max-width: 22rem; + } + + .explore-controls__sheet-actions { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-3); + + width: 100%; + } + + .explore-controls__sheet-actions--single { + grid-template-columns: minmax(0, 1fr); + } + + .explore-controls__sheet-action { + width: 100%; + } + + @media (min-width: 60.0625rem) { + .explore-controls__desktop-control--sort { + position: relative; + + padding-inline-start: var(--space-5); + } + + .explore-controls__desktop-control--sort::before { + content: ''; + + position: absolute; + top: 15%; + bottom: 15%; + left: 0; + + width: var(--border-width-thin); + + background-color: var(--color-border-divider); + } + } + + @media (max-width: 60rem) { + .explore-controls { + padding: var(--space-3); + } + + .explore-controls__desktop { + display: none; + } + + .explore-controls__mobile { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-3); + } + + .explore-controls__mobile-button { + width: 100%; + min-width: 0; + min-height: var(--target-size-min); + } + } +} diff --git a/apps/web/src/features/explore/ExploreControls.test.tsx b/apps/web/src/features/explore/ExploreControls.test.tsx new file mode 100644 index 0000000..0f24033 --- /dev/null +++ b/apps/web/src/features/explore/ExploreControls.test.tsx @@ -0,0 +1,234 @@ +import { useState } from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it } from 'vitest'; + +import ExploreControls from './ExploreControls'; +import { + DEFAULT_EXPLORE_BROWSE_STATE, + type ExploreBrowseState, +} from './exploreBrowseState'; + +function ExploreControlsHarness() { + const [value, setValue] = useState( + DEFAULT_EXPLORE_BROWSE_STATE, + ); + + return ; +} + +describe('ExploreControls', () => { + it('uses Trending as the default sort and keeps desktop and mobile state in sync', async () => { + const user = userEvent.setup(); + + render(); + + const category = screen.getByRole('combobox', { + name: 'Category', + }) as HTMLSelectElement; + + const cookingTime = screen.getByRole('combobox', { + name: 'Cooking time', + }) as HTMLSelectElement; + + const sort = screen.getByRole('combobox', { + name: 'Sort by', + }) as HTMLSelectElement; + + expect(sort.value).toBe('trending'); + + expect( + screen.getByRole('button', { + name: 'Sort: Trending', + hidden: true, + }), + ).toBeTruthy(); + + await user.selectOptions(category, 'dinner'); + await user.selectOptions(cookingTime, 'lte30'); + + expect( + screen.getByRole('button', { + name: 'Filters (2)', + hidden: true, + }), + ).toBeTruthy(); + + fireEvent.click( + screen.getByRole('button', { + name: 'Filters (2)', + hidden: true, + }), + ); + + expect( + screen + .getByRole('button', { name: 'Dinner' }) + .getAttribute('aria-pressed'), + ).toBe('true'); + + expect( + screen + .getByRole('button', { name: '30 min or less' }) + .getAttribute('aria-pressed'), + ).toBe('true'); + }); + + it('applies mobile filter drafts to the shared browse state', async () => { + const user = userEvent.setup(); + + render(); + + fireEvent.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Dinner', + }), + ); + + await user.click( + screen.getByRole('button', { + name: '60 min or less', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect( + screen.getByRole('button', { + name: 'Filters (2)', + hidden: true, + }), + ).toBeTruthy(); + + expect( + ( + screen.getByRole('combobox', { + name: 'Category', + }) as HTMLSelectElement + ).value, + ).toBe('dinner'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Cooking time', + }) as HTMLSelectElement + ).value, + ).toBe('lte60'); + }); + + it('requires a positive custom maximum before applying mobile filters', async () => { + const user = userEvent.setup(); + + render(); + + fireEvent.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Custom maximum', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect( + screen.getByText('Enter a maximum cooking time before applying filters.'), + ).toBeTruthy(); + + const customMaximum = screen.getByRole('spinbutton', { + name: 'Maximum cooking time in minutes', + }); + + await user.type(customMaximum, '45'); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect( + screen.getByRole('button', { + name: 'Filters (1)', + hidden: true, + }), + ).toBeTruthy(); + + expect( + ( + screen.getByRole('combobox', { + name: 'Cooking time', + }) as HTMLSelectElement + ).value, + ).toBe('custom'); + + expect( + ( + screen.getByRole('spinbutton', { + name: 'Maximum cooking time', + }) as HTMLInputElement + ).value, + ).toBe('45'); + }); + + it('applies mobile sorting and reflects it in the desktop sort control', async () => { + const user = userEvent.setup(); + + render(); + + fireEvent.click( + screen.getByRole('button', { + name: 'Sort: Trending', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('radio', { + name: 'Most saved', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply sort', + }), + ); + + expect( + screen.getByRole('button', { + name: 'Sort: Most saved', + hidden: true, + }), + ).toBeTruthy(); + + expect( + ( + screen.getByRole('combobox', { + name: 'Sort by', + }) as HTMLSelectElement + ).value, + ).toBe('most-saved'); + }); +}); diff --git a/apps/web/src/features/explore/ExploreControls.tsx b/apps/web/src/features/explore/ExploreControls.tsx new file mode 100644 index 0000000..63bdb04 --- /dev/null +++ b/apps/web/src/features/explore/ExploreControls.tsx @@ -0,0 +1,388 @@ +import { useState } from 'react'; + +import Button from '../../components/ui/Button/Button'; +import Field from '../../components/ui/Field/Field'; +import FilterChip from '../../components/ui/FilterChip/FilterChip'; +import { Icon } from '../../components/ui/Icon/Icon'; +import Radio from '../../components/ui/Radio/Radio'; +import RadioGroup from '../../components/ui/Radio/RadioGroup'; +import Select from '../../components/ui/Select/Select'; +import Sheet from '../../components/ui/Sheet/Sheet'; +import { FilterIcon, SortIcon } from '../../icons/actions'; +import { CategoriesIcon, CookingTimeIcon } from '../../icons/recipe'; + +import { + DEFAULT_EXPLORE_FILTER_STATE, + EXPLORE_CATEGORY_OPTIONS, + EXPLORE_COOKING_TIME_OPTIONS, + EXPLORE_SORT_OPTIONS, + countActiveExploreFilters, + getExploreSortLabel, + type ExploreBrowseState, + type ExploreCategory, + type ExploreCookingTime, + type ExploreFilterState, + type ExploreSort, +} from './exploreBrowseState'; +import './ExploreControls.css'; + +export type ExploreControlsProps = { + value: ExploreBrowseState; + onChange: (value: ExploreBrowseState) => void; +}; + +function parseCustomMaxMinutes(value: string) { + if (value.trim() === '') { + return null; + } + + const parsed = Number(value); + + return Number.isInteger(parsed) && parsed > 0 ? parsed : null; +} + +function ExploreControls({ value, onChange }: ExploreControlsProps) { + const [filterSheetOpen, setFilterSheetOpen] = useState(false); + const [sortSheetOpen, setSortSheetOpen] = useState(false); + + const [filterDraft, setFilterDraft] = useState({ + category: value.category, + cookingTime: value.cookingTime, + customMaxMinutes: value.customMaxMinutes, + }); + + const [sortDraft, setSortDraft] = useState(value.sort); + const [showCustomTimeError, setShowCustomTimeError] = useState(false); + + const activeFilterCount = countActiveExploreFilters(value); + const currentSortLabel = getExploreSortLabel(value.sort); + + function updateValue(patch: Partial) { + onChange({ + ...value, + ...patch, + }); + } + + function handleDesktopCookingTimeChange(cookingTime: ExploreCookingTime) { + updateValue({ + cookingTime, + customMaxMinutes: + cookingTime === 'custom' ? value.customMaxMinutes : null, + }); + } + + function handleDesktopCustomMaxChange(rawValue: string) { + updateValue({ + cookingTime: 'custom', + customMaxMinutes: parseCustomMaxMinutes(rawValue), + }); + } + + function openFilterSheet() { + setFilterDraft({ + category: value.category, + cookingTime: value.cookingTime, + customMaxMinutes: value.customMaxMinutes, + }); + + setShowCustomTimeError(false); + setFilterSheetOpen(true); + } + + function handleDraftCookingTimeChange(cookingTime: ExploreCookingTime) { + setFilterDraft((current) => ({ + ...current, + cookingTime, + customMaxMinutes: + cookingTime === 'custom' ? current.customMaxMinutes : null, + })); + + setShowCustomTimeError(false); + } + + function handleApplyFilters() { + if ( + filterDraft.cookingTime === 'custom' && + filterDraft.customMaxMinutes === null + ) { + setShowCustomTimeError(true); + return; + } + + onChange({ + ...value, + ...filterDraft, + }); + + setFilterSheetOpen(false); + } + + function openSortSheet() { + setSortDraft(value.sort); + setSortSheetOpen(true); + } + + function handleApplySort() { + updateValue({ + sort: sortDraft, + }); + + setSortSheetOpen(false); + } + + return ( + <> +
+
+ Explore filters and sorting + +
+ +
+ +
+ +
+ + {value.cookingTime === 'custom' && ( +
+ + handleDesktopCustomMaxChange(event.currentTarget.value) + } + /> +
+ )} + +
+ +
+
+ +
+ + + +
+
+ + setFilterSheetOpen(false)} + footer={ +
+ + + +
+ } + > +
+
+ + Category + + +
+ {EXPLORE_CATEGORY_OPTIONS.map((option) => ( + + setFilterDraft((current) => ({ + ...current, + category: option.value, + })) + } + > + {option.label} + + ))} +
+
+ +
+ + Cooking time + + +
+ {EXPLORE_COOKING_TIME_OPTIONS.map((option) => ( + handleDraftCookingTimeChange(option.value)} + > + {option.label} + + ))} +
+ + {filterDraft.cookingTime === 'custom' && ( +
+ { + const customMaxMinutes = parseCustomMaxMinutes( + event.currentTarget.value, + ); + + setFilterDraft((current) => ({ + ...current, + cookingTime: 'custom', + customMaxMinutes, + })); + + setShowCustomTimeError(false); + }} + /> +
+ )} +
+
+
+ + setSortSheetOpen(false)} + footer={ +
+ +
+ } + > + + {EXPLORE_SORT_OPTIONS.map((option) => ( + setSortDraft(option.value)} + /> + ))} + +
+ + ); +} + +export default ExploreControls; diff --git a/apps/web/src/features/explore/ExplorePage.css b/apps/web/src/features/explore/ExplorePage.css index 215f501..048100b 100644 --- a/apps/web/src/features/explore/ExplorePage.css +++ b/apps/web/src/features/explore/ExplorePage.css @@ -42,22 +42,6 @@ gap: var(--space-6); } - .explore-page__toolbar { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: var(--space-4); - - min-height: var(--target-size-min); - padding: var(--space-3) var(--space-4); - - background-color: var(--color-surface-raised); - - border: var(--border-width-thin) solid var(--color-border-subtle); - border-radius: var(--radius-lg); - } - .explore-page__result-count { color: var(--color-text-secondary); @@ -75,6 +59,15 @@ margin-block-start: var(--space-2); } + .explore-page__toast-region { + position: fixed; + right: var(--space-6); + bottom: var(--space-6); + z-index: var(--z-overlay); + + width: min(24rem, calc(100% - (2 * var(--space-6)))); + } + @media (max-width: 65rem) { .explore-page__grid { grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -99,5 +92,13 @@ .explore-page__grid { grid-template-columns: 1fr; } + + .explore-page__toast-region { + right: var(--space-4); + bottom: var(--space-4); + left: var(--space-4); + + width: auto; + } } } diff --git a/apps/web/src/features/explore/ExplorePage.test.tsx b/apps/web/src/features/explore/ExplorePage.test.tsx index 6a05768..493cb2b 100644 --- a/apps/web/src/features/explore/ExplorePage.test.tsx +++ b/apps/web/src/features/explore/ExplorePage.test.tsx @@ -1,16 +1,37 @@ -import { render, screen } from '@testing-library/react'; +import { render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { MemoryRouter } from 'react-router-dom'; +import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { mockUser } from '../../data/users'; +import { INITIAL_SAVED_RECIPE_IDS, useAppStore } from '../../store'; + import ExplorePage from './ExplorePage'; const scrollToMock = vi.fn(); -function renderExplorePage() { +function LocationProbe() { + const location = useLocation(); + + return
{location.search}
; +} + +function HistoryBackButton() { + const navigate = useNavigate(); + + return ( + + ); +} + +function renderExplorePage(initialEntry = '/') { return render( - + + + , ); } @@ -19,13 +40,19 @@ describe('ExplorePage', () => { beforeEach(() => { scrollToMock.mockClear(); + useAppStore.setState({ + search: '', + currentUser: null, + savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], + }); + Object.defineProperty(window, 'scrollTo', { value: scrollToMock, writable: true, }); }); - it('renders recipe results from the mock dataset', () => { + it('renders the default Trending result set', () => { renderExplorePage(); expect( @@ -34,10 +61,12 @@ describe('ExplorePage', () => { }), ).toBeTruthy(); - expect(screen.getAllByRole('article').length).toBeGreaterThan(0); + expect(screen.getByText('4 recipes found')).toBeTruthy(); + + expect(screen.getAllByRole('article')).toHaveLength(4); }); - it('filters recipes after submitting a search', async () => { + it('searches the catalog and writes committed search to the URL', async () => { const user = userEvent.setup(); renderExplorePage(); @@ -46,7 +75,7 @@ describe('ExplorePage', () => { name: 'Search recipes', }); - await user.type(searchInput, 'SALMON'); + await user.type(searchInput, 'thai'); await user.click( screen.getByRole('button', { @@ -56,17 +85,93 @@ describe('ExplorePage', () => { expect( screen.getByRole('link', { - name: 'Creamy salmon pasta', + name: 'Thai green curry', }), ).toBeTruthy(); expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe('?q=thai'); }); - it('changes page and scrolls to the top', async () => { + it('applies filters, resets page, and writes them to the URL', async () => { const user = userEvent.setup(); - renderExplorePage(); + renderExplorePage('/?sort=popular&page=2'); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Category', + }), + 'dinner', + ); + + expect(screen.getByRole('status').textContent).toMatch(/recipes found/i); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?category=dinner&sort=popular', + ); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Cooking time', + }), + 'lte30', + ); + + expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?category=dinner&time=lte30&sort=popular', + ); + }); + + it('restores search, filters, and sorting from the URL', () => { + renderExplorePage('/?q=salmon&category=dinner&time=lte30&sort=popular'); + + expect( + ( + screen.getByRole('searchbox', { + name: 'Search recipes', + }) as HTMLInputElement + ).value, + ).toBe('salmon'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Category', + }) as HTMLSelectElement + ).value, + ).toBe('dinner'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Cooking time', + }) as HTMLSelectElement + ).value, + ).toBe('lte30'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Sort by', + }) as HTMLSelectElement + ).value, + ).toBe('popular'); + + expect( + screen.getByRole('link', { + name: 'Creamy salmon pasta', + }), + ).toBeTruthy(); + }); + + it('changes page while preserving the browse context', async () => { + const user = userEvent.setup(); + + renderExplorePage('/?sort=popular'); await user.click( screen.getByRole('button', { @@ -80,6 +185,10 @@ describe('ExplorePage', () => { expect(currentPageButton.getAttribute('aria-current')).toBe('page'); + expect(screen.getByTestId('location-search').textContent).toBe( + '?sort=popular&page=2', + ); + expect(scrollToMock).toHaveBeenCalledWith({ top: 0, left: 0, @@ -87,10 +196,28 @@ describe('ExplorePage', () => { }); }); - it('clears the active search when the search input is emptied', async () => { + it('clamps an out-of-range page and corrects the URL', async () => { + renderExplorePage('/?sort=popular&page=99'); + + await waitFor(() => { + expect(screen.getByTestId('location-search').textContent).toBe( + '?sort=popular&page=2', + ); + }); + + expect( + screen + .getByRole('button', { + name: 'Page 2, current page', + }) + .getAttribute('aria-current'), + ).toBe('page'); + }); + + it('clears a submitted search when the search field is emptied', async () => { const user = userEvent.setup(); - renderExplorePage(); + renderExplorePage('/?sort=popular'); const searchInput = screen.getByRole('searchbox', { name: 'Search recipes', @@ -108,14 +235,17 @@ describe('ExplorePage', () => { await user.clear(searchInput); - expect(screen.queryByText('1 recipe found')).toBeNull(); - expect(screen.getAllByRole('article').length).toBeGreaterThan(1); + expect(screen.getByRole('status').textContent).toMatch(/recipes found/i); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?sort=popular', + ); }); - it('clears a no-results search and returns focus to the search field', async () => { + it('clears no-result search and filter criteria while preserving sort', async () => { const user = userEvent.setup(); - renderExplorePage(); + renderExplorePage('/?category=dinner&sort=popular'); const searchInput = screen.getByRole('searchbox', { name: 'Search recipes', @@ -133,14 +263,234 @@ describe('ExplorePage', () => { await user.click( screen.getByRole('button', { - name: 'Clear search', + name: 'Clear search and filters', }), ); - expect(screen.getAllByRole('article').length).toBeGreaterThan(0); + expect(screen.getByRole('status').textContent).toMatch(/recipes found/i); - await vi.waitFor(() => { + expect(screen.getByTestId('location-search').textContent).toBe( + '?sort=popular', + ); + + await waitFor(() => { expect(document.activeElement).toBe(searchInput); }); }); + + it('restores the previous browse state when navigating back', async () => { + const user = userEvent.setup(); + + renderExplorePage(); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Sort by', + }), + 'popular', + ); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Category', + }), + 'dinner', + ); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?category=dinner&sort=popular', + ); + + await user.click( + screen.getByRole('button', { + name: 'Test browser back', + }), + ); + + await waitFor(() => { + expect( + ( + screen.getByRole('combobox', { + name: 'Category', + }) as HTMLSelectElement + ).value, + ).toBe('all'); + }); + + expect( + ( + screen.getByRole('combobox', { + name: 'Sort by', + }) as HTMLSelectElement + ).value, + ).toBe('popular'); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?sort=popular', + ); + }); + + it('saves an eligible recipe and updates shared state', async () => { + const user = userEvent.setup(); + + useAppStore.setState({ + currentUser: mockUser, + }); + + renderExplorePage('/?q=thai&sort=popular'); + + const recipeLink = screen.getByRole('link', { + name: 'Thai green curry', + }); + + const recipeCard = recipeLink.closest('article'); + + expect(recipeCard).not.toBeNull(); + + if (!recipeCard) { + return; + } + + expect( + within(recipeCard).getByRole('button', { + name: /^Save .* to My Cookbook$/, + }), + ).toBeTruthy(); + + await user.click( + within(recipeCard).getByRole('button', { + name: /^Save .* to My Cookbook$/, + }), + ); + + expect( + within(recipeCard).getByRole('button', { + name: /^Remove .* from My Cookbook$/, + }), + ).toBeTruthy(); + + expect(useAppStore.getState().savedRecipeIds).toContain('thai-green-curry'); + + expect(screen.getByText('Recipe saved')).toBeTruthy(); + + expect( + screen.getByText('“Thai green curry” was saved to My Cookbook.'), + ).toBeTruthy(); + }); + + it('confirms before removing a saved recipe', async () => { + const user = userEvent.setup(); + + useAppStore.setState({ + currentUser: mockUser, + }); + + renderExplorePage('/?q=falafel&sort=popular'); + + const recipeLink = screen.getByRole('link', { + name: 'Falafel bowl with hummus', + }); + + const recipeCard = recipeLink.closest('article'); + + expect(recipeCard).not.toBeNull(); + + if (!recipeCard) { + return; + } + + expect( + within(recipeCard).getByRole('button', { + name: /^Remove .* from My Cookbook$/, + }), + ).toBeTruthy(); + + await user.click( + within(recipeCard).getByRole('button', { + name: /^Remove .* from My Cookbook$/, + }), + ); + + expect( + screen.getByRole('dialog', { + name: 'Remove saved recipe?', + }), + ).toBeTruthy(); + + await user.click( + screen.getByRole('button', { + name: 'Unsave', + }), + ); + + expect( + within(recipeCard).getByRole('button', { + name: /^Save .* to My Cookbook$/, + }), + ).toBeTruthy(); + + expect(useAppStore.getState().savedRecipeIds).not.toContain('falafel-bowl'); + + expect(screen.getByText('Recipe removed')).toBeTruthy(); + }); + + it('does not expose Save for recipes created by the current user', () => { + useAppStore.setState({ + currentUser: mockUser, + }); + + renderExplorePage('/?q=apple&sort=popular'); + + const recipeLink = screen.getByRole('link', { + name: 'Norwegian apple cake', + }); + + const recipeCard = recipeLink.closest('article'); + + expect(recipeCard).not.toBeNull(); + + if (!recipeCard) { + return; + } + + expect( + within(recipeCard).queryByRole('button', { + name: /^Save .* to My Cookbook$/, + }), + ).toBeNull(); + + expect( + within(recipeCard).queryByRole('button', { + name: /^Remove .* from My Cookbook$/, + }), + ).toBeNull(); + }); + + it('does not expose Save actions while logged out', () => { + renderExplorePage('/?q=thai&sort=popular'); + + const recipeLink = screen.getByRole('link', { + name: 'Thai green curry', + }); + + const recipeCard = recipeLink.closest('article'); + + expect(recipeCard).not.toBeNull(); + + if (!recipeCard) { + return; + } + + expect( + within(recipeCard).queryByRole('button', { + name: /^Save .* to My Cookbook$/, + }), + ).toBeNull(); + + expect( + within(recipeCard).queryByRole('button', { + name: /^Remove .* from My Cookbook$/, + }), + ).toBeNull(); + }); }); diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx index b8b64d8..e4b00ce 100644 --- a/apps/web/src/features/explore/ExplorePage.tsx +++ b/apps/web/src/features/explore/ExplorePage.tsx @@ -1,4 +1,5 @@ -import { useRef, useState, type SubmitEvent } from 'react'; +import { useEffect, useMemo, useRef, useState, type SubmitEvent } from 'react'; +import { useSearchParams } from 'react-router-dom'; import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps'; @@ -6,45 +7,166 @@ import Button from '../../components/ui/Button/Button'; import EmptyState from '../../components/ui/EmptyState/EmptyState'; import Field from '../../components/ui/Field/Field'; import Pagination from '../../components/ui/Pagination/Pagination'; +import Toast, { type ToastTone } from '../../components/ui/Toast/Toast'; import { SearchIcon } from '../../icons/navigation'; +import { useAppStore } from '../../store'; +import type { Recipe } from '../../types/recipe'; +import { RECIPE_PAGE_SIZE } from '../../lib/recipeBrowse/recipeBrowse'; +import ExploreControls from './ExploreControls'; +import { + DEFAULT_EXPLORE_FILTER_STATE, + countActiveExploreFilters, + getExploreQueryFilters, + type ExploreBrowseState, +} from './exploreBrowseState'; +import { + createExploreSearchParams, + readExploreUrlState, + type ExploreUrlState, +} from './exploreUrlState'; import { getMockExploreResult } from './mockExploreQuery'; import './ExplorePage.css'; -const PAGE_SIZE = 6; +type SaveFeedback = { + tone: ToastTone; + title: string; + message: string; +}; function ExplorePage() { const searchInputRef = useRef(null); - const [searchInput, setSearchInput] = useState(''); - const [searchTerm, setSearchTerm] = useState(''); - const [currentPage, setCurrentPage] = useState(1); + const [searchParams, setSearchParams] = useSearchParams(); + + const currentUser = useAppStore((state) => state.currentUser); + + const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); + + const setRecipeSaved = useAppStore((state) => state.setRecipeSaved); + + const [saveFeedback, setSaveFeedback] = useState(null); + + const { search, browseState, page } = useMemo( + () => readExploreUrlState(searchParams), + [searchParams], + ); + + /* + * The text currently being typed is temporary UI state. + * + * The submitted search is stored in the URL together with filters, + * sorting, and pagination. + */ + const [searchInput, setSearchInput] = useState(search); + + const queryFilters = getExploreQueryFilters(browseState); const result = getMockExploreResult({ - search: searchTerm, - page: currentPage, - pageSize: PAGE_SIZE, + search, + ...queryFilters, + page, + pageSize: RECIPE_PAGE_SIZE, }); + const activeFilterCount = countActiveExploreFilters(browseState); + + const hasSearch = search.length > 0; + const hasActiveFilters = activeFilterCount > 0; + const hasSearchOrFilters = hasSearch || hasActiveFilters; + + /* + * Browser Back/Forward may change the committed search in the URL. + * Keep the visible search input synchronized with that state. + */ + useEffect(() => { + setSearchInput(search); + }, [search]); + + /* + * paginate() clamps out-of-range pages. + * + * If the URL requests a page that no longer exists, replace the invalid + * URL page with the normalized page returned by the query. + */ + useEffect(() => { + if (result.page === page) { + return; + } + + setSearchParams( + createExploreSearchParams({ + search, + browseState, + page: result.page, + }), + { + replace: true, + }, + ); + }, [browseState, page, result.page, search, setSearchParams]); + + function updateUrlState(nextState: ExploreUrlState, replace = false) { + setSearchParams(createExploreSearchParams(nextState), { + replace, + }); + } + function handleSearchSubmit(event: SubmitEvent) { event.preventDefault(); - setSearchTerm(searchInput.trim()); - setCurrentPage(1); + updateUrlState({ + search: searchInput, + browseState, + page: 1, + }); + } + + function handleBrowseStateChange(nextBrowseState: ExploreBrowseState) { + /* + * Once Custom maximum is selected, typing the number can trigger several + * state updates. Replace those intermediate history entries instead of + * creating ?maxTime=4, then ?maxTime=45 as separate Back-button steps. + */ + const replaceCurrentEntry = + browseState.cookingTime === 'custom' && + nextBrowseState.cookingTime === 'custom'; + + updateUrlState( + { + search, + browseState: nextBrowseState, + page: 1, + }, + replaceCurrentEntry, + ); } - function handleClearSearch() { + function handleClearResultCriteria() { + const nextBrowseState: ExploreBrowseState = { + ...DEFAULT_EXPLORE_FILTER_STATE, + sort: browseState.sort, + }; + setSearchInput(''); - setSearchTerm(''); - setCurrentPage(1); + + updateUrlState({ + search: '', + browseState: nextBrowseState, + page: 1, + }); requestAnimationFrame(() => { searchInputRef.current?.focus(); }); } - function handlePageChange(page: number) { - setCurrentPage(page); + function handlePageChange(nextPage: number) { + updateUrlState({ + search, + browseState, + page: nextPage, + }); window.scrollTo({ top: 0, @@ -53,6 +175,52 @@ function ExplorePage() { }); } + function handleRecipeSaveChange(recipe: Recipe, saved: boolean) { + setRecipeSaved(recipe.id, saved); + + setSaveFeedback( + saved + ? { + tone: 'success', + title: 'Recipe saved', + message: `“${recipe.title}” was saved to My Cookbook.`, + } + : { + tone: 'info', + title: 'Recipe removed', + message: `“${recipe.title}” was removed from My Cookbook.`, + }, + ); + } + + let emptyStateTitle = 'No recipes available'; + + if (hasSearch) { + emptyStateTitle = `No recipes found for “${search}”`; + } else if (hasActiveFilters) { + emptyStateTitle = 'No recipes found with these filters'; + } else if (browseState.sort === 'trending') { + emptyStateTitle = 'No trending recipes available'; + } + + let emptyStateDescription = 'There are no public recipes to show right now.'; + + if (hasSearchOrFilters) { + emptyStateDescription = + 'Try changing your search or filters, or clear them to see more recipes.'; + } else if (browseState.sort === 'trending') { + emptyStateDescription = + 'Try another sort option to browse the full recipe catalog.'; + } + + let clearActionLabel = 'Clear filters'; + + if (hasSearch && hasActiveFilters) { + clearActionLabel = 'Clear search and filters'; + } else if (hasSearch) { + clearActionLabel = 'Clear search'; + } + return (
@@ -83,9 +251,16 @@ function ExplorePage() { setSearchInput(value); - if (value === '' && searchTerm !== '') { - setSearchTerm(''); - setCurrentPage(1); + /* + * Preserve the existing Explore behavior where emptying a + * previously submitted search immediately clears that search. + */ + if (value === '' && search !== '') { + updateUrlState({ + search: '', + browseState, + page: 1, + }); } }} /> @@ -103,30 +278,48 @@ function ExplorePage() { Recipe results -
-

- {result.totalItems} {result.totalItems === 1 ? 'recipe' : 'recipes'}{' '} - found - - {searchTerm ? ` for “${searchTerm}”` : ''} - {result.pageCount > 0 - ? `. Page ${result.page} of ${result.pageCount}.` - : '.'} - -

- - {/* - D1-11: - Filter and sort controls will be added here. - */} -
+ + +

+ {result.totalItems} {result.totalItems === 1 ? 'recipe' : 'recipes'}{' '} + found + + {search ? ` for “${search}”` : ''} + + {result.pageCount > 0 + ? `. Page ${result.page} of ${result.pageCount}.` + : '.'} + +

{result.totalItems > 0 ? ( <>
- {result.items.map((recipe) => ( - - ))} + {result.items.map((recipe) => { + const saved = savedRecipeIds.includes(recipe.id); + + const canSave = + currentUser !== null && + recipe.visibility === 'public' && + !recipe.isCreatedByCurrentUser; + + return ( + + handleRecipeSaveChange(recipe, nextSaved) + : undefined + } + /> + ); + })}
@@ -141,26 +334,31 @@ function ExplorePage() { ) : ( - Clear search + hasSearchOrFilters ? ( + ) : undefined } /> )} + + {saveFeedback ? ( +
+ setSaveFeedback(null)} + > + {saveFeedback.message} + +
+ ) : null}
); } diff --git a/apps/web/src/features/explore/SERVER_INTEGRATION.md b/apps/web/src/features/explore/SERVER_INTEGRATION.md new file mode 100644 index 0000000..1c9e533 --- /dev/null +++ b/apps/web/src/features/explore/SERVER_INTEGRATION.md @@ -0,0 +1,360 @@ +# Explore server integration + +The current Explore implementation uses local mock data, but the feature is structured so the UI can later be connected to a GraphQL/API backend without redesigning the page. + +The main goal of the migration is to replace the mock data boundary while keeping the existing URL state, filter-state conversion, page structure, and presentation components. + +## Current flow + +```text +URL query params +→ exploreUrlState.ts +→ ExploreBrowseState +→ getExploreQueryFilters(...) +→ mockExploreQuery.ts +→ paginated recipe result +→ ExplorePage.tsx +→ RecipeCard +``` + +`ExplorePage.tsx` is intentionally not responsible for implementing search, filtering, sorting, or pagination rules itself. + +Instead, it: + +1. reads the current browse state from the URL +2. converts UI-specific filter state into query-friendly values +3. requests a result from the data layer +4. renders the returned recipes and pagination metadata +5. writes browse-state changes back to the URL + +That separation should remain when the backend is introduced. + +## Main files and responsibilities + +### `ExplorePage.tsx` + +This is the page and interaction layer. + +It currently: + +- reads URL state +- owns the unsubmitted search input +- calls the mock Explore query +- renders the result count, recipe cards, empty state, and pagination +- updates the URL when search, filters, sorting, or page changes +- connects Save/Saved UI to shared application state + +When server data is introduced, the main change here should be replacing the synchronous mock query call with data from a GraphQL/API query. + +Today: + +```ts +const result = getMockExploreResult({ + search, + category, + maxCookingMinutes, + sort, + page, + pageSize, +}); +``` + +Later, this could become something conceptually like: + +```ts +const { data, loading, error } = useExploreRecipesQuery({ + variables: { + input: { + search, + category, + maxCookingMinutes, + sort, + page, + pageSize, + }, + }, +}); +``` + +The exact GraphQL client and hook names can be decided later. + +### `exploreUrlState.ts` + +This file should stay responsible for translating between browser query parameters and Explore state. + +For example: + +```text +/project2/?q=pasta&category=dinner&time=lte30&sort=popular&page=2 +``` + +can become frontend state such as: + +```ts +{ + search: 'pasta', + browseState: { + category: 'dinner', + cookingTime: 'lte30', + customMaxMinutes: null, + sort: 'popular', + }, + page: 2, +} +``` + +Keeping this logic in the frontend preserves: + +- refresh behavior +- Back/Forward navigation +- shareable browse URLs +- returning from Recipe Detail to the same result context + +The server does not need to understand UI-specific URL values such as `time=lte30`. + +### `exploreBrowseState.ts` + +This file defines the Explore filter and sort options and converts UI values into query-friendly values. + +For example: + +```text +lte30 +``` + +is a frontend option, while the query layer receives: + +```ts +maxCookingMinutes: 30; +``` + +That same conversion can be used when creating GraphQL variables. + +For example: + +```ts +{ + category: 'dinner', + maxCookingMinutes: 30, + sort: 'popular', +} +``` + +The backend should receive domain values, not frontend option IDs such as `lte15`, `lte30`, or `custom`. + +### `mockExploreQuery.ts` + +This is the main mock data boundary. + +Today it performs work that a backend would normally perform: + +- public/private visibility filtering +- text search +- category filtering +- cooking-time filtering +- Trending filtering +- sorting +- pagination +- pagination metadata calculation + +Conceptually, it acts as a temporary local backend. + +When the real backend exists, this logic should move out of the browser and into the server/data layer. + +## What should move to the backend + +With GraphQL or another API, the server should normally handle: + +- returning only recipes the user is allowed to discover +- searching title, description, tags, and ingredients +- applying category filters +- applying maximum cooking-time filters +- implementing Trending / Most popular / Newest / Most saved ordering +- paginating after filtering and sorting +- returning pagination metadata + +The frontend should send query variables and render the result rather than loading the full recipe dataset and filtering it locally. + +For example: + +```ts +{ + search: 'pasta', + category: 'dinner', + maxCookingMinutes: 30, + sort: 'popular', + page: 2, + pageSize: 6, +} +``` + +A useful server response shape would remain close to the current mock result: + +```ts +{ + items, + totalItems, + page, + pageCount, +} +``` + +This allows the existing result count and pagination UI to stay mostly unchanged. + +## Possible GraphQL shape + +The exact schema does not need to match this, but a future query could look approximately like: + +```graphql +query ExploreRecipes($input: ExploreRecipesInput!) { + exploreRecipes(input: $input) { + items { + id + title + description + category + cuisine + prepMinutes + cookMinutes + servings + tags + imageUrl + + author { + id + name + } + + rating { + average + count + } + + saveCount + isSaved + isCreatedByCurrentUser + createdAt + } + + totalItems + page + pageCount + } +} +``` + +Possible variables: + +```ts +{ + input: { + search: 'pasta', + category: 'dinner', + maxCookingMinutes: 30, + sort: 'popular', + page: 2, + pageSize: 6, + }, +} +``` + +## Saved recipes + +Keep aggregate save data and current-user saved state separate. + +```text +saveCount +``` + +means how many users have saved a recipe and is used for **Most saved** sorting. + +```text +isSaved / savedRecipeIds +``` + +represents whether the current user has saved that recipe. + +Today, `savedRecipeIds` is in-memory Zustand state seeded from mock recipe data. + +With a backend, the server should become the source of truth for this relationship. + +Saving could later become a mutation such as: + +```graphql +mutation SaveRecipe($recipeId: ID!) { + saveRecipe(recipeId: $recipeId) { + recipeId + isSaved + } +} +``` + +Unsaving could use a separate mutation or a single mutation that accepts the desired saved state. + +After a successful mutation, the frontend cache/shared state should update so that Explore, Recipe Detail, and My Cookbook all show the same state. + +## Recommended migration path + +A reasonable migration is: + +1. Keep `exploreUrlState.ts` and `exploreBrowseState.ts`. +2. Introduce a GraphQL/API data-access layer for Explore. +3. Replace `getMockExploreResult(...)` in `ExplorePage.tsx` with the server query result. +4. Add loading and error states for asynchronous requests. +5. Move filtering, sorting, visibility rules, and pagination to the server. +6. Replace in-memory save updates with mutations and synchronized server-backed state. +7. Remove or retain `mockExploreQuery.ts` only for tests/development once production uses real data. + +A future feature structure could look like: + +```text +features/explore/ + ExplorePage.tsx + ExploreControls.tsx + exploreBrowseState.ts + exploreUrlState.ts + queries/ + exploreRecipes.graphql + useExploreRecipes.ts +``` + +The exact structure can be adjusted to match the GraphQL tooling chosen by the project. + +## What should stay in the frontend + +The following should remain frontend responsibilities: + +- URL parsing and serialization +- labels such as `15 min or less` and `Most popular` +- temporary UI state such as open sheets/dialogs and unsubmitted search text +- rendering recipe cards +- rendering pagination controls +- showing loading, empty, error, and success feedback + +Presentation components such as `RecipeCard`, `Pagination`, `Select`, and `Toast` should remain unaware of whether data came from mock arrays, GraphQL, REST, or another backend. + +## Target flow + +The final server-backed Explore flow should roughly be: + +```text +User changes search/filter/sort/page + ↓ +URL is updated + ↓ +exploreUrlState.ts parses URL + ↓ +exploreBrowseState.ts converts UI values + ↓ +GraphQL/API variables are created + ↓ +Server applies search/filter/sort/pagination + ↓ +Server returns recipes + pagination metadata + ↓ +ExplorePage.tsx renders the result + ↓ +RecipeCard renders each recipe +``` + +The goal is therefore to replace the current mock data source, not rebuild the Explore UI. diff --git a/apps/web/src/features/explore/exploreBrowseState.test.ts b/apps/web/src/features/explore/exploreBrowseState.test.ts new file mode 100644 index 0000000..09d5710 --- /dev/null +++ b/apps/web/src/features/explore/exploreBrowseState.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; + +import { + DEFAULT_EXPLORE_BROWSE_STATE, + getExploreQueryFilters, + type ExploreCookingTime, +} from './exploreBrowseState'; + +const cookingTimeCases: Array<[ExploreCookingTime, number | null]> = [ + ['any', null], + ['lte15', 15], + ['lte30', 30], + ['lte60', 60], +]; + +describe('getExploreQueryFilters', () => { + it.each(cookingTimeCases)( + 'maps %s to maxCookingMinutes=%s', + (cookingTime, maxCookingMinutes) => { + expect( + getExploreQueryFilters({ + ...DEFAULT_EXPLORE_BROWSE_STATE, + cookingTime, + }), + ).toEqual({ + category: null, + maxCookingMinutes, + sort: 'trending', + }); + }, + ); + + it('maps a custom maximum and category to query values', () => { + expect( + getExploreQueryFilters({ + category: 'dinner', + cookingTime: 'custom', + customMaxMinutes: 45, + sort: 'most-saved', + }), + ).toEqual({ + category: 'dinner', + maxCookingMinutes: 45, + sort: 'most-saved', + }); + }); +}); diff --git a/apps/web/src/features/explore/exploreBrowseState.ts b/apps/web/src/features/explore/exploreBrowseState.ts new file mode 100644 index 0000000..28cea75 --- /dev/null +++ b/apps/web/src/features/explore/exploreBrowseState.ts @@ -0,0 +1,83 @@ +import { + DEFAULT_RECIPE_FILTER_STATE, + RECIPE_CATEGORY_OPTIONS, + RECIPE_COOKING_TIME_OPTIONS, + countActiveRecipeFilters, + getRecipeQueryFilters, + isRecipeCategory, + isRecipeCookingTime, + type RecipeCategory, + type RecipeCookingTime, + type RecipeFilterState, + type RecipeQueryFilters, +} from '../../lib/recipeBrowse/recipeBrowse'; + +export const EXPLORE_CATEGORY_OPTIONS = RECIPE_CATEGORY_OPTIONS; +export type ExploreCategory = RecipeCategory; + +export const EXPLORE_COOKING_TIME_OPTIONS = RECIPE_COOKING_TIME_OPTIONS; +export type ExploreCookingTime = RecipeCookingTime; + +export const EXPLORE_SORT_OPTIONS = [ + { value: 'trending', label: 'Trending' }, + { value: 'popular', label: 'Most popular' }, + { value: 'newest', label: 'Newest' }, + { value: 'most-saved', label: 'Most saved' }, +] as const; + +export type ExploreSort = (typeof EXPLORE_SORT_OPTIONS)[number]['value']; + +export type ExploreFilterState = RecipeFilterState; + +export type ExploreBrowseState = ExploreFilterState & { + sort: ExploreSort; +}; + +export type ExploreQueryFilters = RecipeQueryFilters & { + sort: ExploreSort; +}; + +export const DEFAULT_EXPLORE_FILTER_STATE: ExploreFilterState = { + ...DEFAULT_RECIPE_FILTER_STATE, +}; + +export const DEFAULT_EXPLORE_BROWSE_STATE: ExploreBrowseState = { + ...DEFAULT_EXPLORE_FILTER_STATE, + sort: 'trending', +}; + +export function isExploreCategory( + value: string | null, +): value is ExploreCategory { + return isRecipeCategory(value); +} + +export function isExploreCookingTime( + value: string | null, +): value is ExploreCookingTime { + return isRecipeCookingTime(value); +} + +export function isExploreSort(value: string | null): value is ExploreSort { + return EXPLORE_SORT_OPTIONS.some((option) => option.value === value); +} + +export function getExploreQueryFilters( + state: ExploreBrowseState, +): ExploreQueryFilters { + return { + ...getRecipeQueryFilters(state), + sort: state.sort, + }; +} + +export function countActiveExploreFilters(state: ExploreFilterState) { + return countActiveRecipeFilters(state); +} + +export function getExploreSortLabel(sort: ExploreSort) { + return ( + EXPLORE_SORT_OPTIONS.find((option) => option.value === sort)?.label ?? + 'Trending' + ); +} diff --git a/apps/web/src/features/explore/exploreUrlState.test.ts b/apps/web/src/features/explore/exploreUrlState.test.ts new file mode 100644 index 0000000..5f35837 --- /dev/null +++ b/apps/web/src/features/explore/exploreUrlState.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_EXPLORE_BROWSE_STATE } from './exploreBrowseState'; +import { + createExploreSearchParams, + readExploreUrlState, +} from './exploreUrlState'; + +describe('Explore URL state', () => { + it('uses the default browse state for an empty URL', () => { + expect(readExploreUrlState(new URLSearchParams())).toEqual({ + search: '', + browseState: DEFAULT_EXPLORE_BROWSE_STATE, + page: 1, + }); + }); + + it('parses search, category, cooking time, sort, and page', () => { + const state = readExploreUrlState( + new URLSearchParams( + 'q=pasta&category=dinner&time=lte30&sort=popular&page=2', + ), + ); + + expect(state).toEqual({ + search: 'pasta', + + browseState: { + category: 'dinner', + cookingTime: 'lte30', + customMaxMinutes: null, + sort: 'popular', + }, + + page: 2, + }); + }); + + it('parses a custom maximum cooking time', () => { + const state = readExploreUrlState( + new URLSearchParams('time=custom&maxTime=45'), + ); + + expect(state.browseState).toEqual({ + category: 'all', + cookingTime: 'custom', + customMaxMinutes: 45, + sort: 'trending', + }); + }); + + it('safely keeps an incomplete custom filter without applying a maximum', () => { + const state = readExploreUrlState(new URLSearchParams('time=custom')); + + expect(state.browseState.cookingTime).toBe('custom'); + expect(state.browseState.customMaxMinutes).toBeNull(); + }); + + it('falls back safely for unknown values', () => { + const state = readExploreUrlState( + new URLSearchParams( + 'category=unknown&time=wrong&sort=random&page=invalid', + ), + ); + + expect(state).toEqual({ + search: '', + browseState: DEFAULT_EXPLORE_BROWSE_STATE, + page: 1, + }); + }); + + it('omits defaults when serializing', () => { + const params = createExploreSearchParams({ + search: '', + browseState: DEFAULT_EXPLORE_BROWSE_STATE, + page: 1, + }); + + expect(params.toString()).toBe(''); + }); + + it('serializes and restores a non-default browse context', () => { + const params = createExploreSearchParams({ + search: ' curry ', + + browseState: { + category: 'dinner', + cookingTime: 'custom', + customMaxMinutes: 50, + sort: 'most-saved', + }, + + page: 3, + }); + + expect(params.toString()).toBe( + 'q=curry&category=dinner&time=custom&maxTime=50&sort=most-saved&page=3', + ); + + expect(readExploreUrlState(params)).toEqual({ + search: 'curry', + + browseState: { + category: 'dinner', + cookingTime: 'custom', + customMaxMinutes: 50, + sort: 'most-saved', + }, + + page: 3, + }); + }); +}); diff --git a/apps/web/src/features/explore/exploreUrlState.ts b/apps/web/src/features/explore/exploreUrlState.ts new file mode 100644 index 0000000..e43f2e7 --- /dev/null +++ b/apps/web/src/features/explore/exploreUrlState.ts @@ -0,0 +1,100 @@ +import { + DEFAULT_EXPLORE_BROWSE_STATE, + isExploreCategory, + isExploreCookingTime, + isExploreSort, + type ExploreBrowseState, +} from './exploreBrowseState'; + +export type ExploreUrlState = { + search: string; + browseState: ExploreBrowseState; + page: number; +}; + +function parsePositiveInteger(value: string | null) { + if (!value) { + return null; + } + + const parsed = Number(value); + + return Number.isInteger(parsed) && parsed > 0 ? parsed : null; +} + +export function readExploreUrlState( + searchParams: URLSearchParams, +): ExploreUrlState { + const categoryParam = searchParams.get('category'); + const cookingTimeParam = searchParams.get('time'); + const sortParam = searchParams.get('sort'); + + const category = isExploreCategory(categoryParam) + ? categoryParam + : DEFAULT_EXPLORE_BROWSE_STATE.category; + + const cookingTime = isExploreCookingTime(cookingTimeParam) + ? cookingTimeParam + : DEFAULT_EXPLORE_BROWSE_STATE.cookingTime; + + const sort = isExploreSort(sortParam) + ? sortParam + : DEFAULT_EXPLORE_BROWSE_STATE.sort; + + const customMaxMinutes = + cookingTime === 'custom' + ? parsePositiveInteger(searchParams.get('maxTime')) + : null; + + return { + search: (searchParams.get('q') ?? '').trim(), + + browseState: { + category, + cookingTime, + customMaxMinutes, + sort, + }, + + page: parsePositiveInteger(searchParams.get('page')) ?? 1, + }; +} + +export function createExploreSearchParams({ + search, + browseState, + page, +}: ExploreUrlState) { + const searchParams = new URLSearchParams(); + + const trimmedSearch = search.trim(); + + if (trimmedSearch) { + searchParams.set('q', trimmedSearch); + } + + if (browseState.category !== 'all') { + searchParams.set('category', browseState.category); + } + + if (browseState.cookingTime !== 'any') { + searchParams.set('time', browseState.cookingTime); + + if ( + browseState.cookingTime === 'custom' && + browseState.customMaxMinutes !== null + ) { + searchParams.set('maxTime', String(browseState.customMaxMinutes)); + } + } + + if (browseState.sort !== 'trending') { + searchParams.set('sort', browseState.sort); + } + + if (page > 1) { + searchParams.set('page', String(page)); + } + + return searchParams; +} diff --git a/apps/web/src/features/explore/mockExploreQuery.test.ts b/apps/web/src/features/explore/mockExploreQuery.test.ts index 6a6ecd8..674fa26 100644 --- a/apps/web/src/features/explore/mockExploreQuery.test.ts +++ b/apps/web/src/features/explore/mockExploreQuery.test.ts @@ -1,78 +1,267 @@ import { describe, expect, it } from 'vitest'; -import { getMockExploreResult } from './mockExploreQuery'; +import { + getMockExploreResult, + MOCK_EXPLORE_NOW, + type ExploreQuery, +} from './mockExploreQuery'; + +function createQuery(overrides: Partial = {}): ExploreQuery { + return { + search: '', + category: null, + maxCookingMinutes: null, + sort: 'popular', + page: 1, + pageSize: 50, + ...overrides, + }; +} describe('getMockExploreResult', () => { it('only returns public recipes', () => { - const result = getMockExploreResult({ - search: '', - page: 1, - pageSize: 50, - }); + const result = getMockExploreResult(createQuery()); expect(result.items.every((recipe) => recipe.visibility === 'public')).toBe( true, ); }); - it('searches recipe titles and descriptions case-insensitively', () => { - const result = getMockExploreResult({ - search: 'SALMON', - page: 1, - pageSize: 6, - }); + it('searches titles and descriptions case-insensitively', () => { + const result = getMockExploreResult( + createQuery({ + search: 'SALMON', + }), + ); expect(result.items.map((recipe) => recipe.id)).toContain('salmon-pasta'); }); it('searches ingredient names', () => { - const result = getMockExploreResult({ - search: 'salmon fillet', - page: 1, - pageSize: 6, - }); + const result = getMockExploreResult( + createQuery({ + search: 'salmon fillet', + }), + ); expect(result.items.map((recipe) => recipe.id)).toContain('salmon-pasta'); }); it('searches tags and treats hyphens like spaces', () => { - const result = getMockExploreResult({ - search: 'one pan', - page: 1, - pageSize: 6, - }); + const result = getMockExploreResult( + createQuery({ + search: 'one pan', + }), + ); expect(result.items.map((recipe) => recipe.id)).toContain('shakshuka'); }); - it('returns paginated results', () => { - const firstPage = getMockExploreResult({ - search: '', - page: 1, - pageSize: 6, - }); + it('filters by category before pagination', () => { + const result = getMockExploreResult( + createQuery({ + category: 'dinner', + page: 2, + pageSize: 2, + }), + ); - const secondPage = getMockExploreResult({ - search: '', - page: 2, - pageSize: 6, - }); + expect(result.totalItems).toBe(6); + expect(result.items).toHaveLength(2); - expect(firstPage.items).toHaveLength(6); - expect(secondPage.items.length).toBeGreaterThan(0); + expect(result.items.every((recipe) => recipe.category === 'Dinner')).toBe( + true, + ); + }); + + it('supports the 15-minute maximum', () => { + const result = getMockExploreResult( + createQuery({ + maxCookingMinutes: 15, + }), + ); + + expect( + result.items.every( + (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 15, + ), + ).toBe(true); + }); + + it('supports the 30-minute maximum', () => { + const result = getMockExploreResult( + createQuery({ + maxCookingMinutes: 30, + }), + ); + + expect(result.totalItems).toBe(2); - expect(firstPage.page).toBe(1); - expect(secondPage.page).toBe(2); + expect( + result.items.every( + (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 30, + ), + ).toBe(true); + }); + + it('supports the 60-minute maximum', () => { + const result = getMockExploreResult( + createQuery({ + maxCookingMinutes: 60, + }), + ); + + expect(result.totalItems).toBe(7); + + expect( + result.items.every( + (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 60, + ), + ).toBe(true); + }); + + it('supports a custom maximum cooking time', () => { + const result = getMockExploreResult( + createQuery({ + maxCookingMinutes: 45, + }), + ); + + expect( + result.items.every( + (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 45, + ), + ).toBe(true); + }); + + it('makes larger maximum-time presets cumulative', () => { + const under15 = getMockExploreResult( + createQuery({ + maxCookingMinutes: 15, + }), + ); + + const under30 = getMockExploreResult( + createQuery({ + maxCookingMinutes: 30, + }), + ); + + const under60 = getMockExploreResult( + createQuery({ + maxCookingMinutes: 60, + }), + ); + + expect(under30.totalItems).toBeGreaterThanOrEqual(under15.totalItems); + + expect(under60.totalItems).toBeGreaterThanOrEqual(under30.totalItems); + }); + + it('sorts Most popular using rating average and rating count', () => { + const result = getMockExploreResult( + createQuery({ + sort: 'popular', + }), + ); + + expect(result.items.slice(0, 3).map((recipe) => recipe.id)).toEqual([ + 'chicken-biryani', + 'norwegian-waffles', + 'shakshuka', + ]); + }); + + it('limits Trending to the previous 14 days and ranks by popularity', () => { + const result = getMockExploreResult( + createQuery({ + sort: 'trending', + }), + ); + + const now = Date.parse(MOCK_EXPLORE_NOW); + const cutoff = now - 14 * 24 * 60 * 60 * 1000; + + expect( + result.items.every((recipe) => { + const createdAt = Date.parse(recipe.createdAt); + + return createdAt >= cutoff && createdAt <= now; + }), + ).toBe(true); + + expect(result.items.map((recipe) => recipe.id)).toEqual([ + 'falafel-bowl', + 'thai-green-curry', + 'sheet-pan-vegetables', + 'apple-cake', + ]); + }); + + it('sorts Newest by creation date descending', () => { + const result = getMockExploreResult( + createQuery({ + sort: 'newest', + }), + ); + + expect(result.items.slice(0, 3).map((recipe) => recipe.id)).toEqual([ + 'ultimate-double-cheeseburger', + 'thai-green-curry', + 'apple-cake', + ]); + }); + + it('sorts Most saved by aggregate save count', () => { + const result = getMockExploreResult( + createQuery({ + sort: 'most-saved', + }), + ); + + for (let index = 1; index < result.items.length; index += 1) { + const previous = result.items[index - 1]; + const current = result.items[index]; + + if (!previous || !current) { + continue; + } + + expect(previous.saveCount).toBeGreaterThanOrEqual(current.saveCount); + } + }); + + it('paginates only after filtering and sorting', () => { + const firstPage = getMockExploreResult( + createQuery({ + sort: 'popular', + page: 1, + pageSize: 6, + }), + ); + + const secondPage = getMockExploreResult( + createQuery({ + sort: 'popular', + page: 2, + pageSize: 6, + }), + ); + + expect(firstPage.totalItems).toBe(11); + expect(firstPage.items).toHaveLength(6); + expect(secondPage.items).toHaveLength(5); expect(firstPage.items[0]?.id).not.toBe(secondPage.items[0]?.id); }); - it('returns no items when the search has no matches', () => { - const result = getMockExploreResult({ - search: 'definitely-not-a-recipe', - page: 1, - pageSize: 6, - }); + it('returns no items when the combined query has no matches', () => { + const result = getMockExploreResult( + createQuery({ + search: 'definitely-not-a-recipe', + category: 'dinner', + }), + ); expect(result.items).toEqual([]); expect(result.totalItems).toBe(0); diff --git a/apps/web/src/features/explore/mockExploreQuery.ts b/apps/web/src/features/explore/mockExploreQuery.ts index ad5ac36..23b6b57 100644 --- a/apps/web/src/features/explore/mockExploreQuery.ts +++ b/apps/web/src/features/explore/mockExploreQuery.ts @@ -1,46 +1,126 @@ import { recipes } from '../../data/recipes'; import { paginate, type PageResult } from '../../lib/pagination/paginate'; +import { filterRecipesByBrowseCriteria } from '../../lib/recipeBrowse/recipeBrowse'; import type { Recipe } from '../../types/recipe'; +import type { ExploreCategory, ExploreSort } from './exploreBrowseState'; + export type ExploreQuery = { search: string; + category: Exclude | null; + maxCookingMinutes: number | null; + sort: ExploreSort; page: number; pageSize: number; }; export type ExploreResult = PageResult; -function normalizeSearchText(value: string) { - return value.trim().toLowerCase().replace(/[-_]+/g, ' ').replace(/\s+/g, ' '); +/** + * The mock catalog represents a fixed Delivery 1 snapshot. + * + * Trending therefore uses a fixed reference time instead of the real system + * clock. Otherwise the static recipes would eventually all become older than + * the 14-day trending window. + */ +export const MOCK_EXPLORE_NOW = '2026-09-05T12:00:00Z'; + +const MOCK_EXPLORE_NOW_MS = Date.parse(MOCK_EXPLORE_NOW); +const TRENDING_WINDOW_MS = 14 * 24 * 60 * 60 * 1000; + +export function getPopularityScore(recipe: Recipe) { + return recipe.rating.average * Math.log1p(recipe.rating.count); } -function matchesSearch(recipe: Recipe, search: string) { - if (!search) { - return true; +function compareNewest(a: Recipe, b: Recipe) { + const dateDifference = Date.parse(b.createdAt) - Date.parse(a.createdAt); + + if (dateDifference !== 0) { + return dateDifference; } - const searchableValues = [ - recipe.title, - recipe.description, - ...recipe.tags, - ...recipe.ingredients.map((ingredient) => ingredient.name), - ]; + return a.id.localeCompare(b.id); +} - return searchableValues.some((value) => - normalizeSearchText(value).includes(search), - ); +function comparePopular(a: Recipe, b: Recipe) { + const popularityDifference = getPopularityScore(b) - getPopularityScore(a); + + if (popularityDifference !== 0) { + return popularityDifference; + } + + const ratingCountDifference = b.rating.count - a.rating.count; + + if (ratingCountDifference !== 0) { + return ratingCountDifference; + } + + const ratingAverageDifference = b.rating.average - a.rating.average; + + if (ratingAverageDifference !== 0) { + return ratingAverageDifference; + } + + return compareNewest(a, b); +} + +function compareMostSaved(a: Recipe, b: Recipe) { + const saveCountDifference = b.saveCount - a.saveCount; + + if (saveCountDifference !== 0) { + return saveCountDifference; + } + + return comparePopular(a, b); +} + +function isTrendingRecipe(recipe: Recipe) { + const createdAt = Date.parse(recipe.createdAt); + + if (!Number.isFinite(createdAt)) { + return false; + } + + const trendingWindowStart = MOCK_EXPLORE_NOW_MS - TRENDING_WINDOW_MS; + + return createdAt >= trendingWindowStart && createdAt <= MOCK_EXPLORE_NOW_MS; +} + +const sortComparators: Record number> = { + trending: comparePopular, + popular: comparePopular, + newest: compareNewest, + 'most-saved': compareMostSaved, +}; + +function sortRecipes(items: readonly Recipe[], sort: ExploreSort) { + return [...items].sort(sortComparators[sort]); } export function getMockExploreResult({ search, + category, + maxCookingMinutes, + sort, page, pageSize, }: ExploreQuery): ExploreResult { - const normalizedSearch = normalizeSearchText(search); + const publicRecipes = recipes.filter( + (recipe) => recipe.visibility === 'public', + ); + + const filteredRecipes = filterRecipesByBrowseCriteria(publicRecipes, { + search, + category, + maxCookingMinutes, + }); + + const sortCandidates = + sort === 'trending' + ? filteredRecipes.filter(isTrendingRecipe) + : filteredRecipes; - const matchingRecipes = recipes - .filter((recipe) => recipe.visibility === 'public') - .filter((recipe) => matchesSearch(recipe, normalizedSearch)); + const sortedRecipes = sortRecipes(sortCandidates, sort); - return paginate(matchingRecipes, page, pageSize); + return paginate(sortedRecipes, page, pageSize); } diff --git a/apps/web/src/features/not-found/NotFoundPage.css b/apps/web/src/features/not-found/NotFoundPage.css new file mode 100644 index 0000000..7423458 --- /dev/null +++ b/apps/web/src/features/not-found/NotFoundPage.css @@ -0,0 +1,108 @@ +@layer components { + .not-found-page { + display: grid; + place-items: center; + + min-height: 72dvh; + padding: var(--space-10) var(--space-4) var(--space-16); + } + + .not-found-page__card { + display: flex; + flex-direction: column; + align-items: center; + + width: min(100%, 39rem); + padding: var(--space-10) var(--space-8) var(--space-8); + + text-align: center; + + background-color: var(--color-surface); + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-xl); + box-shadow: var(--shadow-md); + } + + .not-found-page__illustration { + width: clamp(5rem, 12vw, 7rem); + height: auto; + + margin-block-end: var(--space-3); + + object-fit: contain; + } + + .not-found-page__content { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-2); + } + + .not-found-page__code { + margin: 0; + + font-size: clamp(4rem, 9vw, 5.5rem); + font-weight: var(--font-weight-bold); + line-height: 0.95; + letter-spacing: -0.04em; + } + + .not-found-page__title { + margin: 0; + + font-size: var(--font-size-2xl); + font-weight: var(--font-weight-bold); + line-height: var(--line-height-tight); + } + + .not-found-page__description { + margin: 0; + + color: var(--color-text-secondary); + + font-size: var(--font-size-lg); + line-height: var(--line-height-relaxed); + } + + .not-found-page__actions { + display: flex; + justify-content: center; + gap: var(--space-3); + + width: 100%; + margin-block-start: var(--space-6); + } + + .not-found-page__actions > * { + min-width: 9.5rem; + } + + .not-found-page__hint { + margin: var(--space-5) 0 0; + + color: var(--color-text-secondary); + + font-size: var(--font-size-sm); + line-height: var(--line-height-relaxed); + } + + @media (max-width: 36rem) { + .not-found-page { + min-height: auto; + padding-block: var(--space-8) var(--space-12); + } + + .not-found-page__card { + padding: var(--space-8) var(--space-5); + } + + .not-found-page__actions { + flex-direction: column; + } + + .not-found-page__actions > * { + width: 100%; + } + } +} diff --git a/apps/web/src/features/not-found/NotFoundPage.tsx b/apps/web/src/features/not-found/NotFoundPage.tsx new file mode 100644 index 0000000..fe0e204 --- /dev/null +++ b/apps/web/src/features/not-found/NotFoundPage.tsx @@ -0,0 +1,63 @@ +import { useNavigate } from 'react-router-dom'; + +import Button from '../../components/ui/Button/Button'; +import LinkButton from '../../components/ui/LinkButton/LinkButton'; +import chefHatIllustration from '../../assets/illustrations/not-found-chef-hat.png'; + +import './NotFoundPage.css'; + +function NotFoundPage() { + const navigate = useNavigate(); + + function handleGoBack() { + navigate(-1); + } + + return ( +
+
+ + +
+ + +

+ Page not found +

+ +

+ The recipe you’re looking for isn’t here. +

+
+ +
+ + Explore Recipes + + + +
+ +

+ Try searching or return to Explore. +

+
+
+ ); +} + +export default NotFoundPage; diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.css b/apps/web/src/features/recipe-detail/RecipeDetailPage.css new file mode 100644 index 0000000..7188470 --- /dev/null +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.css @@ -0,0 +1,540 @@ +@layer components { + .recipe-detail-page { + display: flex; + flex-direction: column; + gap: var(--space-4); + + padding-block: var(--space-6) var(--space-16); + } + + .recipe-detail-page--not-found { + min-height: 60dvh; + align-items: center; + justify-content: center; + } + + .recipe-detail-page__back-row { + display: flex; + align-items: center; + } + + .recipe-detail-page__back-button.button { + margin-inline-start: calc(var(--space-3) * -1); + + color: var(--color-text-secondary); + } + + .recipe-detail-page__hero-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: stretch; + gap: var(--space-4); + } + + .recipe-detail-page__content-grid { + display: grid; + grid-template-columns: minmax(18rem, 0.8fr) minmax(0, 1.2fr); + align-items: start; + gap: var(--space-4); + + scroll-margin-top: var(--space-16); + } + + .recipe-detail-page__media, + .recipe-detail-page__summary, + .recipe-detail-page__description-card, + .recipe-detail-page__content-card { + min-width: 0; + + background-color: var(--color-surface); + + border: var(--border-width-thin) solid var(--color-border-subtle); + border-radius: var(--radius-xl); + + box-shadow: var(--shadow-sm); + } + + .recipe-detail-page__media { + overflow: hidden; + + aspect-ratio: 4 / 3; + max-height: 36rem; + } + + .recipe-detail-page__image { + display: block; + + width: 100%; + height: 100%; + + object-fit: cover; + } + + .recipe-detail-page__image--fallback { + object-fit: cover; + } + + .recipe-detail-page__summary { + display: flex; + flex-direction: column; + gap: var(--space-4); + + padding: var(--space-6); + } + + .recipe-detail-page__title-row { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: var(--space-3); + } + + .recipe-detail-page__title-row h1 { + min-width: 0; + + font-size: var(--font-size-3xl); + } + + .recipe-detail-page__author-rating { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-4); + } + + .recipe-detail-page__author { + display: inline-flex; + align-items: center; + gap: var(--space-2); + + color: var(--color-text-secondary); + + font-size: var(--font-size-sm); + font-weight: var(--font-weight-medium); + } + + .recipe-detail-page__jump-button.button { + order: 2; + + width: 100%; + } + + .recipe-detail-page__description-card { + padding: var(--space-5) var(--space-6); + } + + .recipe-detail-page__description-card h2 { + margin-block-end: var(--space-3); + + font-size: var(--font-size-xl); + } + + .recipe-detail-page__description { + width: 100%; + + color: var(--color-text-secondary); + + line-height: var(--line-height-relaxed); + } + + .recipe-detail-page__description--mobile { + display: none; + } + + .recipe-detail-page__meta.recipe-meta { + gap: var(--space-6); + } + + .recipe-detail-page__meta .recipe-meta__item { + font-size: var(--font-size-sm); + } + + .recipe-detail-page__tags { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + + margin: 0; + padding: 0; + + list-style: none; + } + + .recipe-detail-page__tags > li { + display: flex; + } + + .recipe-detail-page__category.tag { + font-weight: var(--font-weight-semibold); + + border-color: var(--color-brand-primary); + } + + .recipe-detail-page__tags-toggle.button { + border-radius: var(--radius-full); + } + + .recipe-detail-page__actions { + order: 1; + + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-3); + + margin-block-start: auto; + } + + .recipe-detail-page__actions > :only-child { + grid-column: 1 / -1; + } + + .recipe-detail-page__actions > .button, + .recipe-detail-page__primary-action.button { + width: 100%; + } + + .recipe-detail-page__action--active.button { + color: var(--color-brand-primary-active); + background-color: var(--color-surface-selected); + + border-color: var(--color-brand-primary); + } + + .recipe-detail-page__action--active.button:hover { + background-color: color-mix( + in srgb, + var(--color-surface-selected) 65%, + var(--color-surface-pressed) + ); + } + + .recipe-detail-page__action--active.button:active { + background-color: var(--color-surface-pressed); + } + + .recipe-detail-page__servings-control { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-4); + + padding: var(--space-4); + + background-color: var(--color-surface-raised); + + border: var(--border-width-thin) solid var(--color-border-divider); + border-radius: var(--radius-lg); + } + + .recipe-detail-page__servings-control--mobile { + display: none; + } + + .recipe-detail-page__servings-control--desktop { + width: 100%; + + background-color: var(--color-surface-muted); + + border-color: var(--color-border-strong); + } + + .recipe-detail-page__servings-control h2 { + font-size: var(--font-size-md); + } + + .recipe-detail-page__servings-control p { + margin-block-start: var(--space-1); + + color: var(--color-text-muted); + + font-size: var(--font-size-xs); + } + + .recipe-detail-page__stepper { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: var(--space-3); + } + + .recipe-detail-page__servings-value { + display: flex; + flex-direction: column; + align-items: center; + + min-width: 4rem; + + color: var(--color-text-secondary); + + font-size: var(--font-size-xs); + line-height: var(--line-height-tight); + } + + .recipe-detail-page__servings-value strong { + color: var(--color-text-primary); + + font-size: var(--font-size-2xl); + line-height: var(--line-height-tight); + } + + .recipe-detail-page__content-card { + padding: var(--space-5); + } + + .recipe-detail-page__section-heading { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-3); + + margin-block-end: var(--space-4); + } + + .recipe-detail-page__section-heading h2 { + font-size: var(--font-size-2xl); + } + + .recipe-detail-page__section-heading > span { + color: var(--color-text-muted); + + font-size: var(--font-size-sm); + } + + .recipe-detail-page__ingredients, + .recipe-detail-page__instructions { + margin: 0; + padding: 0; + + list-style: none; + } + + .recipe-detail-page__ingredients li { + display: grid; + grid-template-columns: minmax(5.5rem, 0.35fr) minmax(0, 1fr); + gap: var(--space-4); + + padding-block: var(--space-3); + + border-top: var(--border-width-thin) solid var(--color-border-divider); + } + + .recipe-detail-page__ingredients li:first-child { + border-top: 0; + } + + .recipe-detail-page__ingredients strong { + color: var(--color-text-primary); + + white-space: nowrap; + } + + .recipe-detail-page__ingredients span { + min-width: 0; + + color: var(--color-text-secondary); + } + + .recipe-detail-page__instructions li { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: flex-start; + gap: var(--space-3); + + padding-block: var(--space-3); + + border-top: var(--border-width-thin) solid var(--color-border-divider); + } + + .recipe-detail-page__instructions li:first-child { + padding-block-start: 0; + + border-top: 0; + } + + .recipe-detail-page__instruction-number { + display: inline-flex; + align-items: center; + justify-content: center; + + width: 2rem; + height: 2rem; + + color: var(--color-brand-primary-active); + background-color: var(--color-brand-accent-soft); + + font-weight: var(--font-weight-semibold); + + border-radius: var(--radius-full); + } + + .recipe-detail-page__instructions p { + padding-block-start: var(--space-1); + + color: var(--color-text-secondary); + + line-height: var(--line-height-relaxed); + } + + .recipe-detail-page__toast-region { + position: fixed; + right: var(--space-6); + bottom: var(--space-6); + z-index: var(--z-overlay); + + width: min(24rem, calc(100% - (2 * var(--space-6)))); + } + + @media (min-width: 60.001rem) { + .recipe-detail-page__hero-grid--oversized-summary + .recipe-detail-page__media { + align-self: start; + + aspect-ratio: 5 / 4; + } + + .recipe-detail-page__title-row h1.recipe-detail-page__title--medium { + font-size: 2.375rem; + } + + .recipe-detail-page__title-row h1.recipe-detail-page__title--long { + font-size: 2.25rem; + } + } + + @media (max-width: 65em) and (min-width: 60.001rem) { + .recipe-detail-page__hero-grid { + grid-template-columns: 1fr; + align-items: start; + } + + .recipe-detail-page__media { + max-height: none; + + aspect-ratio: 16 / 9; + } + + .recipe-detail-page__hero-grid--oversized-summary + .recipe-detail-page__media { + align-self: auto; + + aspect-ratio: 16 / 9; + } + } + + @media (max-width: 60rem) { + .recipe-detail-page__hero-grid, + .recipe-detail-page__content-grid { + grid-template-columns: 1fr; + } + + .recipe-detail-page__hero-grid { + align-items: start; + } + + .recipe-detail-page__media { + max-height: none; + + aspect-ratio: 16 / 9; + } + + .recipe-detail-page__jump-button.button { + order: 0; + } + + .recipe-detail-page__description-card { + display: none; + } + + .recipe-detail-page__description--mobile { + display: block; + } + + .recipe-detail-page__actions { + order: 0; + + margin-block-start: 0; + } + + .recipe-detail-page__servings-control--desktop { + display: none; + } + + .recipe-detail-page__servings-control--mobile { + display: flex; + } + + .recipe-detail-page__content-grid { + gap: var(--space-4); + } + } + + @media (max-width: 44rem) { + .recipe-detail-page { + gap: var(--space-3); + + padding-block: var(--space-4) var(--space-12); + } + + .recipe-detail-page__back-button.button { + margin-inline-start: calc(var(--space-2) * -1); + } + + .recipe-detail-page__hero-grid, + .recipe-detail-page__content-grid { + gap: var(--space-3); + } + + .recipe-detail-page__media { + aspect-ratio: 4 / 3; + } + + .recipe-detail-page__summary, + .recipe-detail-page__content-card { + padding: var(--space-4); + } + + .recipe-detail-page__title-row { + align-items: center; + } + + .recipe-detail-page__title-row h1 { + font-size: var(--font-size-2xl); + } + + .recipe-detail-page__author-rating { + gap: var(--space-3); + } + + .recipe-detail-page__actions { + grid-template-columns: 1fr; + } + + .recipe-detail-page__servings-control { + align-items: flex-start; + flex-direction: column; + } + + .recipe-detail-page__stepper { + justify-content: center; + + width: 100%; + } + + .recipe-detail-page__section-heading h2 { + font-size: var(--font-size-xl); + } + + .recipe-detail-page__ingredients li { + grid-template-columns: minmax(4.75rem, auto) minmax(0, 1fr); + gap: var(--space-3); + } + + .recipe-detail-page__toast-region { + right: var(--space-4); + bottom: var(--space-4); + left: var(--space-4); + + width: auto; + } + } +} diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx new file mode 100644 index 0000000..68a2a1b --- /dev/null +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx @@ -0,0 +1,206 @@ +import '@testing-library/jest-dom/vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { INITIAL_SAVED_RECIPE_IDS, useAppStore } from '../../store'; + +import RecipeDetailPage from './RecipeDetailPage'; + +function LocationProbe() { + const location = useLocation(); + + return ( + + {`${location.pathname}${location.search}`} + + ); +} + +function renderRecipeDetail( + initialEntry: + | string + | { + pathname: string; + state?: unknown; + }, +) { + return render( + + + } /> + } /> + + , + ); +} + +describe('RecipeDetailPage', () => { + beforeEach(() => { + useAppStore.setState({ + savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], + userRatings: {}, + }); + }); + + it('shows public non-owner recipe actions and total cooking time', () => { + renderRecipeDetail('/recipes/salmon-pasta'); + + expect( + screen.getByRole('heading', { name: 'Creamy salmon pasta' }), + ).toBeInTheDocument(); + + expect(screen.getByText('30 min')).toBeInTheDocument(); + + expect( + screen.getByRole('button', { name: 'Save to Cookbook' }), + ).toBeInTheDocument(); + + expect( + screen.getByRole('button', { name: 'Rate Recipe' }), + ).toBeInTheDocument(); + }); + + it('scales ingredient amounts when servings change', async () => { + const user = userEvent.setup(); + + renderRecipeDetail('/recipes/salmon-pasta'); + + expect(screen.getByText('400 g')).toBeInTheDocument(); + + const increaseServingButtons = screen.getAllByRole('button', { + name: 'Increase servings', + }); + + expect(increaseServingButtons.length).toBeGreaterThan(0); + + await user.click(increaseServingButtons[0]!); + + expect(screen.getByText('500 g')).toBeInTheDocument(); + + expect(screen.getAllByText('5 servings').length).toBeGreaterThan(0); + }); + + it('saves a recipe into shared cookbook state', async () => { + const user = userEvent.setup(); + + renderRecipeDetail('/recipes/salmon-pasta'); + + await user.click( + screen.getByRole('button', { + name: 'Save to Cookbook', + }), + ); + + expect(useAppStore.getState().savedRecipeIds).toContain('salmon-pasta'); + + expect(screen.getByRole('button', { name: 'Saved' })).toHaveAttribute( + 'aria-pressed', + 'true', + ); + }); + + it('stores a mock user rating and allows it to be changed later', async () => { + const user = userEvent.setup(); + + renderRecipeDetail('/recipes/salmon-pasta'); + + await user.click( + screen.getByRole('button', { + name: 'Rate Recipe', + }), + ); + + await user.click( + screen.getByRole('radio', { + name: '5 stars', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Save rating', + }), + ); + + expect(useAppStore.getState().userRatings['salmon-pasta']).toBe(5); + + expect( + screen.getByRole('button', { + name: 'Change rating, currently 5 out of 5', + }), + ).toBeInTheDocument(); + }); + + it('shows owner controls and hides ratings for a private recipe', () => { + renderRecipeDetail('/recipes/tomato-soup'); + + expect(screen.getByText('Private')).toBeInTheDocument(); + + expect( + screen.getByRole('link', { + name: 'Edit Recipe', + }), + ).toBeInTheDocument(); + + expect(screen.queryByRole('img', { name: /out of 5/ })).toBeNull(); + + expect( + screen.queryByRole('button', { + name: 'Rate Recipe', + }), + ).toBeNull(); + + expect( + screen.queryByRole('button', { + name: 'Save to Cookbook', + }), + ).toBeNull(); + }); + + it('returns to the exact source URL stored by recipe navigation', async () => { + const user = userEvent.setup(); + + renderRecipeDetail({ + pathname: '/recipes/salmon-pasta', + state: { + from: '/?q=pasta&category=dinner&page=2', + }, + }); + + await user.click( + screen.getByRole('button', { + name: 'Back to Explore', + }), + ); + + expect(screen.getByTestId('location')).toHaveTextContent( + '/?q=pasta&category=dinner&page=2', + ); + }); + + it('uses the cookbook fallback for an owner recipe opened directly', async () => { + const user = userEvent.setup(); + + renderRecipeDetail('/recipes/lentil-soup'); + + await user.click( + screen.getByRole('button', { + name: 'Back to My Cookbook', + }), + ); + + expect(screen.getByTestId('location')).toHaveTextContent('/cookbook'); + }); + + it('shows a simple not-found state for an unknown recipe id', () => { + renderRecipeDetail('/recipes/does-not-exist'); + + expect( + screen.getByRole('heading', { + name: 'Recipe not found', + }), + ).toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx new file mode 100644 index 0000000..062632d --- /dev/null +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -0,0 +1,692 @@ +import { useMemo, useState } from 'react'; + +import { useLocation, useNavigate, useParams } from 'react-router-dom'; + +import fallbackRecipeImage from '../../assets/recipe-fallback.png'; +import RecipeMeta from '../../components/recipe/RecipeMeta/RecipeMeta'; +import RecipeRating from '../../components/recipe/RecipeRating/RecipeRating'; +import RecipeRatingInput from '../../components/recipe/RecipeRatingInput/RecipeRatingInput'; +import Avatar from '../../components/ui/Avatar/Avatar'; +import Button from '../../components/ui/Button/Button'; +import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; +import Dialog from '../../components/ui/Dialog/Dialog'; +import EmptyState from '../../components/ui/EmptyState/EmptyState'; +import { Icon } from '../../components/ui/Icon/Icon'; +import IconButton from '../../components/ui/IconButton/IconButton'; +import LinkButton from '../../components/ui/LinkButton/LinkButton'; +import Tag from '../../components/ui/Tag/Tag'; +import Toast, { type ToastTone } from '../../components/ui/Toast/Toast'; +import { recipes } from '../../data/recipes'; +import { + BookmarkIcon, + EditIcon, + MinusIcon, + PlusIcon, +} from '../../icons/actions'; +import { BackIcon } from '../../icons/navigation'; +import { StarIcon } from '../../icons/rating'; +import { EmptyStateIcon, PrivateIcon } from '../../icons/recipe'; +import { useAppStore } from '../../store'; +import type { Recipe } from '../../types/recipe'; + +import './RecipeDetailPage.css'; + +const MIN_SERVINGS = 1; +const MAX_SERVINGS = 20; +const MAX_VISIBLE_TAGS = 5; + +interface RecipeDetailLocationState { + from?: string; +} + +interface RecipeDetailContentProps { + recipe: Recipe; +} + +type DetailFeedback = { + tone: ToastTone; + title: string; + message: string; +}; + +function formatTagLabel(tag: string) { + return tag + .split('-') + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' '); +} + +function formatScaledAmount( + amount: number, + selectedServings: number, + originalServings: number, +) { + const scaledAmount = amount * (selectedServings / originalServings); + + if (scaledAmount >= 200) { + return String(Math.round(scaledAmount / 5) * 5); + } + + if (scaledAmount >= 50) { + return String(Math.round(scaledAmount)); + } + + if (scaledAmount >= 3) { + return String(Math.round(scaledAmount * 10) / 10); + } + + return String(Math.round(scaledAmount * 100) / 100); +} + +function getDisplayedRating(recipe: Recipe, userRating?: number) { + if (!userRating) { + return recipe.rating; + } + + const nextCount = recipe.rating.count + 1; + const nextAverage = + (recipe.rating.average * recipe.rating.count + userRating) / nextCount; + + return { + average: Number(nextAverage.toFixed(1)), + count: nextCount, + }; +} + +function getSourcePath(locationState: unknown) { + const state = locationState as RecipeDetailLocationState | null; + + return typeof state?.from === 'string' && state.from.startsWith('/') + ? state.from + : undefined; +} + +function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { + const navigate = useNavigate(); + const location = useLocation(); + + const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); + const setRecipeSaved = useAppStore((state) => state.setRecipeSaved); + const userRatings = useAppStore((state) => state.userRatings); + const setUserRating = useAppStore((state) => state.setUserRating); + const removeUserRating = useAppStore((state) => state.removeUserRating); + + const [selectedServings, setSelectedServings] = useState(recipe.servings); + const [confirmUnsaveOpen, setConfirmUnsaveOpen] = useState(false); + const [ratingDialogOpen, setRatingDialogOpen] = useState(false); + const [pendingRating, setPendingRating] = useState(0); + const [feedback, setFeedback] = useState(null); + const [showAllTags, setShowAllTags] = useState(false); + + // TODO(server-auth): replace this mock ownership flag with the authenticated + // user's recipe ownership/authorization returned by the backend. + const isOwner = recipe.isCreatedByCurrentUser; + const isPrivate = recipe.visibility === 'private'; + const isSaved = savedRecipeIds.includes(recipe.id); + const canSaveOrRate = !isOwner && !isPrivate; + const userRating = userRatings[recipe.id]; + const displayedRating = getDisplayedRating(recipe, userRating); + const totalMinutes = recipe.prepMinutes + recipe.cookMinutes; + + const visibleTags = recipe.tags.filter( + (tag) => + formatTagLabel(tag).toLowerCase() !== recipe.category.toLowerCase(), + ); + + const hasHiddenTags = visibleTags.length > MAX_VISIBLE_TAGS; + const displayedTags = showAllTags + ? visibleTags + : visibleTags.slice(0, MAX_VISIBLE_TAGS); + const hiddenTagCount = visibleTags.length - MAX_VISIBLE_TAGS; + + const titleSizeClass = + recipe.title.length > 85 + ? 'recipe-detail-page__title--long' + : recipe.title.length > 60 + ? 'recipe-detail-page__title--medium' + : undefined; + + const hasOversizedSummary = Boolean(titleSizeClass) || hasHiddenTags; + + const sourcePath = getSourcePath(location.state); + const fallbackPath = isOwner || isPrivate ? '/cookbook' : '/'; + + const backLabel = sourcePath + ? sourcePath.startsWith('/cookbook') + ? 'Back to My Cookbook' + : 'Back to Explore' + : isOwner || isPrivate + ? 'Back to My Cookbook' + : 'Back to Explore'; + + function handleBack() { + if (sourcePath) { + navigate(sourcePath, { replace: true }); + return; + } + + if (location.key !== 'default' && window.history.length > 1) { + navigate(-1); + return; + } + + navigate(fallbackPath); + } + + function handleJumpToRecipe() { + document.getElementById('recipe-detail-recipe')?.scrollIntoView({ + behavior: 'smooth', + block: 'start', + }); + } + + function handleSaveClick() { + if (isSaved) { + setConfirmUnsaveOpen(true); + return; + } + + setRecipeSaved(recipe.id, true); + + setFeedback({ + tone: 'success', + title: 'Recipe saved', + message: `${recipe.title} was added to My Cookbook.`, + }); + } + + function handleConfirmUnsave() { + setConfirmUnsaveOpen(false); + + setRecipeSaved(recipe.id, false); + + setFeedback({ + tone: 'info', + title: 'Recipe removed', + message: `${recipe.title} was removed from My Cookbook.`, + }); + } + + function handleOpenRating() { + setPendingRating(userRating ?? 0); + setRatingDialogOpen(true); + } + + function handleSubmitRating() { + if (pendingRating < 1 || pendingRating > 5) { + return; + } + + setUserRating(recipe.id, pendingRating); + setRatingDialogOpen(false); + + setFeedback({ + tone: 'success', + title: userRating ? 'Rating updated' : 'Rating saved', + message: `You rated ${recipe.title} ${pendingRating} out of 5.`, + }); + } + + function handleRemoveRating() { + removeUserRating(recipe.id); + setRatingDialogOpen(false); + setPendingRating(0); + + setFeedback({ + tone: 'info', + title: 'Rating removed', + message: `Your rating for ${recipe.title} was removed.`, + }); + } + + return ( +
+
+ +
+ +
+
+ {recipe.imageUrl +
+ +
+
+

+ {recipe.title} +

+ + {isPrivate ? ( + + Private + + ) : null} +
+ +
+
+ + + By {recipe.author.name} +
+ + {!isPrivate ? ( + + ) : null} +
+ + + +

+ {recipe.description} +

+ + + +
    +
  • + + {recipe.category} + +
  • + + {displayedTags.map((tag) => ( +
  • + {formatTagLabel(tag)} +
  • + ))} + + {hasHiddenTags ? ( +
  • + +
  • + ) : null} +
+ +
+ {isOwner ? ( + + + ) : canSaveOrRate ? ( + <> + + + + + ) : null} +
+ +
+
+

Adjust Servings

+ +

Ingredient amounts update automatically.

+
+ +
+ + setSelectedServings((current) => + Math.max(MIN_SERVINGS, current - 1), + ) + } + /> + + + {selectedServings} + + {selectedServings === 1 ? 'serving' : 'servings'} + + + = MAX_SERVINGS} + onClick={() => + setSelectedServings((current) => + Math.min(MAX_SERVINGS, current + 1), + ) + } + /> +
+
+
+
+ +
+

About this recipe

+ +

{recipe.description}

+
+ +
+
+

Adjust Servings

+ +

Ingredient amounts update automatically.

+
+ +
+ + setSelectedServings((current) => + Math.max(MIN_SERVINGS, current - 1), + ) + } + /> + + + {selectedServings} + + {selectedServings === 1 ? 'serving' : 'servings'} + + + = MAX_SERVINGS} + onClick={() => + setSelectedServings((current) => + Math.min(MAX_SERVINGS, current + 1), + ) + } + /> +
+
+ +
+
+
+

Ingredients

+ + + {selectedServings}{' '} + {selectedServings === 1 ? 'serving' : 'servings'} + +
+ +
    + {recipe.ingredients.map((ingredient) => { + const scaledAmount = formatScaledAmount( + ingredient.amount, + selectedServings, + recipe.servings, + ); + + const amountWithUnit = + `${scaledAmount} ${ingredient.unit}`.trim(); + + return ( +
  • + {amountWithUnit} + + + {ingredient.name} + {ingredient.note ? `, ${ingredient.note}` : ''} + +
  • + ); + })} +
+
+ +
+
+

Instructions

+
+ +
    + {recipe.instructions.map((instruction) => ( +
  1. + + +

    + Step {instruction.step}: + {instruction.text} +

    +
  2. + ))} +
+
+
+ + {canSaveOrRate ? ( + <> + setConfirmUnsaveOpen(false)} + > + You can save this recipe again later. + + + setRatingDialogOpen(false)} + footer={ + <> + {userRating ? ( + + ) : null} + + + + + + } + > + + + + ) : null} + + {feedback ? ( +
+ setFeedback(null)} + > + {feedback.message} + +
+ ) : null} +
+ ); +} + +function RecipeDetailPage() { + const { id } = useParams(); + + const recipe = useMemo( + () => recipes.find((candidate) => candidate.id === id), + [id], + ); + + if (!recipe) { + return ( +
+ Back to Explore} + /> +
+ ); + } + + return ; +} + +export default RecipeDetailPage; diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css new file mode 100644 index 0000000..e5e79e6 --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.css @@ -0,0 +1,308 @@ +@layer components { + .recipe-create-page { + padding-block: var(--space-6) var(--space-8); + } + + .recipe-create-page__header { + display: flex; + flex-direction: column; + gap: var(--space-1); + max-width: 42rem; + margin-inline: auto; + text-align: center; + } + + .recipe-create-page__eyebrow { + margin: 0; + color: var(--color-text-accent); + font-size: var(--font-size-sm); + font-weight: var(--font-weight-bold); + letter-spacing: var(--letter-spacing-wide); + text-transform: uppercase; + } + + .recipe-create-page__intro { + color: var(--color-text-secondary); + } + + .recipe-create-page__header h1 { + font-size: var(--font-size-2xl); + } + + .recipe-create-page__content { + display: flex; + flex-direction: column; + gap: var(--space-4); + max-width: 64rem; + margin: var(--space-6) auto 0; + } + + .recipe-create-page__form { + width: 100%; + } + + .recipe-create-page__section { + display: grid; + grid-template-columns: minmax(10rem, 0.6fr) minmax(0, 1.4fr); + gap: var(--space-4); + padding: var(--space-4); + background: var(--color-surface); + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + } + + .recipe-create-page__section--basic { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .recipe-create-page__section h2 { + margin-bottom: var(--space-1); + font-size: var(--font-size-lg); + } + + .recipe-create-page__section-heading { + display: flex; + flex-direction: column; + gap: var(--space-2); + } + + .recipe-create-page__basic-fields, + .recipe-create-page__repeatable-list { + display: flex; + flex-direction: column; + gap: var(--space-3); + } + + .recipe-create-page__image-field { + display: flex; + flex-direction: column; + gap: var(--space-1); + min-width: 0; + } + + .recipe-create-page__image-selector { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-2); + padding: var(--space-5) var(--space-4); + color: var(--color-text-primary); + background: var(--color-surface-raised); + border: var(--border-width-thin) dashed var(--color-border-default); + border-radius: var(--radius-md); + cursor: pointer; + text-align: center; + transition: + border-color var(--duration-fast) var(--ease-standard), + background-color var(--duration-fast) var(--ease-standard); + } + + .recipe-create-page__section--basic .recipe-create-page__image-field, + .recipe-create-page__section--basic .recipe-create-page__image-selector, + .recipe-create-page__section--basic .recipe-create-page__image-preview-panel { + min-height: 100%; + } + + .recipe-create-page__image-selector { + flex: 1; + justify-content: center; + } + + .recipe-create-page__image-selector:hover { + background: var(--color-surface-hover); + border-color: var(--color-brand-primary); + } + + .recipe-create-page__image-selector--dragging { + background: var(--color-surface-selected); + border-color: var(--color-brand-primary); + } + + .recipe-create-page__image-selector:has( + .recipe-create-page__image-input:focus-visible + ) { + border-color: var(--color-focus-ring); + outline: var(--border-width-thin) solid var(--color-focus-ring); + outline-offset: 2px; + } + + .recipe-create-page__image-selector-icon { + display: grid; + place-items: center; + width: 2.5rem; + height: 2.5rem; + color: var(--color-text-accent); + background: var(--color-surface); + border-radius: var(--radius-full); + } + + .recipe-create-page__image-selector-title { + font-weight: var(--font-weight-semibold); + } + + .recipe-create-page__image-selector-help, + .recipe-create-page__image-name { + font-size: var(--font-size-sm); + } + + .recipe-create-page__image-selector-help { + color: var(--color-text-secondary); + } + + .recipe-create-page__image-selector-action { + padding: var(--space-2) var(--space-3); + color: var(--color-text-accent); + font-size: var(--font-size-sm); + font-weight: var(--font-weight-semibold); + background: var(--color-surface); + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-sm); + } + + .recipe-create-page__image-input { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + white-space: nowrap; + clip: rect(0 0 0 0); + clip-path: inset(50%); + } + + .recipe-create-page__image-field > p[role='alert'] { + color: var(--color-feedback-error); + font-size: var(--font-size-sm); + } + + .recipe-create-page__image-preview { + display: block; + width: 100%; + height: 100%; + min-height: 12rem; + max-height: 20rem; + object-fit: cover; + border-radius: var(--radius-md); + } + + .recipe-create-page__image-preview-panel { + display: flex; + flex: 1; + flex-direction: column; + gap: var(--space-2); + } + + .recipe-create-page__image-preview-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + } + + .recipe-create-page__step-textarea { + min-height: 4.5rem; + max-height: 8rem; + } + + .recipe-create-page__details-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--space-3); + grid-column: 2; + } + + .recipe-create-page__details-grid + .field, + .recipe-create-page__details-grid + .field + .radio-group { + grid-column: 2; + } + + .recipe-create-page__repeatable-row { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: end; + gap: var(--space-2); + } + + .recipe-create-page__repeatable-row--dragging { + opacity: 0.55; + } + + .recipe-create-page__drag-handle { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: var(--target-size-min); + min-height: var(--target-size-min); + color: var(--color-text-muted); + cursor: grab; + } + + .recipe-create-page__drag-handle:active { + cursor: grabbing; + } + + .recipe-create-page__repeatable-row > .field, + .recipe-create-page__repeatable-row > .textarea { + min-width: 0; + } + + .recipe-create-page__actions { + display: flex; + justify-content: flex-end; + gap: var(--space-3); + } + + .recipe-create-page__section p { + color: var(--color-text-secondary); + } + + @media (max-width: 40rem) { + .recipe-create-page { + padding-block: var(--space-6) var(--space-8); + } + + .recipe-create-page__content { + margin-top: var(--space-6); + } + + .recipe-create-page__section { + display: flex; + flex-direction: column; + padding: var(--space-3); + } + + .recipe-create-page__section--basic { + grid-template-columns: 1fr; + } + + .recipe-create-page__section--basic .recipe-create-page__image-selector, + .recipe-create-page__section--basic + .recipe-create-page__image-preview-panel { + min-height: 12rem; + } + + .recipe-create-page__details-grid, + .recipe-create-page__details-grid + .field, + .recipe-create-page__details-grid + .field + .radio-group { + grid-column: auto; + } + + .recipe-create-page__details-grid { + display: flex; + flex-direction: column; + } + + .recipe-create-page__repeatable-row { + grid-template-columns: auto minmax(0, 1fr) auto; + } + + .recipe-create-page__actions { + flex-direction: column-reverse; + } + + .recipe-create-page__actions .button { + width: 100%; + } + } +} diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx new file mode 100644 index 0000000..c741d1e --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -0,0 +1,185 @@ +import '@testing-library/jest-dom/vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; + +import RecipeCreatePage from './RecipeCreatePage'; + +describe('RecipeCreatePage', () => { + it('exposes the recipe fields through accessible labels', () => { + render(); + + expect( + screen.getByRole('heading', { name: 'Add Recipe' }), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe title/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Short description/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Cooking time/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Servings/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Category/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Tags/)).toBeInTheDocument(); + expect( + screen.getByRole('group', { name: /Visibility/ }), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe image/)).toBeInTheDocument(); + }); + + it('shows inline errors and focuses the first invalid field', async () => { + const user = userEvent.setup(); + + render(); + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + + expect(screen.getByText('Enter a recipe title.')).toBeInTheDocument(); + expect( + screen.getByText('Enter a cooking time of at least 1 minute.'), + ).toBeInTheDocument(); + expect(screen.getByText('Choose a recipe category.')).toBeInTheDocument(); + expect(screen.getByText('Add an ingredient.')).toBeInTheDocument(); + expect(screen.getByText('Add an instruction.')).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe title/)).toHaveAttribute( + 'aria-invalid', + 'true', + ); + }); + + it('adds and removes ingredient and instruction rows', async () => { + const user = userEvent.setup(); + + render(); + + await user.click(screen.getByRole('button', { name: 'Add ingredient' })); + expect(screen.getByLabelText('Ingredient 2')).toBeInTheDocument(); + + await user.click( + screen.getByRole('button', { name: 'Remove ingredient 2' }), + ); + expect(screen.queryByLabelText('Ingredient 2')).not.toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Add step' })); + expect(screen.getByLabelText('Step 2')).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Remove step 2' })); + expect(screen.queryByLabelText('Step 2')).not.toBeInTheDocument(); + }); + + it('reorders ingredients and instructions by drag and drop', async () => { + const user = userEvent.setup(); + + render(); + + await user.click(screen.getByRole('button', { name: 'Add ingredient' })); + await user.type(screen.getByLabelText('Ingredient 1'), 'Flour'); + await user.type(screen.getByLabelText('Ingredient 2'), 'Sugar'); + + const firstIngredientRow = screen + .getByLabelText('Ingredient 1') + .closest('.recipe-create-page__repeatable-row'); + const secondIngredientRow = screen + .getByLabelText('Ingredient 2') + .closest('.recipe-create-page__repeatable-row'); + + fireEvent.dragStart(firstIngredientRow!); + fireEvent.drop(secondIngredientRow!, { dataTransfer: {} }); + + expect(screen.getByLabelText('Ingredient 1')).toHaveValue('Sugar'); + expect(screen.getByLabelText('Ingredient 2')).toHaveValue('Flour'); + + await user.click(screen.getByRole('button', { name: 'Add step' })); + await user.type(screen.getByLabelText('Step 1'), 'Mix'); + await user.type(screen.getByLabelText('Step 2'), 'Bake'); + + const firstInstructionRow = screen + .getByLabelText('Step 1') + .closest('.recipe-create-page__repeatable-row'); + const secondInstructionRow = screen + .getByLabelText('Step 2') + .closest('.recipe-create-page__repeatable-row'); + + fireEvent.dragStart(firstInstructionRow!); + fireEvent.drop(secondInstructionRow!, { dataTransfer: {} }); + + expect(screen.getByLabelText('Step 1')).toHaveValue('Bake'); + expect(screen.getByLabelText('Step 2')).toHaveValue('Mix'); + }); + + it('reports an invalid image without sending it anywhere', () => { + render(); + fireEvent.change(screen.getByLabelText(/Recipe image/), { + target: { + files: [ + new File(['not an image'], 'recipe.gif', { type: 'image/gif' }), + ], + }, + }); + + expect( + screen.getByText('Choose a JPG, PNG, or WebP image.'), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe image/)).toHaveAttribute( + 'aria-invalid', + 'true', + ); + }); + + it('supports dropping, previewing, and removing an image', async () => { + vi.stubGlobal('URL', { + createObjectURL: vi.fn(() => 'blob:recipe-preview'), + revokeObjectURL: vi.fn(), + }); + + try { + const user = userEvent.setup(); + render(); + const imageFile = new File(['image data'], 'recipe.png', { + type: 'image/png', + }); + const imageSelector = screen + .getByText('Choose a recipe image') + .closest('label'); + + fireEvent.drop(imageSelector!, { + dataTransfer: { files: [imageFile] }, + }); + + expect( + screen.getByRole('img', { + name: 'Selected recipe', + }), + ).toHaveAttribute('src', 'blob:recipe-preview'); + expect(screen.getByText('recipe.png')).toBeInTheDocument(); + + await user.click( + screen.getByRole('button', { name: 'Remove recipe image' }), + ); + + expect(screen.getByText('Choose a recipe image')).toBeInTheDocument(); + expect( + screen.queryByRole('img', { + name: 'Selected recipe', + }), + ).not.toBeInTheDocument(); + } finally { + vi.unstubAllGlobals(); + } + }); + + it('shows local success feedback for a valid recipe', async () => { + const user = userEvent.setup(); + + render(); + + await user.type(screen.getByLabelText(/Recipe title/), 'Pasta'); + await user.type(screen.getByLabelText(/Cooking time/), '20'); + await user.type(screen.getByLabelText(/Servings/), '2'); + await user.selectOptions(screen.getByLabelText(/Category/), 'dinner'); + await user.type(screen.getByLabelText('Ingredient 1'), '200g pasta'); + await user.type(screen.getByLabelText('Step 1'), 'Boil the pasta.'); + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + + expect(screen.getByText('Recipe ready to publish')).toBeInTheDocument(); + expect( + screen.getByText(/No data was sent to a server/), + ).toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx new file mode 100644 index 0000000..e990910 --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -0,0 +1,709 @@ +import { + useEffect, + useRef, + useState, + type DragEvent, + type FormEvent, +} from 'react'; + +import { + DeleteIcon, + DragHandleIcon, + UploadPhotoIcon, +} from '../../icons/actions'; +import Button from '../../components/ui/Button/Button'; +import Field from '../../components/ui/Field/Field'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; +import IconButton from '../../components/ui/IconButton/IconButton'; +import { Icon } from '../../components/ui/Icon/Icon'; +import Radio from '../../components/ui/Radio/Radio'; +import RadioGroup from '../../components/ui/Radio/RadioGroup'; +import Select from '../../components/ui/Select/Select'; +import Textarea from '../../components/ui/Textarea/Textarea'; + +import './RecipeCreatePage.css'; + +type RecipeErrors = { + title?: string; + description?: string; + cookingTime?: string; + servings?: string; + category?: string; + visibility?: string; + image?: string; + ingredients?: string[]; + instructions?: string[]; +}; + +type FormStatus = 'idle' | 'draft' | 'published'; + +const MAX_IMAGE_SIZE = 5 * 1024 * 1024; +const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp']; + +function moveItem(items: T[], fromIndex: number, toIndex: number) { + const nextItems = [...items]; + const [movedItem] = nextItems.splice(fromIndex, 1); + if (movedItem === undefined) return nextItems; + nextItems.splice(toIndex, 0, movedItem); + return nextItems; +} + +function RecipeCreatePage() { + const [title, setTitle] = useState(''); + const [description, setDescription] = useState(''); + const [cookingTime, setCookingTime] = useState(''); + const [servings, setServings] = useState(''); + const [category, setCategory] = useState(''); + const [tags, setTags] = useState(''); + const [visibility, setVisibility] = useState('public'); + const [imageName, setImageName] = useState(''); + const [imagePreviewUrl, setImagePreviewUrl] = useState(''); + const [isDraggingImage, setIsDraggingImage] = useState(false); + const imageInputRef = useRef(null); + const [ingredients, setIngredients] = useState(['']); + const [instructions, setInstructions] = useState(['']); + const [draggingRow, setDraggingRow] = useState< + { type: 'ingredient' | 'instruction'; index: number } | undefined + >(); + const [errors, setErrors] = useState({}); + const [status, setStatus] = useState('idle'); + + useEffect(() => { + return () => { + if (imagePreviewUrl) URL.revokeObjectURL(imagePreviewUrl); + }; + }, [imagePreviewUrl]); + + function clearError(key: keyof RecipeErrors) { + setErrors((currentErrors) => { + const nextErrors = { ...currentErrors }; + delete nextErrors[key]; + return nextErrors; + }); + setStatus('idle'); + } + + function addIngredient() { + setIngredients((currentIngredients) => [...currentIngredients, '']); + } + + function removeIngredient(index: number) { + setIngredients((currentIngredients) => + currentIngredients.filter( + (_, ingredientIndex) => ingredientIndex !== index, + ), + ); + } + + function updateIngredient(index: number, value: string) { + setIngredients((currentIngredients) => + currentIngredients.map((ingredient, ingredientIndex) => + ingredientIndex === index ? value : ingredient, + ), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + ingredients: currentErrors.ingredients?.map((error, errorIndex) => + errorIndex === index ? '' : error, + ), + })); + setStatus('idle'); + } + + function reorderIngredients(fromIndex: number, toIndex: number) { + if (fromIndex === toIndex) return; + + setIngredients((currentIngredients) => + moveItem(currentIngredients, fromIndex, toIndex), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + ingredients: currentErrors.ingredients + ? moveItem(currentErrors.ingredients, fromIndex, toIndex) + : undefined, + })); + setStatus('idle'); + } + + function addInstruction() { + setInstructions((currentInstructions) => [...currentInstructions, '']); + } + + function removeInstruction(index: number) { + setInstructions((currentInstructions) => + currentInstructions.filter( + (_, instructionIndex) => instructionIndex !== index, + ), + ); + } + + function updateInstruction(index: number, value: string) { + setInstructions((currentInstructions) => + currentInstructions.map((instruction, instructionIndex) => + instructionIndex === index ? value : instruction, + ), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + instructions: currentErrors.instructions?.map((error, errorIndex) => + errorIndex === index ? '' : error, + ), + })); + setStatus('idle'); + } + + function reorderInstructions(fromIndex: number, toIndex: number) { + if (fromIndex === toIndex) return; + + setInstructions((currentInstructions) => + moveItem(currentInstructions, fromIndex, toIndex), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + instructions: currentErrors.instructions + ? moveItem(currentErrors.instructions, fromIndex, toIndex) + : undefined, + })); + setStatus('idle'); + } + + function handleRowDragEnd() { + setDraggingRow(undefined); + } + + function handleIngredientDrop( + event: DragEvent, + toIndex: number, + ) { + event.preventDefault(); + if (draggingRow?.type === 'ingredient') { + reorderIngredients(draggingRow.index, toIndex); + } + setDraggingRow(undefined); + } + + function handleInstructionDrop( + event: DragEvent, + toIndex: number, + ) { + event.preventDefault(); + if (draggingRow?.type === 'instruction') { + reorderInstructions(draggingRow.index, toIndex); + } + setDraggingRow(undefined); + } + + function handleImageChange(file: File | undefined) { + clearError('image'); + + if (!file) { + setImageName(''); + setImagePreviewUrl(''); + return; + } + + if (!ACCEPTED_IMAGE_TYPES.includes(file.type)) { + setErrors((currentErrors) => ({ + ...currentErrors, + image: 'Choose a JPG, PNG, or WebP image.', + })); + setImageName(''); + setImagePreviewUrl(''); + return; + } + + if (file.size > MAX_IMAGE_SIZE) { + setErrors((currentErrors) => ({ + ...currentErrors, + image: 'Choose an image smaller than 5 MB.', + })); + setImageName(''); + setImagePreviewUrl(''); + return; + } + + setImageName(file.name); + setImagePreviewUrl(URL.createObjectURL(file)); + } + + function handleImageDrop(event: DragEvent) { + event.preventDefault(); + setIsDraggingImage(false); + handleImageChange(event.dataTransfer.files[0]); + } + + function removeImage() { + clearError('image'); + setImageName(''); + setImagePreviewUrl(''); + setIsDraggingImage(false); + if (imageInputRef.current) imageInputRef.current.value = ''; + } + + function validateForm(): RecipeErrors { + const nextErrors: RecipeErrors = {}; + + if (!title.trim()) nextErrors.title = 'Enter a recipe title.'; + if (description.trim().length > 200) { + nextErrors.description = 'Keep the description under 200 characters.'; + } + if (!cookingTime || Number(cookingTime) < 1) { + nextErrors.cookingTime = 'Enter a cooking time of at least 1 minute.'; + } + if (!servings || Number(servings) < 1) { + nextErrors.servings = 'Enter at least 1 serving.'; + } + if (!category) nextErrors.category = 'Choose a recipe category.'; + if (!visibility) { + nextErrors.visibility = 'Choose who can see this recipe.'; + } + + const ingredientErrors = ingredients.map((ingredient) => + ingredient.trim() ? '' : 'Add an ingredient.', + ); + if (ingredientErrors.some(Boolean)) + nextErrors.ingredients = ingredientErrors; + + const instructionErrors = instructions.map((instruction) => + instruction.trim() ? '' : 'Add an instruction.', + ); + if (instructionErrors.some(Boolean)) { + nextErrors.instructions = instructionErrors; + } + + return nextErrors; + } + + function handleSubmit(event: FormEvent) { + event.preventDefault(); + + const nextErrors = validateForm(); + setErrors(nextErrors); + + if (Object.keys(nextErrors).length > 0) { + const firstInvalidId = [ + 'recipe-title', + 'cooking-time', + 'servings', + 'category', + 'ingredient-0', + 'instruction-0', + ].find((id) => { + if (id === 'ingredient-0') return nextErrors.ingredients?.[0]; + if (id === 'instruction-0') return nextErrors.instructions?.[0]; + return Boolean(nextErrors[id as keyof RecipeErrors]); + }); + + window.setTimeout( + () => + document.getElementById(firstInvalidId ?? 'recipe-title')?.focus(), + 0, + ); + return; + } + + setStatus('published'); + } + + return ( +
+
+

Share with the community

+

Add Recipe

+

+ Share your favorite recipe with the community. +

+
+ +
+
+ {status === 'published' && ( + + Your recipe has been prepared locally. No data was sent to a + server. + + )} + + {status === 'draft' && ( + + Your draft is available in this form until you leave the page. + + )} + +
+
+
+

Basic Information

+

Tell us about your recipe.

+
+ +
+ { + setTitle(event.target.value); + clearError('title'); + }} + required + /> + +