Improve website settings and special-item pick UX.
Tighten sitemap/settings controls, debounce product search to 10 results, keep catalog-only specials visible after add, and use frosted glass on link/category modals. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
parent
a39aef0c8c
commit
77080a7a4b
@@ -45,12 +45,12 @@
|
||||
.modal {
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
backdrop-filter: blur(24px);
|
||||
-webkit-backdrop-filter: blur(24px);
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(var(--blur-glass, 28px)) saturate(1.45);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass, 28px)) saturate(1.45);
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 20px 60px rgba(31, 38, 135, 0.15);
|
||||
box-shadow: var(--glass-shadow), 0 20px 60px rgba(31, 38, 135, 0.12);
|
||||
}
|
||||
|
||||
.header {
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(var(--blur-glass, 28px)) saturate(1.45);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass, 28px)) saturate(1.45);
|
||||
border: 1px solid var(--glass-border);
|
||||
box-shadow: var(--glass-shadow), 0 20px 60px rgba(31, 38, 135, 0.12);
|
||||
}
|
||||
|
||||
.header {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { X } from 'lucide-react'
|
||||
import { useLocale } from '@meshkee/dashboard-ui'
|
||||
import { useT } from '../i18n/useT'
|
||||
import { ApiError } from '../lib/api'
|
||||
import { listAllProducts } from '../services/productService'
|
||||
import { listAllStoreItems } from '../services/storeItemService'
|
||||
import { listProducts } from '../services/productService'
|
||||
import { listStoreItems } from '../services/storeItemService'
|
||||
import type { SpecialProductsSource } from '../services/settingsService'
|
||||
import { groupStoreItemsByProduct } from '../utils/storeProductGroups'
|
||||
import {
|
||||
SEARCH_RESULT_LIMIT,
|
||||
StoreItemMultiSearchSelect,
|
||||
type StoreItemSearchOption,
|
||||
} from './StoreItemMultiSearchSelect'
|
||||
@@ -22,11 +23,12 @@ interface PickStoreSpecialItemsModalProps {
|
||||
existingIds: string[]
|
||||
source: SpecialProductsSource
|
||||
onClose: () => void
|
||||
onConfirm: (ids: string[]) => void
|
||||
onConfirm: (ids: string[]) => void | Promise<void>
|
||||
isSubmitting?: boolean
|
||||
}
|
||||
|
||||
const ANIMATION_MS = 220
|
||||
const STORE_ITEM_SEARCH_PAGE_SIZE = 30
|
||||
|
||||
export function PickStoreSpecialItemsModal({
|
||||
open,
|
||||
@@ -44,10 +46,10 @@ export function PickStoreSpecialItemsModal({
|
||||
const [mounted, setMounted] = useState(open)
|
||||
const [closing, setClosing] = useState(false)
|
||||
const [options, setOptions] = useState<StoreItemSearchOption[]>([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([])
|
||||
const [selectOpen, setSelectOpen] = useState(false)
|
||||
const searchControllerRef = useRef<AbortController | null>(null)
|
||||
|
||||
const existingSet = useMemo(() => new Set(existingIds), [existingIds])
|
||||
|
||||
@@ -56,7 +58,9 @@ export function PickStoreSpecialItemsModal({
|
||||
setMounted(true)
|
||||
setClosing(false)
|
||||
setSelectedIds([])
|
||||
setOptions([])
|
||||
setError('')
|
||||
setIsSearching(false)
|
||||
} else if (mounted) {
|
||||
setClosing(true)
|
||||
const timer = setTimeout(() => {
|
||||
@@ -68,12 +72,10 @@ export function PickStoreSpecialItemsModal({
|
||||
}, [open, mounted])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
const controller = new AbortController()
|
||||
void loadOptions(controller.signal)
|
||||
return () => controller.abort()
|
||||
}, [open, existingIds, source])
|
||||
return () => {
|
||||
searchControllerRef.current?.abort()
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted || closing) return
|
||||
@@ -84,69 +86,47 @@ export function PickStoreSpecialItemsModal({
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [mounted, closing, onClose])
|
||||
|
||||
async function loadOptions(signal?: AbortSignal) {
|
||||
setIsLoading(true)
|
||||
setError('')
|
||||
const handleSearch = useCallback(
|
||||
async (query: string) => {
|
||||
searchControllerRef.current?.abort()
|
||||
|
||||
try {
|
||||
const nextOptions = fromProducts
|
||||
? await loadProductOptions(signal)
|
||||
: await loadStoreItemOptions(signal)
|
||||
|
||||
setOptions(nextOptions.filter((option) => !existingSet.has(option.id)))
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === 'AbortError') return
|
||||
if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError(
|
||||
fromProducts
|
||||
? t('website.specialItems.pickErrorLoadProducts')
|
||||
: t('website.specialItems.pickErrorLoad'),
|
||||
)
|
||||
if (!query) {
|
||||
setOptions([])
|
||||
setIsSearching(false)
|
||||
setError('')
|
||||
return
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStoreItemOptions(signal?: AbortSignal) {
|
||||
const items = await listAllStoreItems(signal)
|
||||
const listings = groupStoreItemsByProduct(items)
|
||||
return listings
|
||||
.map((listing): StoreItemSearchOption | null => {
|
||||
const storeItemId = listing.representative.storeItemId ?? listing.representative.id
|
||||
const firstPricedVariant = listing.variants.find((v) => v.price !== null) ?? null
|
||||
const price = firstPricedVariant?.price ?? null
|
||||
const hasPrice = listing.variants.some((v) => v.price !== null)
|
||||
const hasInStock = listing.variants.some(
|
||||
(v) => v.stockQuantity === null || v.stockQuantity > 0,
|
||||
)
|
||||
const controller = new AbortController()
|
||||
searchControllerRef.current = controller
|
||||
setIsSearching(true)
|
||||
setError('')
|
||||
|
||||
if (!hasPrice && !hasInStock) return null
|
||||
try {
|
||||
const nextOptions = fromProducts
|
||||
? await loadProductOptions(query, controller.signal)
|
||||
: await loadStoreItemOptions(query, controller.signal)
|
||||
|
||||
return {
|
||||
id: storeItemId,
|
||||
title: listing.productTitle,
|
||||
nameFa: listing.productNameFa,
|
||||
image: listing.productImage,
|
||||
price,
|
||||
if (controller.signal.aborted) return
|
||||
setOptions(nextOptions.filter((option) => !existingSet.has(option.id)))
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === 'AbortError') return
|
||||
if (controller.signal.aborted) return
|
||||
if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError(
|
||||
fromProducts
|
||||
? t('website.specialItems.pickErrorLoadProducts')
|
||||
: t('website.specialItems.pickErrorLoad'),
|
||||
)
|
||||
}
|
||||
})
|
||||
.filter((option): option is StoreItemSearchOption => option !== null)
|
||||
}
|
||||
|
||||
async function loadProductOptions(signal?: AbortSignal) {
|
||||
const products = await listAllProducts(signal)
|
||||
return products.map(
|
||||
(product): StoreItemSearchOption => ({
|
||||
id: product.id,
|
||||
title: product.title,
|
||||
nameFa: product.nameFa,
|
||||
image: product.thumbnailUrl || product.thumbnail || product.image || null,
|
||||
}),
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setIsSearching(false)
|
||||
}
|
||||
},
|
||||
[existingSet, fromProducts, t],
|
||||
)
|
||||
|
||||
function toggleSelection(id: string) {
|
||||
setSelectedIds((prev) =>
|
||||
@@ -154,9 +134,22 @@ export function PickStoreSpecialItemsModal({
|
||||
)
|
||||
}
|
||||
|
||||
function handleConfirm() {
|
||||
if (selectedIds.length === 0) return
|
||||
onConfirm(selectedIds)
|
||||
async function handleConfirm() {
|
||||
if (selectedIds.length === 0 || isSubmitting) return
|
||||
setError('')
|
||||
try {
|
||||
await onConfirm(selectedIds)
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else if (err instanceof Error && err.message) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError(
|
||||
t('website.specialItems.errorAdd'),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function confirmLabel() {
|
||||
@@ -172,7 +165,7 @@ export function PickStoreSpecialItemsModal({
|
||||
className={`${modalStyles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
|
||||
onClick={(e) => {
|
||||
if (e.target !== e.currentTarget) return
|
||||
if (selectOpen) return
|
||||
if (selectedIds.length > 0) return
|
||||
onClose()
|
||||
}}
|
||||
role="presentation"
|
||||
@@ -184,6 +177,8 @@ export function PickStoreSpecialItemsModal({
|
||||
aria-labelledby="pick-special-items-title"
|
||||
lang={isFa ? 'fa' : 'en'}
|
||||
dir={isFa ? 'rtl' : 'ltr'}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className={modalStyles.header}>
|
||||
<div>
|
||||
@@ -209,32 +204,19 @@ export function PickStoreSpecialItemsModal({
|
||||
<div className={modalStyles.body}>
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
{isLoading ? (
|
||||
<p className={styles.empty}>
|
||||
{fromProducts
|
||||
? t('website.specialItems.pickLoadingProducts')
|
||||
: t('website.specialItems.pickLoading')}
|
||||
</p>
|
||||
) : options.length === 0 ? (
|
||||
<p className={styles.empty}>
|
||||
{fromProducts
|
||||
? t('website.specialItems.pickEmptyProducts')
|
||||
: t('website.specialItems.pickEmpty')}
|
||||
</p>
|
||||
) : (
|
||||
<StoreItemMultiSearchSelect
|
||||
options={options}
|
||||
selectedIds={selectedIds}
|
||||
onToggle={toggleSelection}
|
||||
placeholder={
|
||||
fromProducts
|
||||
? t('website.specialItems.pickSearchProducts')
|
||||
: t('website.specialItems.pickSearch')
|
||||
}
|
||||
disabled={isSubmitting}
|
||||
onOpenChange={setSelectOpen}
|
||||
/>
|
||||
)}
|
||||
<StoreItemMultiSearchSelect
|
||||
options={options}
|
||||
selectedIds={selectedIds}
|
||||
onToggle={toggleSelection}
|
||||
onQueryChange={(query) => void handleSearch(query)}
|
||||
isSearching={isSearching}
|
||||
placeholder={
|
||||
fromProducts
|
||||
? t('website.specialItems.pickSearchProducts')
|
||||
: t('website.specialItems.pickSearch')
|
||||
}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
|
||||
<div className={styles.footer}>
|
||||
<button type="button" className={styles.cancelBtn} onClick={onClose} disabled={isSubmitting}>
|
||||
@@ -243,7 +225,7 @@ export function PickStoreSpecialItemsModal({
|
||||
<button
|
||||
type="button"
|
||||
className={styles.confirmBtn}
|
||||
onClick={handleConfirm}
|
||||
onClick={() => void handleConfirm()}
|
||||
disabled={isSubmitting || selectedIds.length === 0}
|
||||
>
|
||||
{confirmLabel()}
|
||||
@@ -255,3 +237,42 @@ export function PickStoreSpecialItemsModal({
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
async function loadProductOptions(name: string, signal?: AbortSignal) {
|
||||
const data = await listProducts(1, SEARCH_RESULT_LIMIT, signal, { name })
|
||||
return data.items.map(
|
||||
(product): StoreItemSearchOption => ({
|
||||
id: product.id,
|
||||
title: product.nameEn,
|
||||
nameFa: product.nameFa,
|
||||
image: product.thumbnail || product.image || null,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async function loadStoreItemOptions(name: string, signal?: AbortSignal) {
|
||||
const data = await listStoreItems(1, STORE_ITEM_SEARCH_PAGE_SIZE, signal, { name })
|
||||
const listings = groupStoreItemsByProduct(data.items)
|
||||
return listings
|
||||
.map((listing): StoreItemSearchOption | null => {
|
||||
const storeItemId = listing.representative.storeItemId ?? listing.representative.id
|
||||
const firstPricedVariant = listing.variants.find((v) => v.price !== null) ?? null
|
||||
const price = firstPricedVariant?.price ?? null
|
||||
const hasPrice = listing.variants.some((v) => v.price !== null)
|
||||
const hasInStock = listing.variants.some(
|
||||
(v) => v.stockQuantity === null || v.stockQuantity > 0,
|
||||
)
|
||||
|
||||
if (!hasPrice && !hasInStock) return null
|
||||
|
||||
return {
|
||||
id: storeItemId,
|
||||
title: listing.productTitle,
|
||||
nameFa: listing.productNameFa,
|
||||
image: listing.productImage,
|
||||
price,
|
||||
}
|
||||
})
|
||||
.filter((option): option is StoreItemSearchOption => option !== null)
|
||||
.slice(0, SEARCH_RESULT_LIMIT)
|
||||
}
|
||||
|
||||
@@ -136,6 +136,8 @@ export function PickWebsiteBrandsModal({
|
||||
aria-labelledby="pick-brands-title"
|
||||
lang={isFa ? 'fa' : 'en'}
|
||||
dir={isFa ? 'rtl' : 'ltr'}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className={modalStyles.header}>
|
||||
<div>
|
||||
|
||||
@@ -137,6 +137,8 @@ export function PickWebsiteCategoriesModal({
|
||||
aria-labelledby="pick-categories-title"
|
||||
lang={isFa ? 'fa' : 'en'}
|
||||
dir={isFa ? 'rtl' : 'ltr'}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className={modalStyles.header}>
|
||||
<div>
|
||||
|
||||
@@ -90,7 +90,14 @@ export function StoreItemCard({
|
||||
|
||||
return (
|
||||
<article className={styles.card}>
|
||||
<button type="button" className={styles.clickable} onClick={() => onOpen(listing)}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.clickable}
|
||||
onClick={() => {
|
||||
if (listing.variantCount > 0) onOpen(listing)
|
||||
}}
|
||||
disabled={listing.variantCount === 0}
|
||||
>
|
||||
<div className={styles.imageWrap}>
|
||||
{showImage ? (
|
||||
<img
|
||||
@@ -132,9 +139,11 @@ export function StoreItemCard({
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
<p className={styles.variantLabel}>
|
||||
{formatVariantCount(listing.variantCount, locale)}
|
||||
</p>
|
||||
{listing.variantCount > 0 ? (
|
||||
<p className={styles.variantLabel}>
|
||||
{formatVariantCount(listing.variantCount, locale)}
|
||||
</p>
|
||||
) : null}
|
||||
<StoreItemPrice
|
||||
price={listing.displayPrice}
|
||||
discountedPrice={listing.displayDiscountedPrice}
|
||||
@@ -144,34 +153,38 @@ export function StoreItemCard({
|
||||
|
||||
<div className={styles.controls} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.controlsLeft}>
|
||||
<Tooltip label={t('storeItems.card.edit')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onEdit(listing)}
|
||||
aria-label={t('storeItems.card.edit')}
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('storeItems.card.discount')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDiscount(listing)}
|
||||
aria-label={t('storeItems.card.discount')}
|
||||
>
|
||||
<Percent size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('storeItems.card.festivalPoints')}>
|
||||
<button
|
||||
type="button"
|
||||
className={listing.showFestival ? styles.festivalActive : undefined}
|
||||
onClick={() => onFestival(listing)}
|
||||
aria-label={t('storeItems.card.festivalPoints')}
|
||||
>
|
||||
<Sparkles size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{listing.variantCount > 0 ? (
|
||||
<>
|
||||
<Tooltip label={t('storeItems.card.edit')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onEdit(listing)}
|
||||
aria-label={t('storeItems.card.edit')}
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('storeItems.card.discount')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDiscount(listing)}
|
||||
aria-label={t('storeItems.card.discount')}
|
||||
>
|
||||
<Percent size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('storeItems.card.festivalPoints')}>
|
||||
<button
|
||||
type="button"
|
||||
className={listing.showFestival ? styles.festivalActive : undefined}
|
||||
onClick={() => onFestival(listing)}
|
||||
aria-label={t('storeItems.card.festivalPoints')}
|
||||
>
|
||||
<Sparkles size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</>
|
||||
) : null}
|
||||
<Tooltip label={removeLabel}>
|
||||
<button
|
||||
type="button"
|
||||
@@ -184,16 +197,18 @@ export function StoreItemCard({
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<Tooltip label={t('storeItems.card.addToCart')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.addToCartBtn}
|
||||
onClick={() => onAddToCart(listing)}
|
||||
aria-label={t('storeItems.card.addToCart')}
|
||||
>
|
||||
<GradientPlusIcon gradientId={plusGradientId} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{listing.variantCount > 0 ? (
|
||||
<Tooltip label={t('storeItems.card.addToCart')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.addToCartBtn}
|
||||
onClick={() => onAddToCart(listing)}
|
||||
aria-label={t('storeItems.card.addToCart')}
|
||||
>
|
||||
<GradientPlusIcon gradientId={plusGradientId} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
|
||||
@@ -6,6 +6,9 @@ import { formatIrtPrice } from '../utils/irtPrice'
|
||||
import selectStyles from './SearchableSelect.module.css'
|
||||
import styles from './StoreItemMultiSearchSelect.module.css'
|
||||
|
||||
export const SEARCH_RESULT_LIMIT = 10
|
||||
export const SEARCH_DEBOUNCE_MS = 1000
|
||||
|
||||
export interface StoreItemSearchOption {
|
||||
id: string
|
||||
title: string
|
||||
@@ -25,6 +28,14 @@ interface StoreItemMultiSearchSelectProps {
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
minSearchLength?: number
|
||||
maxResults?: number
|
||||
isSearching?: boolean
|
||||
/**
|
||||
* When set, typing is debounced and the parent fetches results.
|
||||
* Local filtering is skipped.
|
||||
*/
|
||||
onQueryChange?: (query: string) => void
|
||||
debounceMs?: number
|
||||
/**
|
||||
* Optional hook for parents that need to know when the dropdown is open
|
||||
* (e.g. to prevent modal outside-click closing).
|
||||
@@ -39,6 +50,10 @@ export function StoreItemMultiSearchSelect({
|
||||
placeholder,
|
||||
disabled = false,
|
||||
minSearchLength = 3,
|
||||
maxResults = SEARCH_RESULT_LIMIT,
|
||||
isSearching = false,
|
||||
onQueryChange,
|
||||
debounceMs = SEARCH_DEBOUNCE_MS,
|
||||
onOpenChange,
|
||||
}: StoreItemMultiSearchSelectProps) {
|
||||
const t = useT()
|
||||
@@ -46,47 +61,74 @@ export function StoreItemMultiSearchSelect({
|
||||
const isFa = locale === 'fa'
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [selectedById, setSelectedById] = useState<Record<string, StoreItemSearchOption>>({})
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const onQueryChangeRef = useRef(onQueryChange)
|
||||
onQueryChangeRef.current = onQueryChange
|
||||
|
||||
const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds])
|
||||
const searchPlaceholder = placeholder ?? t('storeItems.search.minChars', { count: minSearchLength })
|
||||
const trimmedQuery = query.trim()
|
||||
const canSearch = trimmedQuery.length >= minSearchLength
|
||||
|
||||
useEffect(() => {
|
||||
onOpenChange?.(open)
|
||||
}, [open, onOpenChange])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const trimmed = query.trim()
|
||||
if (trimmed.length < minSearchLength) return []
|
||||
const q = trimmed.toLowerCase()
|
||||
return options.filter(
|
||||
(option) =>
|
||||
option.title.toLowerCase().includes(q) || option.nameFa.includes(trimmed),
|
||||
)
|
||||
}, [options, query, minSearchLength])
|
||||
|
||||
const selectedOptions = useMemo(
|
||||
() => options.filter((option) => selectedSet.has(option.id)),
|
||||
[options, selectedSet],
|
||||
)
|
||||
useEffect(() => {
|
||||
setSelectedById((prev) => {
|
||||
const next = { ...prev }
|
||||
for (const id of Object.keys(next)) {
|
||||
if (!selectedSet.has(id)) delete next[id]
|
||||
}
|
||||
for (const option of options) {
|
||||
if (selectedSet.has(option.id)) next[option.id] = option
|
||||
}
|
||||
return next
|
||||
})
|
||||
}, [options, selectedSet])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onClickOutside = (e: MouseEvent) => {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
setOpen(false)
|
||||
setQuery('')
|
||||
}
|
||||
const cb = onQueryChangeRef.current
|
||||
if (!cb) return
|
||||
if (!canSearch) {
|
||||
cb('')
|
||||
return
|
||||
}
|
||||
document.addEventListener('mousedown', onClickOutside)
|
||||
return () => document.removeEventListener('mousedown', onClickOutside)
|
||||
}, [open])
|
||||
const timer = window.setTimeout(() => cb(trimmedQuery), debounceMs)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [canSearch, trimmedQuery, debounceMs])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (!canSearch) return []
|
||||
if (onQueryChange) return options.slice(0, maxResults)
|
||||
const q = trimmedQuery.toLowerCase()
|
||||
return options
|
||||
.filter(
|
||||
(option) =>
|
||||
option.title.toLowerCase().includes(q) || option.nameFa.includes(trimmedQuery),
|
||||
)
|
||||
.slice(0, maxResults)
|
||||
}, [canSearch, onQueryChange, options, trimmedQuery, maxResults])
|
||||
|
||||
const selectedOptions = useMemo(
|
||||
() =>
|
||||
selectedIds
|
||||
.map((id) => selectedById[id])
|
||||
.filter((option): option is StoreItemSearchOption => Boolean(option)),
|
||||
[selectedIds, selectedById],
|
||||
)
|
||||
|
||||
function handleFocus() {
|
||||
if (!disabled) setOpen(true)
|
||||
}
|
||||
|
||||
function handleClearSearch() {
|
||||
setQuery('')
|
||||
setOpen(false)
|
||||
onQueryChangeRef.current?.('')
|
||||
}
|
||||
|
||||
function renderOptionMeta(option: StoreItemSearchOption) {
|
||||
const primary = isFa ? option.nameFa || option.title : option.title
|
||||
const secondary = isFa
|
||||
@@ -121,11 +163,11 @@ export function StoreItemMultiSearchSelect({
|
||||
)
|
||||
}
|
||||
|
||||
const showDropdown = open && query.trim().length >= minSearchLength
|
||||
const showDropdown = open && (canSearch || trimmedQuery.length > 0)
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper} dir={isFa ? 'rtl' : 'ltr'}>
|
||||
<div className={selectStyles.wrapper} ref={containerRef}>
|
||||
<div className={selectStyles.wrapper}>
|
||||
<div className={`${selectStyles.inputWrap} ${open ? selectStyles.inputWrapOpen : ''}`}>
|
||||
<Search size={16} className={selectStyles.searchIcon} />
|
||||
<input
|
||||
@@ -142,15 +184,31 @@ export function StoreItemMultiSearchSelect({
|
||||
disabled={disabled}
|
||||
dir={isFa ? 'rtl' : 'ltr'}
|
||||
/>
|
||||
{query ? (
|
||||
<button
|
||||
type="button"
|
||||
className={selectStyles.clearBtn}
|
||||
onClick={handleClearSearch}
|
||||
aria-label={t('storeItems.search.clearQuery')}
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{showDropdown && (
|
||||
<ul className={`${selectStyles.dropdown} ${selectStyles.dropdownInFlow}`} role="listbox">
|
||||
{filtered.length === 0 ? (
|
||||
{!canSearch ? (
|
||||
<li className={selectStyles.noResults}>
|
||||
{options.length === 0
|
||||
? t('storeItems.search.noProducts')
|
||||
: t('storeItems.search.noMatch')}
|
||||
{t('storeItems.search.minChars', { count: minSearchLength })}
|
||||
</li>
|
||||
) : isSearching ? (
|
||||
<li className={selectStyles.noResults}>{t('website.specialItems.pickSearching')}</li>
|
||||
) : filtered.length === 0 ? (
|
||||
<li className={selectStyles.noResults}>
|
||||
{onQueryChange || options.length > 0
|
||||
? t('storeItems.search.noMatch')
|
||||
: t('storeItems.search.noProducts')}
|
||||
</li>
|
||||
) : (
|
||||
filtered.map((option) => {
|
||||
@@ -182,14 +240,6 @@ export function StoreItemMultiSearchSelect({
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{open && query.trim().length > 0 && query.trim().length < minSearchLength && (
|
||||
<ul className={`${selectStyles.dropdown} ${selectStyles.dropdownInFlow}`}>
|
||||
<li className={selectStyles.noResults}>
|
||||
{t('storeItems.search.minChars', { count: minSearchLength })}
|
||||
</li>
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selectedOptions.length > 0 && (
|
||||
|
||||
Reference in New Issue
Block a user