Use Product Filters
Product filter React hook for faceted product lists: OR within a facet, AND across facets, price bands on number fields, sort options, results and a count of what each option would leave.
"use client"
import { useState, type Dispatch, type SetStateAction } from "react"
type FilterOption = { value: string; label: string; min?: number; max?: number }
type FilterFacet<Id extends string> = {
id: Id
name: string
options: readonly FilterOption[]
}
type ProductSort<Key extends string> = {
value: string
label: string
key: Key
direction: "asc" | "desc"
}
type FilterSelection<Id extends string> = Partial<Record<Id, readonly string[]>>
type FilterKey<P> = Extract<
{
[K in keyof P]-?: NonNullable<P[K]> extends
string | number | readonly string[]
? K
: never
}[keyof P],
string
>
type ProductFiltersState<P, Id extends string> = {
selection: FilterSelection<Id>
setSelection: Dispatch<SetStateAction<FilterSelection<Id>>>
sort: string
setSort: Dispatch<SetStateAction<string>>
results: P[]
selected: number
count: (facet: FilterFacet<Id>, value: string) => number
toggle: (facet: Id, value: string, checked: boolean) => void
}
// Options in a facet are OR, facets are AND; on a number field an option is
// a min..max range (a price band).
function matches<P extends object, Id extends FilterKey<P>>(
product: P,
facets: readonly FilterFacet<Id>[],
selection: FilterSelection<Id>
) {
return facets.every((facet) => {
const chosen = selection[facet.id] ?? []
if (!chosen.length) return true
const field = product[facet.id]
if (field === undefined || field === null) return false
return chosen.some((value) => {
if (typeof field === "number") {
const range = facet.options.find((option) => option.value === value)
if (range?.min === undefined && range?.max === undefined)
return String(field) === value
return (
field >= (range?.min ?? -Infinity) && field < (range?.max ?? Infinity)
)
}
return typeof field === "string"
? field === value
: Array.isArray(field) && field.includes(value)
})
})
}
function sortBy<P extends object, Key extends Extract<keyof P, string>>(
products: readonly P[],
sorts: readonly ProductSort<Key>[],
value: string
) {
const sort = sorts.find((option) => option.value === value)
if (!sort) return [...products]
const sign = sort.direction === "asc" ? 1 : -1
return [...products].sort((a, b) => {
const left = a[sort.key]
const right = b[sort.key]
const order =
typeof left === "number" && typeof right === "number"
? left - right
: String(left).localeCompare(String(right))
return order * sign
})
}
// The filter state for a product list: what is chosen, the sort, the
// results, and how many products each option would leave.
function useProductFilters<
P extends object,
Id extends FilterKey<P>,
Key extends Extract<keyof P, string>,
>({
products,
facets,
sorts,
initial = {},
}: {
products: readonly P[]
facets: readonly FilterFacet<Id>[]
sorts: readonly ProductSort<Key>[]
initial?: FilterSelection<Id>
}): ProductFiltersState<P, Id> {
const [selection, setSelection] = useState<FilterSelection<Id>>(initial)
const [sort, setSort] = useState<string>(sorts[0]?.value ?? "")
const results = sortBy(
products.filter((product) => matches(product, facets, selection)),
sorts,
sort
)
const selected = Object.values<readonly string[] | undefined>(
selection
).reduce((sum, values) => sum + (values?.length ?? 0), 0)
const count = (facet: FilterFacet<Id>, value: string) =>
products.filter((product) =>
matches(product, facets, { ...selection, [facet.id]: [value] })
).length
const toggle = (facet: Id, value: string, checked: boolean) =>
setSelection((current) => {
const values = current[facet] ?? []
return {
...current,
[facet]: checked
? [...values.filter((item) => item !== value), value]
: values.filter((item) => item !== value),
}
})
return {
selection,
setSelection,
sort,
setSort,
results,
selected,
count,
toggle,
}
}
export {
useProductFilters,
type FilterFacet,
type FilterOption,
type FilterSelection,
type ProductFiltersState,
type ProductSort,
}
"use client"
import { useId } from "react"
import { formatMoney } from "@/hooks/use-cart"
import {
useProductFilters,
type FilterFacet,
type ProductSort,
} from "@/hooks/use-product-filters"
import {
NativeSelect,
NativeSelectOption,
} from "@/components/ui/native-select"
import { Toggle } from "@/components/ui/toggle"
// The copy: change text here, not in the markup.
const COPY = {
sort: "Sort",
results: (count: number) => `${count} ${count === 1 ? "print" : "prints"}`,
none: "No prints match. Turn a filter off.",
} as const
type Print = {
id: string
name: string
paper: string
palette: string
price: number
// The swatch: the print's two main colors.
colors: readonly [string, string]
}
const PRINTS: Print[] = [
{
id: "fern",
name: "Fern",
paper: "rag",
palette: "cool",
price: 13500,
colors: ["oklch(0.62 0.08 150)", "oklch(0.2 0.02 150)"],
},
{
id: "copper-column",
name: "Copper Column",
paper: "washi",
palette: "warm",
price: 12500,
colors: ["oklch(0.62 0.15 55)", "oklch(0.18 0.01 55)"],
},
{
id: "vesper",
name: "Vesper",
paper: "rag",
palette: "cool",
price: 9500,
colors: ["oklch(0.55 0.12 300)", "oklch(0.25 0.06 280)"],
},
{
id: "ember-field",
name: "Ember Field",
paper: "rag",
palette: "warm",
price: 14500,
colors: ["oklch(0.6 0.17 35)", "oklch(0.3 0.08 30)"],
},
{
id: "tide",
name: "Tide",
paper: "washi",
palette: "cool",
price: 11000,
colors: ["oklch(0.6 0.1 220)", "oklch(0.25 0.05 240)"],
},
{
id: "warmth",
name: "Warmth",
paper: "washi",
palette: "warm",
price: 8500,
colors: ["oklch(0.75 0.13 80)", "oklch(0.55 0.15 40)"],
},
]
const FACETS: FilterFacet<"paper" | "palette">[] = [
{
id: "paper",
name: "Paper",
options: [
{ value: "rag", label: "Cotton rag" },
{ value: "washi", label: "Washi" },
],
},
{
id: "palette",
name: "Palette",
options: [
{ value: "warm", label: "Warm" },
{ value: "cool", label: "Cool" },
],
},
]
const SORTS: ProductSort<"price" | "name">[] = [
{
value: "price-asc",
label: "Price, low to high",
key: "price",
direction: "asc",
},
{
value: "price-desc",
label: "Price, high to low",
key: "price",
direction: "desc",
},
{ value: "name", label: "Name", key: "name", direction: "asc" },
]
/** A print list on useProductFilters: options in a facet widen the list,
* facets narrow it, each chip shows how many prints it would leave, and the
* sort reorders the results. */
export default function UseProductFiltersDemo() {
const sortId = useId()
const { selection, sort, setSort, results, count, toggle } =
useProductFilters({ products: PRINTS, facets: FACETS, sorts: SORTS })
return (
<div className="flex w-full max-w-md flex-col gap-5">
<div className="flex flex-col gap-3">
{FACETS.map((facet) => (
<div
key={facet.id}
role="group"
aria-label={facet.name}
className="flex flex-wrap items-center gap-2"
>
<span className="w-14 text-sm text-muted-foreground">
{facet.name}
</span>
{facet.options.map((option) => (
<Toggle
key={option.value}
variant="outline"
size="sm"
pressed={(selection[facet.id] ?? []).includes(option.value)}
onPressedChange={(pressed) =>
toggle(facet.id, option.value, pressed)
}
>
{option.label}
<span className="text-muted-foreground tabular-nums">
{count(facet, option.value)}
</span>
</Toggle>
))}
</div>
))}
</div>
<div className="flex items-center justify-between gap-4">
<p role="status" className="text-sm font-medium">
{COPY.results(results.length)}
</p>
<div className="flex items-center gap-2">
<label htmlFor={sortId} className="text-sm text-muted-foreground">
{COPY.sort}
</label>
<NativeSelect
id={sortId}
size="sm"
value={sort}
onChange={(event) => setSort(event.target.value)}
>
{SORTS.map((option) => (
<NativeSelectOption key={option.value} value={option.value}>
{option.label}
</NativeSelectOption>
))}
</NativeSelect>
</div>
</div>
{results.length === 0 ? (
<p className="text-sm text-muted-foreground">{COPY.none}</p>
) : (
<ul role="list" className="grid grid-cols-2 gap-3 sm:grid-cols-3">
{results.map((print) => (
<li key={print.id} className="flex flex-col gap-1.5">
<span
aria-hidden="true"
className="aspect-[4/5] rounded-md"
style={{
background: `linear-gradient(${print.colors[0]}, ${print.colors[1]})`,
}}
/>
<span className="text-sm font-medium">{print.name}</span>
<span className="text-xs text-muted-foreground tabular-nums">
{formatMoney(print.price)}
</span>
</li>
))}
</ul>
)}
</div>
)
}
"use client"
import { useCallback, useMemo, useState } from "react"
// A line is one product variant in the cart. Its id is the line's own, never
// the product's: two variants of one product are two lines.
type CartLine = {
id: string
productId: string
name: string
href: string
options: readonly string[]
unitPrice: number
quantity: number
maxQuantity?: number
imageUrl: string
imageAlt: string
inStock: boolean
leadTime?: string
}
// Estimates are the knob: each takes the subtotal in minor units and returns
// minor units. Nothing here knows a real tax rule or carrier.
type CartEstimate = {
shipping?: (subtotal: number, lines: readonly CartLine[]) => number
tax?: (subtotal: number, lines: readonly CartLine[]) => number
}
type CartTotals = {
count: number
subtotal: number
shipping: number
tax: number
total: number
}
const DEFAULT_MAX_QUANTITY = 8
function cartCount(lines: readonly CartLine[]) {
return lines.reduce((sum, line) => sum + line.quantity, 0)
}
function cartLineAmount(line: Pick<CartLine, "unitPrice" | "quantity">) {
return line.unitPrice * line.quantity
}
function cartTotals(
lines: readonly CartLine[],
estimate: CartEstimate = {}
): CartTotals {
const subtotal = lines.reduce((sum, line) => sum + cartLineAmount(line), 0)
const shipping = lines.length
? (estimate.shipping?.(subtotal, lines) ?? 0)
: 0
const tax = lines.length ? (estimate.tax?.(subtotal, lines) ?? 0) : 0
return {
count: cartCount(lines),
subtotal,
shipping,
tax,
total: subtotal + shipping + tax,
}
}
function cartLineLabel(line: Pick<CartLine, "name" | "options">) {
return [line.name, ...line.options].join(", ")
}
function clampQuantity(line: CartLine, quantity: number) {
const max = line.maxQuantity ?? DEFAULT_MAX_QUANTITY
if (!Number.isInteger(quantity)) return line.quantity
return Math.min(Math.max(quantity, 1), max)
}
const formatters = new Map<string, Intl.NumberFormat>()
// Amounts are integer minor units; the currency decides how many make a unit.
function formatMoney(
amount: number,
{ currency = "USD", locale = "en-US" } = {}
) {
const key = `${locale}:${currency}`
let formatter = formatters.get(key)
if (!formatter) {
formatter = new Intl.NumberFormat(locale, { style: "currency", currency })
formatters.set(key, formatter)
}
const digits = formatter.resolvedOptions().maximumFractionDigits ?? 2
return formatter.format(amount / 10 ** digits)
}
function useCart<Line extends CartLine>(
initialLines: readonly Line[],
estimate?: CartEstimate
) {
const [lines, setLines] = useState<readonly Line[]>(initialLines)
const setQuantity = useCallback((id: string, quantity: number) => {
setLines((current) =>
current.map((line) =>
line.id === id
? { ...line, quantity: clampQuantity(line, quantity) }
: line
)
)
}, [])
const remove = useCallback((id: string) => {
setLines((current) => current.filter((line) => line.id !== id))
}, [])
const clear = useCallback(() => setLines([]), [])
const reset = useCallback(() => setLines(initialLines), [initialLines])
const totals = useMemo(() => cartTotals(lines, estimate), [lines, estimate])
return {
lines,
totals,
count: totals.count,
isEmpty: lines.length === 0,
setQuantity,
remove,
clear,
reset,
}
}
export {
useCart,
cartTotals,
cartCount,
cartLineAmount,
cartLineLabel,
formatMoney,
DEFAULT_MAX_QUANTITY,
type CartLine,
type CartEstimate,
type CartTotals,
}
Installation
pnpm dlx shadcn@latest add @01orbital/use-product-filtersnpx shadcn@latest add @01orbital/use-product-filtersyarn dlx shadcn@latest add @01orbital/use-product-filtersbunx --bun shadcn@latest add @01orbital/use-product-filtersUsed in blocks
2 blocks are built with Use Product Filters:
Last updated on