Files
videoreg.ru/web-front/src/fsd/features/library-search/ui.tsx
T

97 lines
3.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect, useState } from "react";
import { Button, Input, Select, ContentCard, StateMessage } from "@/fsd/shared/ui";
import { analytics } from "@/fsd/shared/config";
type Entry = {
path: string;
title: string;
summary: string;
category: string;
date: string;
text: string;
};
const normalized = (value: string) =>
value
.toLocaleLowerCase("ru")
.replaceAll("ё", "е")
.replace(/\s+/g, " ")
.trim();
export default function Search({ entries, idPrefix = "library", emitAnalytics = true }: { entries: Entry[]; idPrefix?: string; emitAnalytics?: boolean }) {
const [query, setQuery] = useState("");
const [category, setCategory] = useState("Все темы");
const categories = ["Все темы", ...new Set(entries.map((a) => a.category))];
const words = normalized(query).split(" ").filter(Boolean);
const found = entries.filter(
(a) =>
(category === "Все темы" || a.category === category) &&
words.every((word) =>
normalized(a.title + " " + a.summary + " " + a.text).includes(word),
),
);
useEffect(() => {
if (!analytics.enabled || !emitAnalytics || !query.trim() || found.length !== 0) return;
// Wait until the live filtered zero state is displayed, not an initial page state.
const timer = setTimeout(() => document.dispatchEvent(new Event("videoreg:search-zero-results")), 500);
return () => clearTimeout(timer);
}, [query, category, found.length, emitAnalytics]);
return (
<>
<div className="search-panel">
<label htmlFor={idPrefix + "-query"}>Найти в материалах</label>
<div className="query-row">
<Input
id={idPrefix + "-query"}
type="search"
placeholder="Например: GPS, USB или резервная копия"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<Button
type="button"
onClick={() => {
setQuery("");
setCategory("Все темы");
}}
>
Сбросить
</Button>
</div>
<label htmlFor={idPrefix + "-category"}>Раздел</label>
<Select
id={idPrefix + "-category"}
value={category}
onChange={(e) => setCategory(e.target.value)}
>
{categories.map((c) => (
<option key={c}>{c}</option>
))}
</Select>
</div>
<p className="result-count" role="status">
Найдено материалов: {found.length}
</p>
<div className="search-results">
{found.map((a) => (
<ContentCard key={a.path} href={a.path} title={a.title} summary={a.summary} eyebrow={a.category + " · " + a.date} />
))}
</div>
{found.length === 0 && (
<StateMessage className="empty" title="Такого сочетания пока нет">
<p>
Попробуйте название модели, «карта», «кадры» или уберите фильтр
раздела.
</p>
<Button
onClick={() => {
setQuery("");
setCategory("Все темы");
}}
>
Показать все материалы
</Button>
</StateMessage>
)}
</>
);
}