4 Commits
Author SHA1 Message Date
arswarogandClaude Opus 4.7 18eb34f541 chat/widget: отображение статуса подключения бота
Заменяет захардкоженное "Ready to help" на живой индикатор.
Статус берётся из поля status ответа GET /v1/status, капитализируется
и показывается справа от имени бота. Polling каждые 30с, пауза при
скрытой вкладке, recheck по клику, tooltip с API URL.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-09 11:59:23 +03:00
arswarog 8ff4ba6c94 chat/widget: отображение использованых источников 2026-07-08 11:12:26 +03:00
arswarog 33236cf6a9 chat: подключение к бекенду 2026-07-08 11:11:53 +03:00
arswarog 03f7302317 docuservix/widgets/chat: добавлен компонент чата
Reviewed-on: #6
Co-authored-by: Arswarog <arswarog@yandex.ru>
Co-committed-by: Arswarog <arswarog@yandex.ru>
2026-06-19 18:28:07 +03:00
18 changed files with 343 additions and 26 deletions
+7 -5
View File
@@ -11,11 +11,13 @@ Docuservix docs — шаблон документационного сайта
## Commands
- `npm start` — dev-сервер
- `npm run build` — production-сборка в `build/`
- `npm run typecheck` — проверка типов (tsc)
- `npm run prettier:check` — проверка форматирования
- `npm run prettier:fix` — автоформатирование
Используется **yarn**.
- `yarn start` — dev-сервер
- `yarn build` — production-сборка в `build/`
- `yarn typecheck` — проверка типов (tsc)
- `yarn prettier:check` — проверка форматирования
- `yarn prettier:fix` — автоформатирование
## Architecture
+3 -1
View File
@@ -48,7 +48,9 @@
"js-yaml": "^4.2.0",
"prism-react-renderer": "^2.3.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.10.1",
@@ -0,0 +1,59 @@
.MD p:last-child {
margin-bottom: 0;
}
.MD p:first-child {
margin-top: 0;
}
.MD code {
padding: 0.15em 0.4em;
border-radius: 4px;
background: var(--ifm-color-emphasis-200);
font-size: 0.85em;
}
.MD pre {
margin: 0.5em 0;
padding: 0.75em;
overflow-x: auto;
border-radius: 6px;
background: var(--ifm-color-emphasis-100);
}
.MD pre code {
padding: 0;
background: none;
}
.MD ul,
.MD ol {
padding-left: 1.5em;
margin: 0.5em 0;
}
.MD table {
width: 100%;
margin: 0.5em 0;
border-collapse: collapse;
font-size: 0.9em;
}
.MD th,
.MD td {
padding: 0.4em 0.75em;
border: 1px solid var(--ifm-color-emphasis-300);
text-align: left;
}
.MD th {
background: var(--ifm-color-emphasis-100);
font-weight: var(--ifm-font-weight-semibold);
}
.MD blockquote {
margin: 0.5em 0;
padding: 0.25em 1em;
border-left: 3px solid var(--ifm-color-emphasis-300);
color: var(--ifm-color-emphasis-700);
}
@@ -0,0 +1,17 @@
import React, { ReactNode } from 'react';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import styles from './MD.module.css';
interface MDProps {
children: string;
}
export function MD({ children }: MDProps): ReactNode {
return (
<div className={styles.MD}>
<Markdown remarkPlugins={[remarkGfm]}>{children}</Markdown>
</div>
);
}
@@ -0,0 +1 @@
export { MD } from './MD';
+1 -1
View File
@@ -19,7 +19,7 @@ function useQuery(): string {
}
export function useChat(): UseChatResult {
const chatEndpoint = useOptions().api + '/chat';
const chatEndpoint = useOptions().api + '/v1/chat';
const urlQuery = useQuery();
const [messages, setMessages] = useState<IChatMessage[]>([]);
+119
View File
@@ -0,0 +1,119 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useOptions } from '@docuservix/hooks/useOptions';
import { ChatStatus } from '@docuservix/models/chat';
interface UseChatStatusResult {
status: ChatStatus;
apiUrl: string;
recheck: () => void;
}
const POLL_INTERVAL_MS = 30_000;
const REQUEST_TIMEOUT_MS = 5_000;
function sameStatus(a: ChatStatus, b: ChatStatus): boolean {
if (a.kind !== b.kind) return false;
if (a.kind === 'server' && b.kind === 'server') return a.label === b.label;
return true;
}
export function useChatStatus(): UseChatStatusResult {
const apiUrl = useOptions().api ?? '';
const statusApiUrl = apiUrl + '/v1/status';
const [status, setStatus] = useState<ChatStatus>({ kind: 'connecting' });
const abortRef = useRef<AbortController | null>(null);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const updateStatus = useCallback((next: ChatStatus): void => {
setStatus((prev) => (sameStatus(prev, next) ? prev : next));
}, []);
const check = useCallback(async (): Promise<void> => {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
let timedOut = false;
const timeoutId = setTimeout(() => {
timedOut = true;
controller.abort();
}, REQUEST_TIMEOUT_MS);
try {
const res = await fetch(statusApiUrl, { signal: controller.signal });
if (!res.ok) {
updateStatus({ kind: 'offline' });
return;
}
const parsed = (await res.json()) as { status?: unknown } | null | undefined;
const raw = typeof parsed?.status === 'string' ? parsed.status : null;
if (raw === null || raw.length === 0) {
updateStatus({ kind: 'offline' });
return;
}
updateStatus({
kind: 'server',
label: raw.charAt(0).toUpperCase() + raw.slice(1),
});
} catch {
if (!controller.signal.aborted || timedOut) {
updateStatus({ kind: 'offline' });
}
} finally {
clearTimeout(timeoutId);
}
}, [statusApiUrl, updateStatus]);
const scheduleNext = useCallback((): void => {
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(async () => {
if (document.visibilityState === 'visible') {
await check();
}
scheduleNext();
}, POLL_INTERVAL_MS);
}, [check]);
const recheck = useCallback((): void => {
updateStatus({ kind: 'connecting' });
void check();
scheduleNext();
}, [check, scheduleNext, updateStatus]);
useEffect(() => {
void check();
scheduleNext();
const onVisibilityChange = (): void => {
if (document.visibilityState === 'visible') {
void check();
scheduleNext();
}
};
document.addEventListener('visibilitychange', onVisibilityChange);
return (): void => {
document.removeEventListener('visibilitychange', onVisibilityChange);
abortRef.current?.abort();
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
}
};
}, [check, scheduleNext]);
return { status, apiUrl, recheck };
}
+1 -1
View File
@@ -5,7 +5,7 @@ import type { LoadContext, Plugin } from '@docusaurus/types';
import { DocuservixOptions } from '@docuservix/models/docuservix';
export default function docuservix(options: Partial<DocuservixOptions> = {}) {
const { api = '/api' } = options;
const api = process.env.DOCUSERVIX_API || options.api || '/api';
return function pluginDocuservix(_context: LoadContext): Plugin {
return {
+5
View File
@@ -1,3 +1,8 @@
export type ChatStatus =
| { kind: 'connecting' }
| { kind: 'offline' }
| { kind: 'server'; label: string };
export interface IChat {
messages: IChatMessage[];
}
+1 -1
View File
@@ -29,7 +29,7 @@ export function Chat({ dialog, typing, statusMessage, onSend }: ChatProps): Reac
/>
{statusMessage && <div className={b('statusMessage')}>{statusMessage}</div>}
<Input
loading={typing}
disabled={typing}
onSend={onSend}
/>
</div>
@@ -24,9 +24,3 @@
color: var(--ifm-font-color-base);
font-size: 1.125rem;
}
.Header__info p {
margin: 0;
color: var(--ifm-color-emphasis-600);
font-size: 0.85rem;
}
+2 -1
View File
@@ -3,6 +3,7 @@ import React, { ReactNode } from 'react';
import styles from './Header.module.css';
import { RobotIcon } from './icons';
import { Status } from './Status';
const b = block(styles, 'Header');
@@ -14,7 +15,7 @@ export function Header(): ReactNode {
</div>
<div className={b('info')}>
<h3>AI Assistant</h3>
<p>Ready to help</p>
<Status />
</div>
</div>
);
+5 -5
View File
@@ -7,17 +7,17 @@ import styles from './Input.module.css';
const b = block(styles, 'Input');
interface InputProps {
loading?: boolean;
disabled?: boolean;
onSend?: (text: string) => void;
}
export function Input({ loading, onSend }: InputProps): ReactNode {
export function Input({ disabled, onSend }: InputProps): ReactNode {
const [input, setInput] = useState('');
const handleSend = () => {
const text = input.trim();
if (!text || loading) {
if (!text || disabled) {
return;
}
@@ -41,12 +41,12 @@ export function Input({ loading, onSend }: InputProps): ReactNode {
onKeyDown={handleKeyDown}
placeholder="Type your message here..."
rows={1}
disabled={loading}
disabled={disabled}
/>
<button
className={b('send')}
onClick={handleSend}
disabled={loading || !input.trim()}
disabled={disabled || !input.trim()}
>
<PaperPlaneIcon />
</button>
@@ -1,5 +1,5 @@
.Message {
max-width: 85%;
max-width: 90%;
animation: slideIn 0.3s ease-out;
}
@@ -63,8 +63,8 @@
text-decoration: underline;
}
@media (min-width: 576px) {
@media (max-width: 576px) {
.Message {
max-width: 75%;
max-width: 100%;
}
}
+5 -1
View File
@@ -2,6 +2,8 @@ import Link from '@docusaurus/Link';
import block from 'bem-css-modules';
import React, { ReactNode } from 'react';
import { MD } from '@docuservix/entities/markdown';
import { IChatSource, sourceToPath, sourceToUrl } from '@docuservix/models/chat';
import styles from './Message.module.css';
@@ -17,7 +19,9 @@ interface MessageProps {
export function Message({ role, content, sources }: MessageProps): ReactNode {
return (
<div className={b({ role })}>
<div className={b('content')}>{content}</div>
<div className={b('content')}>
<MD>{content}</MD>
</div>
{sources && sources.length > 0 && (
<div className={b('sources')}>
@@ -0,0 +1,53 @@
.Status {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0;
background: none;
border: none;
cursor: pointer;
color: var(--ifm-color-emphasis-600);
font-size: 0.85rem;
line-height: 1;
}
.Status:hover .Status__label {
color: var(--ifm-color-emphasis-800);
}
.Status:focus-visible {
outline: 2px solid var(--ifm-color-primary);
outline-offset: 2px;
border-radius: 4px;
}
.Status__dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--ifm-color-emphasis-400);
flex-shrink: 0;
}
.Status_kind_server .Status__dot {
background: #22c55e;
}
.Status_kind_offline .Status__dot {
background: #ef4444;
}
.Status_kind_connecting .Status__dot {
background: #eab308;
animation: Status__pulse 1s ease-in-out infinite;
}
@keyframes Status__pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.4;
}
}
@@ -0,0 +1,38 @@
import block from 'bem-css-modules';
import React, { ReactNode } from 'react';
import { useChatStatus } from '@docuservix/hooks/useChatStatus';
import { ChatStatus } from '@docuservix/models/chat';
import styles from './Status.module.css';
const b = block(styles, 'Status');
function getLabel(status: ChatStatus): string {
switch (status.kind) {
case 'connecting':
return 'Подключение…';
case 'offline':
return 'Offline';
case 'server':
return status.label;
}
}
export function Status(): ReactNode {
const { status, apiUrl, recheck } = useChatStatus();
const label = getLabel(status);
return (
<button
type="button"
className={b({ kind: status.kind })}
onClick={recheck}
title={apiUrl}
aria-label={`Статус: ${label}. Нажмите для проверки`}
>
<span className={b('dot')} />
<span className={b('label')}>{label}</span>
</button>
);
}
+23 -1
View File
@@ -7308,6 +7308,11 @@ html-tags@^3.3.1:
resolved "https://registry.yarnpkg.com/html-tags/-/html-tags-3.3.1.tgz#a04026a18c882e4bba8a01a3d39cfe465d40b5ce"
integrity sha512-ztqyC3kLto0e9WbNp0aeP+M3kTt+nbaIveGmUxAtZa+8iFgKLUOD4YKM5j+f3QD89bra7UeumolZHKuOXnTmeQ==
html-url-attributes@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/html-url-attributes/-/html-url-attributes-3.0.1.tgz#83b052cd5e437071b756cd74ae70f708870c2d87"
integrity sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==
html-void-elements@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/html-void-elements/-/html-void-elements-3.0.0.tgz#fc9dbd84af9e747249034d4d62602def6517f1d7"
@@ -10556,6 +10561,23 @@ react-loadable-ssr-addon-v5-slorber@^1.0.3:
dependencies:
"@types/react" "*"
react-markdown@^10.1.0:
version "10.1.0"
resolved "https://registry.yarnpkg.com/react-markdown/-/react-markdown-10.1.0.tgz#e22bc20faddbc07605c15284255653c0f3bad5ca"
integrity sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==
dependencies:
"@types/hast" "^3.0.0"
"@types/mdast" "^4.0.0"
devlop "^1.0.0"
hast-util-to-jsx-runtime "^2.0.0"
html-url-attributes "^3.0.0"
mdast-util-to-hast "^13.0.0"
remark-parse "^11.0.0"
remark-rehype "^11.0.0"
unified "^11.0.0"
unist-util-visit "^5.0.0"
vfile "^6.0.0"
react-router-config@^5.1.1:
version "5.1.1"
resolved "https://registry.yarnpkg.com/react-router-config/-/react-router-config-5.1.1.tgz#0f4263d1a80c6b2dc7b9c1902c9526478194a988"
@@ -10809,7 +10831,7 @@ remark-frontmatter@^5.0.0:
micromark-extension-frontmatter "^2.0.0"
unified "^11.0.0"
remark-gfm@^4.0.0:
remark-gfm@^4.0.0, remark-gfm@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/remark-gfm/-/remark-gfm-4.0.1.tgz#33227b2a74397670d357bf05c098eaf8513f0d6b"
integrity sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==