From 0dc03f75c02be081d7f75ddebe7dd9507ba4de36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= <136926544+orjavik@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:17:31 +0100 Subject: [PATCH 1/3] fix(cookbook): restore recipe list navigation and improve search --- README.md | 4 +- .../migrations/0006_recipe_title_subwords.sql | 16 + apps/api/migrations/meta/0006_snapshot.json | 920 ++++++++++++++++++ apps/api/migrations/meta/_journal.json | 7 + .../src/features/recipes/recipeRepository.ts | 27 +- .../src/features/recipes/recipeSearch.test.ts | 10 +- .../features/cookbook/CookbookPage.test.tsx | 17 + .../src/features/cookbook/CookbookPage.tsx | 28 +- .../features/cookbook/cookbookBrowseState.ts | 4 +- .../src/features/explore/ExplorePage.test.tsx | 17 + apps/web/src/features/explore/ExplorePage.tsx | 31 +- .../recipe-detail/RecipeDetailPage.tsx | 57 +- .../recipes/RecipeCreatePage.test.tsx | 56 +- .../src/features/recipes/RecipeCreatePage.tsx | 8 +- .../recipeBrowse/useDebouncedRecipeSearch.ts | 41 + docs/frontend-integration.md | 2 +- docs/performance-and-images.md | 10 +- scripts/test-recipe-api.ts | 35 + 18 files changed, 1176 insertions(+), 114 deletions(-) create mode 100644 apps/api/migrations/0006_recipe_title_subwords.sql create mode 100644 apps/api/migrations/meta/0006_snapshot.json create mode 100644 apps/web/src/lib/recipeBrowse/useDebouncedRecipeSearch.ts diff --git a/README.md b/README.md index 0313169..345e528 100644 --- a/README.md +++ b/README.md @@ -161,7 +161,7 @@ Oppskrifter kan være offentlige eller private. Offentlige oppskrifter finnes gj ### Søk, filtrering og sortering -Søket dekker titler, beskrivelser, ingredienser og tagger. Alle søkeordene må gi treff. API-et filtrerer på kategori og tid før resultatene deles inn i sider. +Søket oppdateres etter 300 ms uten ny inntasting og dekker titler, beskrivelser, ingredienser og tagger. Alle søkeordene må gi treff. API-et filtrerer på kategori og tid før resultatene deles inn i sider. Sorteringen tilbyr nyeste først, kortest samlet tilberedningstid og høyest vurdering. Høyest vurdering bruker et uvektet gjennomsnitt. Antall vurderinger vises sammen med gjennomsnittet. @@ -390,7 +390,7 @@ KI-verktøy får ikke ekte passord, tokens, personopplysninger eller andre hemme - Utkast lagres bare i nettleseren (localStorage) per bruker og oppskrift, ikke på serveren, og følger derfor ikke brukeren til en annen enhet. De slettes ved utlogging. - Ytelse er målt lokalt med 100 000 genererte oppskrifter (`npm run db:seed:large`) i en egen testdatabase, ikke på VM-en. Se [søk og skalerbarhet](docs/performance-and-images.md#søk-og-skalerbarhet). -- Søk finner hele ord og begynnelsen av ord, ikke deler midt i et ord («cake» finner ikke «pancakes»). +- Treff inni et ord er begrenset til oppskriftstitler og søkeord på minst tre tegn. «Cake» finner «cupcakes» etter treff på ord som begynner med «cake». - Bildeoperasjoner bruker en global lås for korrekt koordinering. Dette begrenser samtidige skriveoperasjoner. - Bildekvoter har faste grenser. Registrering har IP-begrensning, men flere kontoer kan fortsatt omgå brukerkvotene. Refererte bilder teller mot totalgrensen og slettes ikke av cleanup. - VM-en bruker HTTP. Foreleser har avklart at HTTPS ikke er et krav for denne innleveringen, men det er nødvendig for å beskytte innlogging under transport. Bruk bare testpassord. diff --git a/apps/api/migrations/0006_recipe_title_subwords.sql b/apps/api/migrations/0006_recipe_title_subwords.sql new file mode 100644 index 0000000..4725121 --- /dev/null +++ b/apps/api/migrations/0006_recipe_title_subwords.sql @@ -0,0 +1,16 @@ +-- Ordinary words keep PostgreSQL's default D weight. B marks only fragments +-- from inside title words, so the same GIN index can find both match groups. +CREATE OR REPLACE FUNCTION "project2"."recipe_search_document"(recipe uuid, title text, description text) +RETURNS tsvector LANGUAGE sql STABLE AS $$ + SELECT to_tsvector('simple', concat_ws(' ', title, description, + (SELECT string_agg(i.name, ' ') FROM "project2"."recipe_ingredients" i WHERE i.recipe_id = recipe), + (SELECT string_agg(t.tag, ' ') FROM "project2"."recipe_tags" t WHERE t.recipe_id = recipe))) + || setweight(to_tsvector('simple', coalesce(( + SELECT string_agg(substr(word, start_pos), ' ') + FROM unnest(tsvector_to_array(to_tsvector('simple', title))) AS words(word) + CROSS JOIN LATERAL generate_series(2, char_length(word) - 2) AS offsets(start_pos) + ), '')), 'B') +$$; +--> statement-breakpoint +UPDATE "project2"."recipes" r +SET search_vector = "project2"."recipe_search_document"(r.id, r.title, r.description); diff --git a/apps/api/migrations/meta/0006_snapshot.json b/apps/api/migrations/meta/0006_snapshot.json new file mode 100644 index 0000000..940623f --- /dev/null +++ b/apps/api/migrations/meta/0006_snapshot.json @@ -0,0 +1,920 @@ +{ + "id": "73928da2-2f00-4213-839e-ef972ec2ba72", + "prevId": "1c6400ab-7455-4e6f-8c2e-a9e6b7053209", + "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, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "columnsFrom": ["user_id"], + "tableTo": "users", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "columnsFrom": ["recipe_id"], + "tableTo": "recipes", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "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, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "columnsFrom": ["recipe_id"], + "tableTo": "recipes", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "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, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "columnsFrom": ["recipe_id"], + "tableTo": "recipes", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "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", + "columnsFrom": ["recipe_id"], + "tableTo": "recipes", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "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()" + }, + "rating_avg": { + "name": "rating_avg", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "rating_count": { + "name": "rating_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "search_vector": { + "name": "search_vector", + "type": "tsvector", + "primaryKey": false, + "notNull": true, + "default": "''::tsvector" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "recipes_source_idx": { + "name": "recipes_source_idx", + "columns": [ + { + "expression": "source_recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "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, + "with": {}, + "method": "btree", + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false + }, + "recipes_public_category_created_idx": { + "name": "recipes_public_category_created_idx", + "columns": [ + { + "expression": "category", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "first" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "first" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false + }, + "recipes_public_total_time_idx": { + "name": "recipes_public_total_time_idx", + "columns": [ + { + "expression": "(\"prep_minutes\" + \"cook_minutes\")", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "first" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "first" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false + }, + "recipes_public_rating_idx": { + "name": "recipes_public_rating_idx", + "columns": [ + { + "expression": "rating_avg", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "first" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "first" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false + }, + "recipes_search_idx": { + "name": "recipes_search_idx", + "columns": [ + { + "expression": "search_vector", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "gin", + "concurrently": false + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "columnsFrom": ["author_id"], + "tableTo": "users", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "recipes_source_recipe_id_recipes_id_fk": { + "name": "recipes_source_recipe_id_recipes_id_fk", + "tableFrom": "recipes", + "columnsFrom": ["source_recipe_id"], + "tableTo": "recipes", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "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, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "columnsFrom": ["user_id"], + "tableTo": "users", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "columnsFrom": ["recipe_id"], + "tableTo": "recipes", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "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", + "columnsFrom": ["user_id"], + "tableTo": "users", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.uploaded_images": { + "name": "uploaded_images", + "schema": "project2", + "columns": { + "filename": { + "name": "filename", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "byte_size": { + "name": "byte_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "uploaded_images_owner_idx": { + "name": "uploaded_images_owner_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "uploaded_images_owner_id_users_id_fk": { + "name": "uploaded_images_owner_id_users_id_fk", + "tableFrom": "uploaded_images", + "columnsFrom": ["owner_id"], + "tableTo": "users", + "schemaTo": "project2", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "uploaded_images_size_valid": { + "name": "uploaded_images_size_valid", + "value": "\"project2\".\"uploaded_images\".\"byte_size\" >= 0" + } + }, + "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, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "views": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index 8266efe..8389a11 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1794837583052, "tag": "0005_recipe_search_and_ratings", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1795176845501, + "tag": "0006_recipe_title_subwords", + "breakpoints": true } ] } diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index b4d8470..601c560 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -15,9 +15,15 @@ import { DEFAULT_API_LIMITS, type ApiLimits } from '../../apiLimits.js'; * query, and repeated words are only searched once. Returns '' when there * is nothing to search for. */ -export function toSearchQuery(search: string) { +export function toSearchQuery(search: string, wordStartsOnly = false) { const words = search.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []; - return [...new Set(words)].map((word) => `${word}:*`).join(' & '); + // D matches ordinary words. Longer terms can also match indexed title fragments. + return [...new Set(words)] + .map( + (word) => + `${word}:*${wordStartsOnly || Array.from(word).length < 3 ? 'D' : ''}`, + ) + .join(' & '); } /** @@ -271,9 +277,13 @@ export function createRecipeRepository( 'r.rating_avg DESC NULLS LAST,r.created_at DESC,r.id DESC', }[input.sort]; const where = ` WHERE ${[listAccessCondition(scope), ...listFilterConditions()].join(' AND ')}`; + const searchQuery = toSearchQuery(input.search); + const rankByWordStart = searchQuery + ? "(r.search_vector @@ to_tsquery('simple',$7)) DESC, " + : ''; const args = [ userId, - toSearchQuery(input.search), + searchQuery, input.category ?? null, input.maxCookingMinutes ?? null, ]; @@ -298,8 +308,15 @@ export function createRecipeRepository( totalCount === 0 ? { rows: [] } : await client.query( - summarySelect + where + ` ORDER BY ${order} LIMIT $5 OFFSET $6`, - [...args, input.pageSize, (page - 1) * input.pageSize], + summarySelect + + where + + ` ORDER BY ${rankByWordStart}${order} LIMIT $5 OFFSET $6`, + [ + ...args, + input.pageSize, + (page - 1) * input.pageSize, + ...(searchQuery ? [toSearchQuery(input.search, true)] : []), + ], ); return { items: rows.rows, diff --git a/apps/api/src/features/recipes/recipeSearch.test.ts b/apps/api/src/features/recipes/recipeSearch.test.ts index 94c0ba3..bc63f45 100644 --- a/apps/api/src/features/recipes/recipeSearch.test.ts +++ b/apps/api/src/features/recipes/recipeSearch.test.ts @@ -8,20 +8,24 @@ describe('toSearchQuery', () => { expect(toSearchQuery(' Chick ')).toBe('chick:*'); }); + it('can restrict every term to ordinary word starts for ranking', () => { + expect(toSearchQuery('cake in', true)).toBe('cake:*D & in:*D'); + }); + it('keeps non-English letters and digits', () => { expect(toSearchQuery('Palačinke')).toBe('palačinke:*'); expect(toSearchQuery('bringebær muffins')).toBe('bringebær:* & muffins:*'); - expect(toSearchQuery('15 min')).toBe('15:* & min:*'); + expect(toSearchQuery('15 min')).toBe('15:*D & min:*'); }); it('splits hyphenated words like the database does', () => { - expect(toSearchQuery('sunny-side-up')).toBe('sunny:* & side:* & up:*'); + expect(toSearchQuery('sunny-side-up')).toBe('sunny:* & side:* & up:*D'); }); it('drops tsquery syntax so user input can never break the query', () => { expect(toSearchQuery('soup &')).toBe('soup:*'); expect(toSearchQuery("it's (soup) | !cake:*")).toBe( - 'it:* & s:* & soup:* & cake:*', + 'it:*D & s:*D & soup:* & cake:*', ); }); diff --git a/apps/web/src/features/cookbook/CookbookPage.test.tsx b/apps/web/src/features/cookbook/CookbookPage.test.tsx index 0180bb9..545b723 100644 --- a/apps/web/src/features/cookbook/CookbookPage.test.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.test.tsx @@ -94,3 +94,20 @@ it('shows session-expired failures with retry', async () => { ).toBeTruthy(); expect(screen.queryByText('Your cookbook is empty')).toBeNull(); }); + +it('searches once after typing pauses and keeps the filters', async () => { + const searches: string[] = []; + mockRecipeFetch((_operation, variables) => { + searches.push((variables.input as { search: string }).search); + return { data: { cookbook: apiPage() } }; + }); + mount('/cookbook?category=soup'); + const user = userEvent.setup(); + await user.type(screen.getByRole('searchbox'), 'cake'); + await waitFor(() => expect(searches).toEqual(['', 'cake'])); + const params = new URLSearchParams( + screen.getByTestId('location').textContent ?? '', + ); + expect(params.get('category')).toBe('soup'); + expect(params.get('q')).toBe('cake'); +}); diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx index 57dbcab..bf69049 100644 --- a/apps/web/src/features/cookbook/CookbookPage.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.tsx @@ -1,3 +1,4 @@ +import { useDebouncedRecipeSearch } from '../../lib/recipeBrowse/useDebouncedRecipeSearch'; import { usePageTitle } from '../../lib/usePageTitle'; import { useCallback, @@ -60,7 +61,7 @@ function CookbookPage() { [searchParams], ); - const [searchInput, setSearchInput] = useState(search); + const [searchInput, setSearchInput] = useDebouncedRecipeSearch(search); const queryFilters = getCookbookQueryFilters(browseState); @@ -107,10 +108,6 @@ function CookbookPage() { 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. @@ -213,8 +210,6 @@ function CookbookPage() { sort: browseState.sort, }; - setSearchInput(''); - updateUrlState({ scope, search: '', @@ -335,24 +330,7 @@ function CookbookPage() { value={searchInput} placeholder="Search recipes, ingredients or tags..." autoComplete="off" - onChange={(event) => { - 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, - }); - } - }} + onChange={(event) => setSearchInput(event.currentTarget.value)} /> +