COPY docuservix
This commit is contained in:
@@ -89,6 +89,16 @@ const config: Config = {
|
||||
],
|
||||
],
|
||||
|
||||
themes: ['@docusaurus/theme-mermaid'],
|
||||
|
||||
plugins: [
|
||||
[
|
||||
path.resolve(__dirname, './plugins/docuservix-search/index.ts'),
|
||||
{
|
||||
providersModule: require.resolve('./src/search-providers'),
|
||||
},
|
||||
],
|
||||
],
|
||||
themeConfig: {
|
||||
// Replace with your project's social card
|
||||
image: 'img/docusaurus-social-card.jpg',
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import path from 'path';
|
||||
import type { LoadContext, Plugin } from '@docusaurus/types';
|
||||
|
||||
interface SearchPluginOptions {
|
||||
providersModule: string;
|
||||
}
|
||||
|
||||
export default function docuservixSearchPlugin(
|
||||
_ctx: LoadContext,
|
||||
options: SearchPluginOptions,
|
||||
): Plugin {
|
||||
return {
|
||||
name: 'docuservix-search',
|
||||
|
||||
getThemePath() {
|
||||
return path.resolve(__dirname, './theme');
|
||||
},
|
||||
|
||||
getTypeScriptThemePath() {
|
||||
return path.resolve(__dirname, './theme');
|
||||
},
|
||||
|
||||
configureWebpack() {
|
||||
return {
|
||||
resolve: {
|
||||
alias: {
|
||||
'@docuservix-search/config': options.providersModule,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async contentLoaded({ actions }) {
|
||||
actions.addRoute({
|
||||
path: '/search',
|
||||
component: '@theme/SearchPage',
|
||||
exact: true,
|
||||
});
|
||||
actions.addRoute({
|
||||
path: '/chat',
|
||||
component: '@theme/ChatPage',
|
||||
exact: true,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { useLocation } from '@docusaurus/router';
|
||||
import Link from '@docusaurus/Link';
|
||||
import Layout from '@theme/Layout';
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { chatUrl } from '@docuservix-search/config';
|
||||
|
||||
import styles from './styles.module.css';
|
||||
|
||||
interface Source {
|
||||
file: string;
|
||||
heading: string;
|
||||
anchor: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
sources?: Source[];
|
||||
}
|
||||
|
||||
function stripNumericPrefixes(p: string): string {
|
||||
return p
|
||||
.split('/')
|
||||
.map((seg) => seg.replace(/^\d+-/, ''))
|
||||
.join('/');
|
||||
}
|
||||
|
||||
function sourceToUrl(file: string, anchor: string): string {
|
||||
let p = file.replace(/^docs\//, '').replace(/\.md$/, '');
|
||||
|
||||
p = stripNumericPrefixes(p);
|
||||
|
||||
return `/docs/${p}${anchor ? `#${anchor}` : ''}`;
|
||||
}
|
||||
|
||||
function sourceToPath(file: string): string {
|
||||
const p = file.replace(/^docs\//, '').replace(/\.md$/, '');
|
||||
|
||||
return stripNumericPrefixes(p);
|
||||
}
|
||||
|
||||
function useQuery(): string {
|
||||
const location = useLocation();
|
||||
const params = new URLSearchParams(location.search);
|
||||
|
||||
return params.get('q') ?? '';
|
||||
}
|
||||
|
||||
export default function ChatPage(): JSX.Element {
|
||||
const urlQuery = useQuery();
|
||||
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const initialSentRef = useRef(false);
|
||||
|
||||
const sendMessage = useCallback(async (content: string, history: Message[]) => {
|
||||
if (!content.trim()) return;
|
||||
|
||||
const userMessage: Message = { role: 'user', content };
|
||||
const newHistory = [...history, userMessage];
|
||||
|
||||
setMessages(newHistory);
|
||||
setInput('');
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch(chatUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ messages: newHistory }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const data: { answer: string; sources?: Source[] } = await res.json();
|
||||
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: 'assistant', content: data.answer, sources: data.sources },
|
||||
]);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка при обращении к серверу');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (urlQuery && !initialSentRef.current) {
|
||||
initialSentRef.current = true;
|
||||
sendMessage(urlQuery, []);
|
||||
}
|
||||
}, [urlQuery, sendMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, [messages, loading]);
|
||||
|
||||
const handleSend = () => {
|
||||
if (!loading && input.trim()) {
|
||||
sendMessage(input, messages);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout title="Чат">
|
||||
<div className={styles.page}>
|
||||
{urlQuery && (
|
||||
<div className={styles.header}>
|
||||
<Link
|
||||
to={`/search?q=${encodeURIComponent(urlQuery)}`}
|
||||
className={styles.backLink}
|
||||
>
|
||||
← Назад к поиску
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.messages}>
|
||||
{messages.length === 0 && !loading && (
|
||||
<div className={styles.empty}>Задайте вопрос...</div>
|
||||
)}
|
||||
|
||||
{messages.map((msg, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`${styles.messageRow} ${msg.role === 'user' ? styles.messageRowUser : styles.messageRowAssistant}`}
|
||||
>
|
||||
<div
|
||||
className={`${styles.bubble} ${msg.role === 'user' ? styles.userBubble : styles.assistantBubble}`}
|
||||
>
|
||||
<div className={styles.bubbleContent}>{msg.content}</div>
|
||||
|
||||
{msg.sources && msg.sources.length > 0 && (
|
||||
<div className={styles.sources}>
|
||||
<div className={styles.sourcesLabel}>Источники:</div>
|
||||
{msg.sources.map((src, j) => (
|
||||
<Link
|
||||
key={j}
|
||||
to={sourceToUrl(src.file, src.anchor)}
|
||||
className={styles.sourceLink}
|
||||
>
|
||||
{src.heading || sourceToPath(src.file)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{loading && (
|
||||
<div className={`${styles.messageRow} ${styles.messageRowAssistant}`}>
|
||||
<div
|
||||
className={`${styles.bubble} ${styles.assistantBubble} ${styles.loadingBubble}`}
|
||||
>
|
||||
<span className={styles.loadingDot} />
|
||||
<span className={styles.loadingDot} />
|
||||
<span className={styles.loadingDot} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className={styles.errorRow}>
|
||||
<div className={styles.errorText}>{error}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
<div className={styles.inputRow}>
|
||||
<textarea
|
||||
className={styles.input}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Введите сообщение... (Enter — отправить, Shift+Enter — перенос)"
|
||||
rows={2}
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
className={styles.sendBtn}
|
||||
onClick={handleSend}
|
||||
disabled={loading || !input.trim()}
|
||||
>
|
||||
Отправить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
.page {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 0 1rem 2rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: 0.75rem 0;
|
||||
border-bottom: 1px solid var(--ifm-color-emphasis-200);
|
||||
}
|
||||
|
||||
.backLink {
|
||||
color: var(--ifm-color-primary);
|
||||
font-size: 0.875rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.backLink:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.messages {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 2rem 0;
|
||||
color: var(--ifm-color-emphasis-500);
|
||||
font-size: 0.95rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.messageRow {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.messageRowUser {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.messageRowAssistant {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.bubble {
|
||||
max-width: 75%;
|
||||
padding: 10px 14px;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
border-radius: var(--ifm-global-radius);
|
||||
}
|
||||
|
||||
.userBubble {
|
||||
color: var(--ifm-color-primary-contrast-foreground);
|
||||
background: var(--ifm-color-primary);
|
||||
}
|
||||
|
||||
.assistantBubble {
|
||||
color: var(--ifm-font-color-base);
|
||||
background: var(--ifm-background-surface-color);
|
||||
border: 1px solid var(--ifm-color-emphasis-200);
|
||||
}
|
||||
|
||||
.bubbleContent {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.sources {
|
||||
margin-top: 8px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--ifm-color-emphasis-200);
|
||||
}
|
||||
|
||||
.sourcesLabel {
|
||||
margin-bottom: 4px;
|
||||
color: var(--ifm-color-emphasis-600);
|
||||
font-weight: var(--ifm-font-weight-semibold);
|
||||
font-size: 0.75rem;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.sourceLink {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
color: var(--ifm-color-primary);
|
||||
font-size: 0.8rem;
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.sourceLink:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.loadingBubble {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.loadingDot {
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
background: var(--ifm-color-emphasis-400);
|
||||
border-radius: 50%;
|
||||
animation: bounce 1.2s infinite;
|
||||
}
|
||||
|
||||
.loadingDot:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
.loadingDot:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%,
|
||||
60%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
30% {
|
||||
transform: translateY(-5px);
|
||||
}
|
||||
}
|
||||
|
||||
.errorRow {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.errorText {
|
||||
padding: 8px 14px;
|
||||
color: var(--ifm-color-danger);
|
||||
font-size: 0.85rem;
|
||||
background: var(--ifm-color-danger-contrast-background);
|
||||
border: 1px solid var(--ifm-color-danger);
|
||||
border-radius: var(--ifm-global-radius);
|
||||
}
|
||||
|
||||
.inputRow {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: flex-end;
|
||||
padding: 0.75rem 0;
|
||||
border-top: 1px solid var(--ifm-color-emphasis-200);
|
||||
}
|
||||
|
||||
.input {
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
color: var(--ifm-font-color-base);
|
||||
font-size: var(--ifm-font-size-base);
|
||||
font-family: inherit;
|
||||
background: var(--ifm-background-surface-color);
|
||||
border: 1px solid var(--ifm-color-emphasis-300);
|
||||
border-radius: var(--ifm-global-radius);
|
||||
outline: none;
|
||||
transition: border-color 0.2s ease;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
.input:focus {
|
||||
border-color: var(--ifm-color-primary);
|
||||
}
|
||||
|
||||
.input:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.sendBtn {
|
||||
padding: 8px 18px;
|
||||
color: var(--ifm-color-primary-contrast-foreground);
|
||||
font-weight: var(--ifm-font-weight-semibold);
|
||||
font-size: 0.875rem;
|
||||
white-space: nowrap;
|
||||
background: var(--ifm-color-primary);
|
||||
border: none;
|
||||
border-radius: var(--ifm-global-radius);
|
||||
cursor: pointer;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
|
||||
.sendBtn:hover:not(:disabled) {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.sendBtn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useHistory } from '@docusaurus/router';
|
||||
import searchConfig from '@docuservix-search/config';
|
||||
import type { SearchResult } from '../../types';
|
||||
import styles from './styles.module.css';
|
||||
|
||||
const MAX_DROPDOWN_RESULTS = 10;
|
||||
const DEBOUNCE_MS = 300;
|
||||
|
||||
export default function SearchBar(): JSX.Element {
|
||||
const [query, setQuery] = useState('');
|
||||
const [results, setResults] = useState<SearchResult[]>([]);
|
||||
const [notices, setNotices] = useState<string[]>([]);
|
||||
const [hasErrors, setHasErrors] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedIndex, setSelectedIndex] = useState(-1);
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
const history = useHistory();
|
||||
|
||||
const runSearch = useCallback(async (q: string) => {
|
||||
if (q.trim().length < 2) {
|
||||
setResults([]);
|
||||
setNotices([]);
|
||||
setHasErrors(false);
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (abortRef.current) {
|
||||
abortRef.current.abort();
|
||||
}
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
|
||||
const timeout = searchConfig.timeout ?? 5000;
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
setLoading(true);
|
||||
setHasErrors(false);
|
||||
|
||||
try {
|
||||
const settled = await Promise.allSettled(
|
||||
searchConfig.providers.map((provider) => {
|
||||
const signal = controller.signal;
|
||||
return provider.search(q, signal);
|
||||
}),
|
||||
);
|
||||
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
const allResults: SearchResult[] = [];
|
||||
const allNotices: string[] = [];
|
||||
let anyError = false;
|
||||
|
||||
for (const outcome of settled) {
|
||||
if (outcome.status === 'fulfilled') {
|
||||
allResults.push(...outcome.value.results);
|
||||
if (outcome.value.notice) {
|
||||
allNotices.push(outcome.value.notice);
|
||||
}
|
||||
} else {
|
||||
anyError = true;
|
||||
}
|
||||
}
|
||||
|
||||
allResults.sort((a, b) => b.relevance - a.relevance);
|
||||
const top = allResults.slice(0, MAX_DROPDOWN_RESULTS);
|
||||
|
||||
setResults(top);
|
||||
setNotices(allNotices);
|
||||
setHasErrors(anyError);
|
||||
setOpen(true);
|
||||
setSelectedIndex(-1);
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = e.target.value;
|
||||
setQuery(value);
|
||||
if (timerRef.current) clearTimeout(timerRef.current);
|
||||
timerRef.current = setTimeout(() => runSearch(value), DEBOUNCE_MS);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (!open) {
|
||||
if (e.key === 'Enter' && query.trim()) {
|
||||
history.push(`/search?q=${encodeURIComponent(query.trim())}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setSelectedIndex((prev) => Math.min(prev + 1, results.length - 1));
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setSelectedIndex((prev) => Math.max(prev - 1, -1));
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (selectedIndex >= 0 && results[selectedIndex]) {
|
||||
window.location.href = results[selectedIndex].url;
|
||||
} else if (query.trim()) {
|
||||
history.push(`/search?q=${encodeURIComponent(query.trim())}`);
|
||||
}
|
||||
setOpen(false);
|
||||
} else if (e.key === 'Escape') {
|
||||
setOpen(false);
|
||||
setSelectedIndex(-1);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
setOpen(false);
|
||||
setSelectedIndex(-1);
|
||||
}
|
||||
};
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timerRef.current) clearTimeout(timerRef.current);
|
||||
if (abortRef.current) abortRef.current.abort();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={styles.container}
|
||||
>
|
||||
<input
|
||||
className={styles.input}
|
||||
type="search"
|
||||
placeholder="Поиск..."
|
||||
value={query}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
aria-label="Поиск по документации"
|
||||
aria-expanded={open}
|
||||
aria-autocomplete="list"
|
||||
role="combobox"
|
||||
/>
|
||||
{loading && (
|
||||
<span
|
||||
className={styles.spinner}
|
||||
aria-label="Загрузка..."
|
||||
/>
|
||||
)}
|
||||
{open && (
|
||||
<div
|
||||
className={styles.dropdown}
|
||||
role="listbox"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
>
|
||||
{hasErrors && (
|
||||
<div className={styles.errorBadge}>Некоторые источники недоступны</div>
|
||||
)}
|
||||
{results.length === 0 && !loading && (
|
||||
<div className={styles.empty}>Ничего не найдено</div>
|
||||
)}
|
||||
{results.map((result, i) => (
|
||||
<a
|
||||
key={`${result.url}-${i}`}
|
||||
href={result.url}
|
||||
role="option"
|
||||
aria-selected={i === selectedIndex}
|
||||
className={
|
||||
i === selectedIndex
|
||||
? `${styles.item} ${styles.selectedItem}`
|
||||
: styles.item
|
||||
}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
<div className={styles.itemHeading}>{result.title}</div>
|
||||
<div className={styles.itemFile}>
|
||||
<span
|
||||
className={styles.badge}
|
||||
data-type={result.type}
|
||||
>
|
||||
{result.type}
|
||||
</span>
|
||||
{result.path}
|
||||
<span className={styles.itemScore}>
|
||||
{Math.round(result.relevance * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
{result.content && (
|
||||
<div className={styles.itemContent}>{result.content}</div>
|
||||
)}
|
||||
</a>
|
||||
))}
|
||||
{notices.map((notice, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={styles.notice}
|
||||
>
|
||||
{notice}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
.container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.input {
|
||||
width: 200px;
|
||||
height: 32px;
|
||||
padding: 0 32px 0 12px;
|
||||
color: var(--ifm-font-color-base);
|
||||
font-size: var(--ifm-font-size-base);
|
||||
background: var(--ifm-background-surface-color);
|
||||
border: 1px solid var(--ifm-color-emphasis-300);
|
||||
border-radius: var(--ifm-global-radius);
|
||||
outline: none;
|
||||
transition:
|
||||
width 0.2s ease,
|
||||
border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.input:focus {
|
||||
width: 280px;
|
||||
border-color: var(--ifm-color-primary);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid var(--ifm-color-emphasis-300);
|
||||
border-top-color: var(--ifm-color-primary);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.dropdown {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
right: 0;
|
||||
z-index: 100;
|
||||
min-width: 320px;
|
||||
max-width: 480px;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
background: var(--ifm-background-surface-color);
|
||||
border: 1px solid var(--ifm-color-emphasis-300);
|
||||
border-radius: var(--ifm-global-radius);
|
||||
box-shadow: var(--ifm-global-shadow-md);
|
||||
}
|
||||
|
||||
.item {
|
||||
display: block;
|
||||
padding: 10px 14px;
|
||||
color: var(--ifm-font-color-base);
|
||||
text-decoration: none;
|
||||
border-bottom: 1px solid var(--ifm-color-emphasis-200);
|
||||
}
|
||||
|
||||
.item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.item:hover {
|
||||
color: var(--ifm-color-primary);
|
||||
text-decoration: none;
|
||||
background: var(--ifm-color-emphasis-100);
|
||||
}
|
||||
|
||||
.selectedItem {
|
||||
color: var(--ifm-color-primary);
|
||||
background: var(--ifm-color-emphasis-100);
|
||||
outline: 2px solid var(--ifm-color-primary-light);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.itemHeading {
|
||||
margin-bottom: 2px;
|
||||
font-weight: var(--ifm-font-weight-semibold);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 1px 6px;
|
||||
color: var(--ifm-color-emphasis-700);
|
||||
font-weight: normal;
|
||||
font-size: 0.65rem;
|
||||
letter-spacing: 0.04em;
|
||||
white-space: nowrap;
|
||||
text-transform: uppercase;
|
||||
background: var(--ifm-color-emphasis-200);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.itemFile {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
margin-bottom: 4px;
|
||||
color: var(--ifm-color-emphasis-600);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.itemScore {
|
||||
margin-left: auto;
|
||||
color: var(--ifm-color-emphasis-500);
|
||||
font-size: 0.7rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.itemContent {
|
||||
display: -webkit-box;
|
||||
overflow: hidden;
|
||||
color: var(--ifm-color-emphasis-700);
|
||||
font-size: 0.8rem;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 12px 14px;
|
||||
color: var(--ifm-color-emphasis-600);
|
||||
font-size: 0.875rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.notice {
|
||||
padding: 8px 14px;
|
||||
color: var(--ifm-color-info-dark);
|
||||
font-size: 0.8rem;
|
||||
background: var(--ifm-color-info-contrast-background);
|
||||
border-top: 1px solid var(--ifm-color-emphasis-200);
|
||||
}
|
||||
|
||||
.errorBadge {
|
||||
padding: 8px 14px;
|
||||
color: var(--ifm-color-warning-dark);
|
||||
font-size: 0.8rem;
|
||||
background: var(--ifm-color-warning-contrast-background);
|
||||
border-bottom: 1px solid var(--ifm-color-emphasis-200);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { useHistory, useLocation } from '@docusaurus/router';
|
||||
import searchConfig from '@docuservix-search/config';
|
||||
import Link from '@docusaurus/Link';
|
||||
import Layout from '@theme/Layout';
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import type { SearchResult } from '../../types';
|
||||
|
||||
import styles from './styles.module.css';
|
||||
|
||||
const MAX_RESULTS = 25;
|
||||
|
||||
function useQuery(): string {
|
||||
const location = useLocation();
|
||||
const params = new URLSearchParams(location.search);
|
||||
|
||||
return params.get('q') ?? '';
|
||||
}
|
||||
|
||||
export default function SearchPage(): JSX.Element {
|
||||
const urlQuery = useQuery();
|
||||
const history = useHistory();
|
||||
|
||||
const [inputValue, setInputValue] = useState(urlQuery);
|
||||
const [results, setResults] = useState<SearchResult[]>([]);
|
||||
const [notices, setNotices] = useState<string[]>([]);
|
||||
const [errors, setErrors] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [activeFilter, setActiveFilter] = useState<string>('all');
|
||||
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const runSearch = useCallback(async (q: string) => {
|
||||
if (!q.trim()) {
|
||||
setResults([]);
|
||||
setNotices([]);
|
||||
setErrors([]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (abortRef.current) {
|
||||
abortRef.current.abort();
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
abortRef.current = controller;
|
||||
|
||||
const timeout = searchConfig.timeout ?? 5000;
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
setLoading(true);
|
||||
setErrors([]);
|
||||
|
||||
try {
|
||||
const settled = await Promise.allSettled(
|
||||
searchConfig.providers.map((provider) => provider.search(q, controller.signal)),
|
||||
);
|
||||
|
||||
if (controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
|
||||
const allResults: SearchResult[] = [];
|
||||
const allNotices: string[] = [];
|
||||
const allErrors: string[] = [];
|
||||
|
||||
for (let i = 0; i < settled.length; i++) {
|
||||
const outcome = settled[i];
|
||||
const provider = searchConfig.providers[i];
|
||||
|
||||
if (outcome.status === 'fulfilled') {
|
||||
allResults.push(...outcome.value.results);
|
||||
|
||||
if (outcome.value.notice) {
|
||||
allNotices.push(outcome.value.notice);
|
||||
}
|
||||
} else {
|
||||
allErrors.push(`${provider.name}: недоступен`);
|
||||
}
|
||||
}
|
||||
|
||||
allResults.sort((a, b) => b.relevance - a.relevance);
|
||||
|
||||
setResults(allResults.slice(0, MAX_RESULTS));
|
||||
setNotices(allNotices);
|
||||
setErrors(allErrors);
|
||||
setActiveFilter('all');
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setInputValue(urlQuery);
|
||||
runSearch(urlQuery);
|
||||
}, [urlQuery, runSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (abortRef.current) {
|
||||
abortRef.current.abort();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setInputValue(e.target.value);
|
||||
};
|
||||
|
||||
const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter' && inputValue.trim()) {
|
||||
history.push(`/search?q=${encodeURIComponent(inputValue.trim())}`);
|
||||
}
|
||||
};
|
||||
|
||||
const sourceTypes = ['all', ...Array.from(new Set(results.map((r) => r.type)))];
|
||||
|
||||
const filteredResults =
|
||||
activeFilter === 'all' ? results : results.filter((r) => r.type === activeFilter);
|
||||
|
||||
const typeLabel: Record<string, string> = {
|
||||
all: 'Все',
|
||||
docs: 'Docs',
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout title={urlQuery ? `Поиск: ${urlQuery}` : 'Поиск'}>
|
||||
<div className={styles.container}>
|
||||
<h1 className={styles.heading}>Поиск</h1>
|
||||
<input
|
||||
className={styles.searchInput}
|
||||
type="search"
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
placeholder="Введите запрос и нажмите Enter..."
|
||||
aria-label="Поисковый запрос"
|
||||
/>
|
||||
|
||||
{urlQuery && (
|
||||
<Link
|
||||
to={`/chat?q=${encodeURIComponent(urlQuery)}`}
|
||||
className={styles.chatLink}
|
||||
>
|
||||
Спросить ИИ →
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{errors.length > 0 && (
|
||||
<div
|
||||
className="alert alert--warning"
|
||||
role="alert"
|
||||
>
|
||||
{errors.map((err, i) => (
|
||||
<div key={i}>{err}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{notices.length > 0 && (
|
||||
<div
|
||||
className="alert alert--info"
|
||||
role="note"
|
||||
>
|
||||
{notices.map((notice, i) => (
|
||||
<div key={i}>{notice}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && <div className={styles.loadingText}>Поиск...</div>}
|
||||
|
||||
{!loading && urlQuery && (
|
||||
<>
|
||||
{sourceTypes.length > 2 && (
|
||||
<div
|
||||
className={styles.filters}
|
||||
role="tablist"
|
||||
>
|
||||
{sourceTypes.map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
role="tab"
|
||||
aria-selected={activeFilter === type}
|
||||
className={
|
||||
activeFilter === type
|
||||
? `${styles.filterBtn} ${styles.filterBtnActive}`
|
||||
: styles.filterBtn
|
||||
}
|
||||
onClick={() => setActiveFilter(type)}
|
||||
>
|
||||
{typeLabel[type] ?? type}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{filteredResults.length === 0 ? (
|
||||
<div className={styles.empty}>Ничего не найдено</div>
|
||||
) : (
|
||||
<div className={styles.resultList}>
|
||||
{filteredResults.map((result, i) => (
|
||||
<a
|
||||
key={`${result.url}-${i}`}
|
||||
href={result.url}
|
||||
className={styles.resultItem}
|
||||
>
|
||||
<div className={styles.resultTitle}>{result.title}</div>
|
||||
<div className={styles.resultMeta}>
|
||||
<span
|
||||
className={styles.badge}
|
||||
data-type={result.type}
|
||||
>
|
||||
{typeLabel[result.type] ?? result.type}
|
||||
</span>
|
||||
<span className={styles.resultPath}>{result.path}</span>
|
||||
{result.anchor && (
|
||||
<span className={styles.resultAnchor}>
|
||||
#{result.anchor}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.resultScore}>
|
||||
{Math.round(result.relevance * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
{result.content && (
|
||||
<div className={styles.resultContent}>
|
||||
{result.content}
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
.container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem 1rem;
|
||||
}
|
||||
|
||||
.heading {
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.searchInput {
|
||||
width: 100%;
|
||||
height: 40px;
|
||||
margin-bottom: 1.5rem;
|
||||
padding: 0 16px;
|
||||
color: var(--ifm-font-color-base);
|
||||
font-size: var(--ifm-font-size-base);
|
||||
background: var(--ifm-background-surface-color);
|
||||
border: 1px solid var(--ifm-color-emphasis-300);
|
||||
border-radius: var(--ifm-global-radius);
|
||||
outline: none;
|
||||
transition: border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.searchInput:focus {
|
||||
border-color: var(--ifm-color-primary);
|
||||
}
|
||||
|
||||
.loadingText {
|
||||
padding: 1rem 0;
|
||||
color: var(--ifm-color-emphasis-600);
|
||||
}
|
||||
|
||||
.filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.filterBtn {
|
||||
padding: 4px 12px;
|
||||
color: var(--ifm-font-color-base);
|
||||
font-size: 0.875rem;
|
||||
background: var(--ifm-background-surface-color);
|
||||
border: 1px solid var(--ifm-color-emphasis-300);
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.filterBtn:hover {
|
||||
border-color: var(--ifm-color-primary);
|
||||
}
|
||||
|
||||
.filterBtnActive {
|
||||
color: var(--ifm-color-primary-contrast-foreground);
|
||||
background: var(--ifm-color-primary);
|
||||
border-color: var(--ifm-color-primary);
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 2rem 0;
|
||||
color: var(--ifm-color-emphasis-600);
|
||||
font-size: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.resultList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--ifm-color-emphasis-300);
|
||||
border-radius: var(--ifm-global-radius);
|
||||
}
|
||||
|
||||
.resultItem {
|
||||
display: block;
|
||||
padding: 12px 16px;
|
||||
color: var(--ifm-font-color-base);
|
||||
text-decoration: none;
|
||||
border-bottom: 1px solid var(--ifm-color-emphasis-200);
|
||||
transition: background 0.1s ease;
|
||||
}
|
||||
|
||||
.resultItem:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.resultItem:hover {
|
||||
color: var(--ifm-font-color-base);
|
||||
text-decoration: none;
|
||||
background: var(--ifm-color-emphasis-100);
|
||||
}
|
||||
|
||||
.resultTitle {
|
||||
margin-bottom: 4px;
|
||||
font-weight: var(--ifm-font-weight-semibold);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.resultMeta {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.resultPath {
|
||||
color: var(--ifm-color-emphasis-600);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.resultAnchor {
|
||||
color: var(--ifm-color-emphasis-500);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.resultScore {
|
||||
margin-left: auto;
|
||||
color: var(--ifm-color-emphasis-500);
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.resultContent {
|
||||
display: -webkit-box;
|
||||
overflow: hidden;
|
||||
color: var(--ifm-color-emphasis-700);
|
||||
font-size: 0.85rem;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.chatLink {
|
||||
display: inline-block;
|
||||
margin-bottom: 1rem;
|
||||
padding: 6px 14px;
|
||||
color: var(--ifm-color-primary);
|
||||
font-size: 0.875rem;
|
||||
text-decoration: none;
|
||||
border: 1px solid var(--ifm-color-primary);
|
||||
border-radius: var(--ifm-global-radius);
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
color 0.15s ease;
|
||||
}
|
||||
|
||||
.chatLink:hover {
|
||||
color: var(--ifm-color-primary-contrast-foreground);
|
||||
text-decoration: none;
|
||||
background: var(--ifm-color-primary);
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 1px 8px;
|
||||
color: var(--ifm-color-emphasis-700);
|
||||
font-weight: normal;
|
||||
font-size: 0.7rem;
|
||||
letter-spacing: 0.04em;
|
||||
white-space: nowrap;
|
||||
text-transform: uppercase;
|
||||
background: var(--ifm-color-emphasis-200);
|
||||
border-radius: 999px;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface SearchResult {
|
||||
title: string;
|
||||
content: string;
|
||||
path: string;
|
||||
anchor?: string;
|
||||
type: string;
|
||||
relevance: number; // 0–1
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface SearchProviderResponse {
|
||||
results: SearchResult[];
|
||||
notice?: string;
|
||||
}
|
||||
|
||||
export interface SearchProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
timeout?: number;
|
||||
search: (query: string, signal: AbortSignal) => Promise<SearchProviderResponse>;
|
||||
}
|
||||
|
||||
export interface SearchConfig {
|
||||
timeout: number;
|
||||
providers: SearchProvider[];
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type {
|
||||
SearchConfig,
|
||||
SearchProvider,
|
||||
SearchResult,
|
||||
} from '../plugins/docuservix-search/types';
|
||||
|
||||
interface RawResult {
|
||||
score: number;
|
||||
file: string;
|
||||
heading: string;
|
||||
anchor?: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
function stripNumericPrefixes(p: string): string {
|
||||
return p
|
||||
.split('/')
|
||||
.map((seg) => seg.replace(/^\d+-/, ''))
|
||||
.join('/');
|
||||
}
|
||||
|
||||
function resultToUrl(file: string, anchor: string): string {
|
||||
let p = file.replace(/^docs\//, '').replace(/\.md$/, '');
|
||||
|
||||
p = stripNumericPrefixes(p);
|
||||
|
||||
return `/docs/${p}#${anchor}`;
|
||||
}
|
||||
|
||||
function resultToDisplayPath(file: string): string {
|
||||
const p = file.replace(/^docs\//, '').replace(/\.md$/, '');
|
||||
|
||||
return stripNumericPrefixes(p);
|
||||
}
|
||||
|
||||
function rawToSearchResult(raw: RawResult): SearchResult {
|
||||
return {
|
||||
title: raw.heading,
|
||||
content: raw.content,
|
||||
path: resultToDisplayPath(raw.file),
|
||||
anchor: raw.anchor,
|
||||
type: 'docs',
|
||||
relevance: raw.score,
|
||||
url: resultToUrl(raw.file, raw.anchor),
|
||||
};
|
||||
}
|
||||
|
||||
const docsProvider: SearchProvider = {
|
||||
id: 'docs',
|
||||
name: 'Документация',
|
||||
timeout: 5000,
|
||||
async search(query, signal) {
|
||||
const res = await fetch(
|
||||
`http://localhost:8080/1vit/more/v1/search?q=${encodeURIComponent(query)}&limit=25`,
|
||||
{ signal },
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const data: { results: RawResult[] } = await res.json();
|
||||
|
||||
return {
|
||||
results: (data.results ?? []).map(rawToSearchResult),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const searchConfig: SearchConfig = {
|
||||
timeout: 5000,
|
||||
providers: [docsProvider],
|
||||
};
|
||||
|
||||
export default searchConfig;
|
||||
|
||||
export const chatUrl = 'http://localhost:8080/1vit/more/v1/chat';
|
||||
Reference in New Issue
Block a user