diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 45dbefe..daae458 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -30,7 +30,7 @@ import { useFontSize } from "./hooks/useFontSize"; import { loadSearchPreferences, saveSearchPreferences, -} from "./pages/SearchResults/searchPreferences"; +} from "./pages/SearchResults/searchPreferencesStorage"; import { createCategoryUrl } from "./pages/home/categoryNavigation"; // Styling diff --git a/frontend/src/pages/SearchResults/SearchResultsPage.tsx b/frontend/src/pages/SearchResults/SearchResultsPage.tsx index ca427e0..792fe8f 100644 --- a/frontend/src/pages/SearchResults/SearchResultsPage.tsx +++ b/frontend/src/pages/SearchResults/SearchResultsPage.tsx @@ -1,14 +1,13 @@ +import { useState } from "react"; + import { - useEffect, - useLayoutEffect, - useRef, - useState, -} from "react"; + useSearchResults, + PAGE_SIZE, +} from "./hooks/useSearchResults"; -import { gql } from "@apollo/client"; -import type { TypedDocumentNode } from "@apollo/client"; +import { useSearchState } from "./hooks/useSearchState"; -import { useQuery } from "@apollo/client/react"; +import { usePreserveScroll } from "./hooks/usePreserveScroll"; import FilterChip from "../../components/filterChip/FilterChip"; import SearchFilters from "./SearchFilters"; @@ -16,235 +15,47 @@ import SearchPagination from "./SearchPagination"; import SearchProductList from "./SearchProductList"; import SearchSortSelect from "./SearchSortSelect"; -import { - SEARCH_PRODUCTS_QUERY, - SEARCH_FILTER_COUNTS_QUERY, -} from "./searchQueries"; - -import { - loadSearchPreferences, - saveSearchPreferences, -} from "./searchPreferences"; - -import type { SearchProduct, Category } from "../../types/product"; -import type { SearchSort, FilterCount } from "../../types/filters"; +import type { SearchSort } from "../../types/filters"; import "./SearchResultsPage.css"; import SearchEmptyState from "./SearchEmptyState"; import { useStoreNames } from "../../hooks/useStoreNames"; -import { useSearchParams } from "react-router"; - -const PAGE_SIZE = 20; - -// Typer for spørringen som henter alle kategorinavn -type CategoryNamesData = { - categories: Category[]; -}; - -// Henter alle kategorinavn én gang, slik at filterbrikkene alltid kan vise -// navn (også etter refresh og når søket gir null treff) -const CATEGORY_NAMES_QUERY: TypedDocumentNode = gql` - query CategoryNames { - categories { - id - name - } - } -`; - const collator = new Intl.Collator("nb-NO", { sensitivity: "base", }); -function normalizeCounts( - items: - | ReadonlyArray<{ - value?: string; - label?: string; - count?: number; - } | null> - | null - | undefined, -): FilterCount[] { - return (items ?? []).flatMap((item) => { - if ( - item && - typeof item.value === "string" && - typeof item.label === "string" && - typeof item.count === "number" - ) { - return [{ - value: item.value, - label: item.label, - count: item.count, - }]; - } - - return []; - }); -} - -function normalizeProducts( - items: ReadonlyArray<{ - ean?: string; - name?: string; - brand?: string | null; - imageUrl?: string | null; - categoryId?: string | null; - prices?: ReadonlyArray<{ - storeCode?: string; - storeName?: string; - price?: number; - unitPrice?: number | null; - } | null>; - } | null> | null | undefined, -): SearchProduct[] { - return (items ?? []).flatMap((product) => { - if ( - !product || - typeof product.ean !== "string" || - typeof product.name !== "string" - ) { - return []; - } - - const prices = (product.prices ?? []).flatMap( - (price) => { - if ( - !price || - typeof price.storeCode !== "string" || - typeof price.price !== "number" - ) { - return []; - } - - return [{ - storeCode: price.storeCode, - storeName: - typeof price.storeName === "string" - ? price.storeName - : price.storeCode, - price: price.price, - unitPrice: - typeof price.unitPrice === "number" - ? price.unitPrice - : null, - }]; - }, - ); - - return [{ - ean: product.ean, - name: product.name, - brand: product.brand ?? null, - imageUrl: product.imageUrl ?? null, - categoryId: product.categoryId ?? null, - prices, - }]; - }); -} - export default function SearchResultsPage() { - const [searchParams] = useSearchParams(); - // Butikknavn fra databasen, f.eks. "MENY_NO" → "Meny" - const { getStoreName } = useStoreNames(); - const urlSearchTerm = searchParams.get("q"); - - // Hent lagrede innstillinger kun ved første rendering. - const [initialPreferences] = useState( - loadSearchPreferences, - ); - - const searchTerm = urlSearchTerm ?? ""; - - const [currentPage, setCurrentPage] = useState(() => - initialPreferences.searchTerm === searchTerm - ? initialPreferences.currentPage - : 1, - ); - - const [sort, setSort] = useState( - initialPreferences.sort, - ); - - const [selectedCategories, setSelectedCategories] = - useState(() => { - const urlCategories = searchParams.getAll("category"); - - if (urlCategories.length > 0) { - return urlCategories; - } - - if (urlSearchTerm === null) { - return []; - } - - return initialPreferences.selectedCategories; - }); - - const [selectedStores, setSelectedStores] = - useState(() => - urlSearchTerm === null - ? [] - : initialPreferences.selectedStores, - ); + // Søkeord, filtre, sortering og paginering håndteres i egen hook. +const { + searchTerm, + currentPage, + setCurrentPage, + sort, + setSort, + selectedCategories, + setSelectedCategories, + selectedStores, + setSelectedStores, +} = useSearchState(); + +// Butikknavn hentes fra databasen. +const { getStoreName } = useStoreNames(); const [knownCategoryNames, setKnownCategoryNames] = useState>({}); const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false); - // Brukes til å bevare scrollposisjonen når filtre endres. - const scrollPositionRef = useRef(null); - const resultsRef = useRef(null); - const productsSectionRef = useRef(null); - - const [loadingMinHeight, setLoadingMinHeight] = - useState(null); - - const preservePosition = () => { - scrollPositionRef.current = window.scrollY; - - if (resultsRef.current) { - setLoadingMinHeight( - resultsRef.current.getBoundingClientRect().height, - ); - } - }; - - // Gjenopprett scrollposisjon etter at React har - // oppdatert innholdet. - useLayoutEffect(() => { - if (scrollPositionRef.current !== null) { - const previousPosition = scrollPositionRef.current; - - window.scrollTo({ - top: previousPosition, - behavior: "instant", - }); - - scrollPositionRef.current = null; - } - }); - - // Lagre søkeinnstillingene automatisk. - useEffect(() => { - saveSearchPreferences({ - searchTerm, - selectedCategories, - selectedStores, - sort, - currentPage, - }); - }, [ - searchTerm, - selectedCategories, - selectedStores, - sort, - currentPage, - ]); + // Scrollhåndtering for filtre, sortering og paginering. + const { + resultsRef, + productsSectionRef, + loadingMinHeight, + preservePosition, + scrollToProducts, + } = usePreserveScroll(); const handleCategoriesChange = ( values: string[], @@ -272,11 +83,7 @@ export default function SearchResultsPage() { if (page === currentPage) return; setCurrentPage(page); - - productsSectionRef.current?.scrollIntoView({ - behavior: "smooth", - block: "start", - }); + scrollToProducts(); }; const resetFilters = () => { @@ -291,64 +98,29 @@ export default function SearchResultsPage() { const hasCategorySelection = selectedCategories.length > 0; - // Katalogen skal også kunne vise alle produkter. - const shouldFetchProducts = true; - - // Hent produkter. + // GraphQL-spørringer, filtertall og paginering. const { - data, + products, + totalProducts, + totalPages, + firstProduct, + lastProduct, + categoryCounts, + storeCounts, + allCategoryNames, + hasFilterData, loading, error, - } = useQuery(SEARCH_PRODUCTS_QUERY, { - variables: { - search: searchTerm.trim(), - categories: selectedCategories, - storeCodes: selectedStores, - sort, - limit: PAGE_SIZE, - offset: (currentPage - 1) * PAGE_SIZE, - }, - skip: !shouldFetchProducts, - }); - - // Hent dynamiske filtertall. - const { - data: filterData, - previousData: previousFilterData, - loading: filtersLoading, - error: filtersError, - } = useQuery(SEARCH_FILTER_COUNTS_QUERY, { - variables: { - search: searchTerm.trim(), - categories: selectedCategories, - storeCodes: selectedStores, - }, - skip: !shouldFetchProducts, + filtersLoading, + filtersError, + } = useSearchResults({ + searchTerm, + selectedCategories, + selectedStores, + sort, + currentPage, }); - // Mens nye filtertall lastes, viser vi de forrige. Da beholder filterlisten - // samme høyde, og siden hopper ikke til toppen når du velger et filter. - const filterSource = filterData ?? previousFilterData; - - const categoryCounts = normalizeCounts( - filterSource?.categoryFilterCounts, - ); - - const storeCounts = normalizeCounts( - filterSource?.storeFilterCounts, - ); - - // Henter alle kategorinavn én gang (brukes når navnet ikke finnes i filtertallene) - const { data: categoryNameData } = useQuery(CATEGORY_NAMES_QUERY); - - // Gjør listen om til et oppslag: kategori-id -> navn - const allCategoryNames: Record = Object.fromEntries( - (categoryNameData?.categories ?? []).map((category) => [ - category.id, - category.name, - ]), - ); - // Prøver først filtertallene, så navn vi har sett tidligere, så alle kategorinavn. // «Kategori X» vises bare hvis navnet ikke finnes noe sted. const getCategoryName = (value: string) => @@ -377,21 +149,6 @@ export default function SearchResultsPage() { handleCategoriesChange(values); }; - const products = normalizeProducts(data?.products); - - const totalProducts = data?.productsCount ?? 0; - const totalPages = Math.ceil( - totalProducts / PAGE_SIZE, - ); - - const firstProduct = - (currentPage - 1) * PAGE_SIZE + 1; - - const lastProduct = Math.min( - currentPage * PAGE_SIZE, - totalProducts, - ); - const hasActiveFilters = selectedCategories.length > 0 || selectedStores.length > 0; @@ -445,7 +202,7 @@ export default function SearchResultsPage() {

- {shouldFetchProducts && !loading && !error + {!loading && !error ? `${totalProducts} produkter funnet` : "Søkeresultater"}

@@ -487,7 +244,7 @@ export default function SearchResultsPage() {

)} - {filtersLoading && !filterSource && ( + {filtersLoading && !hasFilterData && (

Henter filtre...

)} diff --git a/frontend/src/pages/SearchResults/hooks/usePreserveScroll.ts b/frontend/src/pages/SearchResults/hooks/usePreserveScroll.ts new file mode 100644 index 0000000..302b938 --- /dev/null +++ b/frontend/src/pages/SearchResults/hooks/usePreserveScroll.ts @@ -0,0 +1,55 @@ + +import { useLayoutEffect, useRef, useState } from "react"; + +// Bevarer scrollposisjonen når filtre eller sortering endres. +// Holder også resultatlisten i samme høyde mens nye data lastes. +export function usePreserveScroll() { + const scrollPositionRef = useRef(null); + const resultsRef = useRef(null); + const productsSectionRef = useRef(null); + + const [loadingMinHeight, setLoadingMinHeight] = + useState(null); + + // Husk scrollposisjonen og høyden på resultatlisten. + const preservePosition = () => { + scrollPositionRef.current = window.scrollY; + + if (resultsRef.current) { + setLoadingMinHeight( + resultsRef.current.getBoundingClientRect().height, + ); + } + }; + + // Gjenopprett scrollposisjonen etter at React har + // oppdatert innholdet. + useLayoutEffect(() => { + if (scrollPositionRef.current !== null) { + const previousPosition = scrollPositionRef.current; + + window.scrollTo({ + top: previousPosition, + behavior: "instant", + }); + + scrollPositionRef.current = null; + } + }); + + // Ved paginering skal produktseksjonen vises fra toppen. + const scrollToProducts = () => { + productsSectionRef.current?.scrollIntoView({ + behavior: "smooth", + block: "start", + }); + }; + + return { + resultsRef, + productsSectionRef, + loadingMinHeight, + preservePosition, + scrollToProducts, + }; +} diff --git a/frontend/src/pages/SearchResults/hooks/useSearchResults.ts b/frontend/src/pages/SearchResults/hooks/useSearchResults.ts new file mode 100644 index 0000000..70ee469 --- /dev/null +++ b/frontend/src/pages/SearchResults/hooks/useSearchResults.ts @@ -0,0 +1,212 @@ +import { useQuery } from "@apollo/client/react"; + +import type { SearchProduct } from "../../../types/product"; +import type { FilterCount, SearchSort } from "../../../types/filters"; + +import { + SEARCH_PRODUCTS_QUERY, + SEARCH_FILTER_COUNTS_QUERY, + CATEGORY_NAMES_QUERY, +} from "../searchQueries"; + +// ========================================== +// Typer og konstanter +// ========================================== + +export const PAGE_SIZE = 20; + +type UseSearchResultsParams = { + searchTerm: string; + selectedCategories: string[]; + selectedStores: string[]; + sort: SearchSort; + currentPage: number; +}; + +// ========================================== +// Normalisering av filtertall +// ========================================== + +function normalizeCounts( + items: + | ReadonlyArray<{ + value?: string; + label?: string; + count?: number; + } | null> + | null + | undefined, +): FilterCount[] { + return (items ?? []).flatMap((item) => { + if ( + item && + typeof item.value === "string" && + typeof item.label === "string" && + typeof item.count === "number" + ) { + return [{ + value: item.value, + label: item.label, + count: item.count, + }]; + } + + return []; + }); +} + +// ========================================== +// Normalisering av produkter +// ========================================== + +function normalizeProducts( + items: ReadonlyArray<{ + ean?: string; + name?: string; + brand?: string | null; + imageUrl?: string | null; + categoryId?: string | null; + prices?: ReadonlyArray<{ + storeCode?: string; + storeName?: string; + price?: number; + unitPrice?: number | null; + } | null>; + } | null> | null | undefined, +): SearchProduct[] { + return (items ?? []).flatMap((product) => { + if ( + !product || + typeof product.ean !== "string" || + typeof product.name !== "string" + ) { + return []; + } + + const prices = (product.prices ?? []).flatMap((price) => { + if ( + !price || + typeof price.storeCode !== "string" || + typeof price.price !== "number" + ) { + return []; + } + + return [{ + storeCode: price.storeCode, + storeName: + typeof price.storeName === "string" + ? price.storeName + : price.storeCode, + price: price.price, + unitPrice: + typeof price.unitPrice === "number" + ? price.unitPrice + : null, + }]; + }); + + return [{ + ean: product.ean, + name: product.name, + brand: product.brand ?? null, + imageUrl: product.imageUrl ?? null, + categoryId: product.categoryId ?? null, + prices, + }]; + }); +} + +// ========================================== +// Hook: GraphQL og søkeresultater +// ========================================== + +export function useSearchResults({ + searchTerm, + selectedCategories, + selectedStores, + sort, + currentPage, +}: UseSearchResultsParams) { + // Hent produkter og antall treff. + // Katalogen skal også fungere uten søkeord eller filtre. + const { + data, + loading, + error, + } = useQuery(SEARCH_PRODUCTS_QUERY, { + variables: { + search: searchTerm.trim(), + categories: selectedCategories, + storeCodes: selectedStores, + sort, + limit: PAGE_SIZE, + offset: (currentPage - 1) * PAGE_SIZE, + }, + }); + + // Hent filtertall for kategorier og butikker. + const { + data: filterData, + previousData: previousFilterData, + loading: filtersLoading, + error: filtersError, + } = useQuery(SEARCH_FILTER_COUNTS_QUERY, { + variables: { + search: searchTerm.trim(), + categories: selectedCategories, + storeCodes: selectedStores, + }, + }); + + // Behold forrige filtertall mens nye resultater lastes. + const filterSource = filterData ?? previousFilterData; + + const categoryCounts = normalizeCounts( + filterSource?.categoryFilterCounts, + ); + + const storeCounts = normalizeCounts( + filterSource?.storeFilterCounts, + ); + + // Hent alle kategorinavn for filterbrikker. + const { data: categoryNameData } = useQuery(CATEGORY_NAMES_QUERY); + + const allCategoryNames: Record = Object.fromEntries( + (categoryNameData?.categories ?? []).map((category) => [ + category.id, + category.name, + ]), + ); + + // Normaliser produkter og beregn paginering. + const products = normalizeProducts(data?.products); + + const totalProducts = data?.productsCount ?? 0; + const totalPages = Math.ceil(totalProducts / PAGE_SIZE); + + const firstProduct = (currentPage - 1) * PAGE_SIZE + 1; + const lastProduct = Math.min( + currentPage * PAGE_SIZE, + totalProducts, + ); + + const hasFilterData = filterSource != null; + + return { + products, + totalProducts, + totalPages, + firstProduct, + lastProduct, + categoryCounts, + storeCounts, + allCategoryNames, + hasFilterData, + loading, + error, + filtersLoading, + filtersError, + }; +} diff --git a/frontend/src/pages/SearchResults/hooks/useSearchState.ts b/frontend/src/pages/SearchResults/hooks/useSearchState.ts new file mode 100644 index 0000000..ae8eb77 --- /dev/null +++ b/frontend/src/pages/SearchResults/hooks/useSearchState.ts @@ -0,0 +1,123 @@ +import { useEffect, useState } from "react"; +import { useSearchParams } from "react-router"; + +import { useLocalStorage } from "../../../hooks/useLocalStorage"; +import { STORAGE_KEYS } from "../../../constants/storageKeys"; + +import { + defaultSearchPreferences, + parseSearchPreferences, +} from "../searchPreferencesStorage"; + +import type { SearchPreferences } from "../searchPreferencesStorage"; +import type { SearchSort } from "../../../types/filters"; + +// ========================================== +// Initialisering fra URL og localStorage +// ========================================== + +function getInitialSearchState( + searchTerm: string, + urlSearchTerm: string | null, + urlCategories: string[], + preferences: SearchPreferences, +): SearchPreferences { + if (urlCategories.length > 0) { + return { + ...defaultSearchPreferences, + selectedCategories: urlCategories, + }; + } + + if (urlSearchTerm === null) { + return { ...defaultSearchPreferences }; + } + + if (preferences.searchTerm !== searchTerm) { + return { + ...defaultSearchPreferences, + searchTerm, + }; + } + + return preferences; +} + +// ========================================== +// Hook: søketilstand +// ========================================== + +export function useSearchState() { + const [searchParams] = useSearchParams(); + + const urlSearchTerm = searchParams.get("q"); + const searchTerm = urlSearchTerm ?? ""; + const urlCategories = searchParams.getAll("category"); + + const [preferences, setPreferences] = + useLocalStorage( + STORAGE_KEYS.searchPreferences, + parseSearchPreferences, + ); + + const [state, setState] = useState(() => + getInitialSearchState( + searchTerm, + urlSearchTerm, + urlCategories, + preferences, + ), + ); + + // ========================================== + // Automatisk lagring + // ========================================== + + useEffect(() => { + const next: SearchPreferences = { + ...state, + searchTerm, + }; + + setPreferences((previous) => { + if (JSON.stringify(previous) === JSON.stringify(next)) { + return previous; + } + + return next; + }); + }, [state, searchTerm, setPreferences]); + + // ========================================== + // Oppdatering av filtre og paginering + // ========================================== + + const updateState = ( + changes: Partial, + ) => { + setState((previous) => ({ + ...previous, + ...changes, + })); + }; + + return { + searchTerm, + + currentPage: state.currentPage, + setCurrentPage: (page: number) => + updateState({ currentPage: page }), + + sort: state.sort, + setSort: (value: SearchSort) => + updateState({ sort: value }), + + selectedCategories: state.selectedCategories, + setSelectedCategories: (values: string[]) => + updateState({ selectedCategories: values }), + + selectedStores: state.selectedStores, + setSelectedStores: (values: string[]) => + updateState({ selectedStores: values }), + }; +} diff --git a/frontend/src/pages/SearchResults/searchPreferences.ts b/frontend/src/pages/SearchResults/searchPreferences.ts deleted file mode 100644 index b260c43..0000000 --- a/frontend/src/pages/SearchResults/searchPreferences.ts +++ /dev/null @@ -1,91 +0,0 @@ - -import type { SearchSort } from "../../types/filters"; -import { STORAGE_KEYS } from "../../constants/storageKeys"; - -export type SearchPreferences = { - searchTerm: string; - selectedCategories: string[]; - selectedStores: string[]; - sort: SearchSort; - currentPage: number; -}; - -const STORAGE_KEY = STORAGE_KEYS.searchPreferences; - -const defaultPreferences: SearchPreferences = { - searchTerm: "ost", - selectedCategories: [], - selectedStores: [], - sort: "relevance", - currentPage: 1, -}; - -export function loadSearchPreferences(): SearchPreferences { - try { - const stored = localStorage.getItem(STORAGE_KEY); - - if (!stored) { - return defaultPreferences; - } - - const parsed: unknown = JSON.parse(stored); - - if (!parsed || typeof parsed !== "object") { - return defaultPreferences; - } - - const data = parsed as Partial; - - return { - searchTerm: - typeof data.searchTerm === "string" - ? data.searchTerm - : defaultPreferences.searchTerm, - - selectedCategories: - Array.isArray(data.selectedCategories) - ? data.selectedCategories.filter( - (value): value is string => - typeof value === "string", - ) - : [], - - selectedStores: - Array.isArray(data.selectedStores) - ? data.selectedStores.filter( - (value): value is string => - typeof value === "string", - ) - : [], - - sort: - data.sort === "price_asc" || - data.sort === "price_desc" || - data.sort === "relevance" - ? data.sort - : "relevance", - - currentPage: - typeof data.currentPage === "number" && - Number.isInteger(data.currentPage) && - data.currentPage > 0 - ? data.currentPage - : 1, - }; - } catch { - return defaultPreferences; - } -} - -export function saveSearchPreferences( - preferences: SearchPreferences, -): void { - try { - localStorage.setItem( - STORAGE_KEY, - JSON.stringify(preferences), - ); - } catch { - // Lagring kan være deaktivert i nettleseren. - } -} diff --git a/frontend/src/pages/SearchResults/searchPreferencesStorage.ts b/frontend/src/pages/SearchResults/searchPreferencesStorage.ts new file mode 100644 index 0000000..ef03f50 --- /dev/null +++ b/frontend/src/pages/SearchResults/searchPreferencesStorage.ts @@ -0,0 +1,105 @@ + +import type { SearchSort } from "../../types/filters"; +import { STORAGE_KEYS } from "../../constants/storageKeys"; + +// ========================================== +// Typer og standardverdier +// ========================================== + +export type SearchPreferences = { + searchTerm: string; + selectedCategories: string[]; + selectedStores: string[]; + sort: SearchSort; + currentPage: number; +}; + +export const defaultSearchPreferences: SearchPreferences = { + searchTerm: "", + selectedCategories: [], + selectedStores: [], + sort: "relevance", + currentPage: 1, +}; + +const STORAGE_KEY = STORAGE_KEYS.searchPreferences; + +// ========================================== +// Validering av lagrede innstillinger +// ========================================== + +export function parseSearchPreferences( + saved: unknown, +): SearchPreferences { + if (!saved || typeof saved !== "object") { + return { ...defaultSearchPreferences }; + } + + const data = saved as Partial; + + return { + searchTerm: + typeof data.searchTerm === "string" + ? data.searchTerm + : "", + + selectedCategories: + Array.isArray(data.selectedCategories) + ? data.selectedCategories.filter( + (value): value is string => + typeof value === "string", + ) + : [], + + selectedStores: + Array.isArray(data.selectedStores) + ? data.selectedStores.filter( + (value): value is string => + typeof value === "string", + ) + : [], + + sort: + data.sort === "price_asc" || + data.sort === "price_desc" || + data.sort === "relevance" + ? data.sort + : "relevance", + + currentPage: + typeof data.currentPage === "number" && + Number.isInteger(data.currentPage) && + data.currentPage > 0 + ? data.currentPage + : 1, + }; +} + +// ========================================== +// Lagring utenfor React +// ========================================== + +export function loadSearchPreferences(): SearchPreferences { + try { + const stored = localStorage.getItem(STORAGE_KEY); + + return parseSearchPreferences( + stored === null ? undefined : JSON.parse(stored), + ); + } catch { + return parseSearchPreferences(undefined); + } +} + +export function saveSearchPreferences( + preferences: SearchPreferences, +): void { + try { + localStorage.setItem( + STORAGE_KEY, + JSON.stringify(preferences), + ); + } catch { + // Siden fungerer selv om localStorage ikke er tilgjengelig. + } +} diff --git a/frontend/src/pages/SearchResults/searchQueries.ts b/frontend/src/pages/SearchResults/searchQueries.ts index 14c53ea..ea24f26 100644 --- a/frontend/src/pages/SearchResults/searchQueries.ts +++ b/frontend/src/pages/SearchResults/searchQueries.ts @@ -2,7 +2,7 @@ import { gql } from "@apollo/client"; import type { TypedDocumentNode } from "@apollo/client"; -import type { SearchProduct } from "../../types/product"; +import type { SearchProduct, Category } from "../../types/product"; import type { FilterCount, SearchSort } from "../../types/filters"; export type SearchProductsData = { @@ -99,3 +99,18 @@ export const SEARCH_FILTER_COUNTS_QUERY: TypedDocumentNode< } } `; + +// Henter alle kategorinavn, også når et søk ikke gir treff. +// Brukes for å vise riktige navn på valgte filterbrikker. +export type CategoryNamesData = { + categories: Category[]; +}; + +export const CATEGORY_NAMES_QUERY: TypedDocumentNode = gql` + query CategoryNames { + categories { + id + name + } + } +`; \ No newline at end of file