Files
web/components/HotelReservation/HotelCardListing/index.tsx
Niclas Edenvin 0f97757e31 Merged in feat/sw-620-sort-hotels (pull request #868)
Feat/sw-620 sort hotels

* SW-620 Add radio button to select box

* feat(SW-620): Implement sorting on select hotel

* Fix casing

* Shallow copy hoteldata

* Use translations

* Remove unnecessary style

* Import order

* Type


Approved-by: Pontus Dreij
2024-11-11 08:55:49 +00:00

90 lines
2.6 KiB
TypeScript

"use client"
import { useSearchParams } from "next/navigation"
import { useMemo } from "react"
import Title from "@/components/TempDesignSystem/Text/Title"
import HotelCard from "../HotelCard"
import { DEFAULT_SORT } from "../SelectHotel/HotelSorter"
import styles from "./hotelCardListing.module.css"
import {
type HotelCardListingProps,
HotelCardListingTypeEnum,
} from "@/types/components/hotelReservation/selectHotel/hotelCardListingProps"
import { SortOrder } from "@/types/components/hotelReservation/selectHotel/hotelSorter"
export default function HotelCardListing({
hotelData,
type = HotelCardListingTypeEnum.PageListing,
activeCard,
onHotelCardHover,
}: HotelCardListingProps) {
const searchParams = useSearchParams()
const sortBy = useMemo(
() => searchParams.get("sort") ?? DEFAULT_SORT,
[searchParams]
)
const sortedHotels = useMemo(() => {
switch (sortBy) {
case SortOrder.Name:
return [...hotelData].sort((a, b) =>
a.hotelData.name.localeCompare(b.hotelData.name)
)
case SortOrder.TripAdvisorRating:
return [...hotelData].sort(
(a, b) =>
(b.hotelData.ratings?.tripAdvisor.rating ?? 0) -
(a.hotelData.ratings?.tripAdvisor.rating ?? 0)
)
case SortOrder.Price:
return [...hotelData].sort(
(a, b) =>
parseInt(a.price?.memberAmount ?? "0", 10) -
parseInt(b.price?.memberAmount ?? "0", 10)
)
case SortOrder.Distance:
default:
return [...hotelData].sort(
(a, b) =>
a.hotelData.location.distanceToCentre -
b.hotelData.location.distanceToCentre
)
}
}, [hotelData, sortBy])
const hotels = useMemo(() => {
const appliedFilters = searchParams.get("filters")?.split(",")
if (!appliedFilters || appliedFilters.length === 0) return sortedHotels
return sortedHotels.filter((hotel) =>
appliedFilters.every((appliedFilterId) =>
hotel.hotelData.detailedFacilities.some(
(facility) => facility.id.toString() === appliedFilterId
)
)
)
}, [searchParams, sortedHotels])
return (
<section className={styles.hotelCards}>
{hotels?.length ? (
hotels.map((hotel) => (
<HotelCard
key={hotel.hotelData.operaId}
hotel={hotel}
type={type}
state={hotel.hotelData.name === activeCard ? "active" : "default"}
onHotelCardHover={onHotelCardHover}
/>
))
) : (
<Title>No hotels found</Title>
)}
</section>
)
}