global update and global fix
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
'use client';
|
||||
|
||||
import { Copy } from 'lucide-react';
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger
|
||||
} from '@/components/ui/context-menu';
|
||||
|
||||
interface BotChatMessageContextMenuProps {
|
||||
text?: string;
|
||||
onCopy?: () => void;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function BotChatMessageContextMenu({ text, onCopy, children }: BotChatMessageContextMenuProps) {
|
||||
const copyText = text?.trim();
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
<ContextMenuContent className="min-w-[200px]">
|
||||
{copyText ? (
|
||||
<ContextMenuItem
|
||||
onClick={() => {
|
||||
void navigator.clipboard.writeText(copyText);
|
||||
onCopy?.();
|
||||
}}
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
Копировать текст
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
);
|
||||
}
|
||||
122
apps/frontend/components/chat/bot-inline-keyboard.tsx
Normal file
122
apps/frontend/components/chat/bot-inline-keyboard.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
'use client';
|
||||
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { InlineKeyboardButton, parseInlineKeyboardMarkup } from '@/lib/bot-reply-markup';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function buildInlineButtonKey(messageId: number, rowIndex: number, buttonIndex: number) {
|
||||
return `${messageId}:${rowIndex}:${buttonIndex}`;
|
||||
}
|
||||
|
||||
interface BotInlineKeyboardProps {
|
||||
markup: unknown;
|
||||
messageId: number;
|
||||
loadingButtonKey?: string | null;
|
||||
disabled?: boolean;
|
||||
onCallbackClick?: (callbackData: string, buttonKey: string) => void | Promise<void>;
|
||||
onOpenMiniApp?: (url: string) => void;
|
||||
onOpenUrl?: (url: string) => void;
|
||||
}
|
||||
|
||||
export function BotInlineKeyboard({
|
||||
markup,
|
||||
messageId,
|
||||
loadingButtonKey = null,
|
||||
disabled = false,
|
||||
onCallbackClick,
|
||||
onOpenMiniApp,
|
||||
onOpenUrl
|
||||
}: BotInlineKeyboardProps) {
|
||||
const rows = parseInlineKeyboardMarkup(markup);
|
||||
if (!rows.length) return null;
|
||||
|
||||
return (
|
||||
<div className="mt-2 space-y-1.5">
|
||||
{rows.map((row, rowIndex) => (
|
||||
<div
|
||||
key={`row-${rowIndex}`}
|
||||
className={cn('flex gap-1.5', row.length === 1 ? 'flex-col' : 'flex-row flex-wrap')}
|
||||
>
|
||||
{row.map((button, buttonIndex) => (
|
||||
<InlineKeyboardButtonView
|
||||
key={`btn-${rowIndex}-${buttonIndex}`}
|
||||
button={button}
|
||||
buttonKey={buildInlineButtonKey(messageId, rowIndex, buttonIndex)}
|
||||
fullWidth={row.length === 1}
|
||||
loading={loadingButtonKey === buildInlineButtonKey(messageId, rowIndex, buttonIndex)}
|
||||
disabled={disabled || (loadingButtonKey !== null && loadingButtonKey !== buildInlineButtonKey(messageId, rowIndex, buttonIndex))}
|
||||
onCallbackClick={onCallbackClick}
|
||||
onOpenMiniApp={onOpenMiniApp}
|
||||
onOpenUrl={onOpenUrl}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InlineKeyboardButtonView({
|
||||
button,
|
||||
buttonKey,
|
||||
fullWidth,
|
||||
loading,
|
||||
disabled,
|
||||
onCallbackClick,
|
||||
onOpenMiniApp,
|
||||
onOpenUrl
|
||||
}: {
|
||||
button: InlineKeyboardButton;
|
||||
buttonKey: string;
|
||||
fullWidth: boolean;
|
||||
loading: boolean;
|
||||
disabled: boolean;
|
||||
onCallbackClick?: (callbackData: string, buttonKey: string) => void | Promise<void>;
|
||||
onOpenMiniApp?: (url: string) => void;
|
||||
onOpenUrl?: (url: string) => void;
|
||||
}) {
|
||||
const webAppUrl = button.web_app?.url;
|
||||
const callbackData = button.callback_data ?? button.callbackData;
|
||||
|
||||
async function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
|
||||
event.preventDefault();
|
||||
if (disabled || loading) return;
|
||||
|
||||
if (webAppUrl) {
|
||||
if (onOpenMiniApp) {
|
||||
onOpenMiniApp(webAppUrl);
|
||||
} else {
|
||||
window.open(webAppUrl, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (button.url) {
|
||||
if (onOpenUrl) {
|
||||
onOpenUrl(button.url);
|
||||
} else {
|
||||
window.open(button.url, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (callbackData && onCallbackClick) {
|
||||
await onCallbackClick(callbackData, buttonKey);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled || loading}
|
||||
className={cn(
|
||||
'inline-flex min-h-9 items-center justify-center rounded-xl border border-[#dce3ec] bg-[#f4f7fb] px-3 py-2 text-xs font-medium text-[#1f2430] transition',
|
||||
'hover:bg-[#e8eef6] disabled:cursor-not-allowed disabled:opacity-60',
|
||||
fullWidth ? 'w-full' : 'min-w-0 flex-1'
|
||||
)}
|
||||
onClick={(event) => void handleClick(event)}
|
||||
>
|
||||
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : button.text}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
109
apps/frontend/components/chat/bot-message-keyboard.tsx
Normal file
109
apps/frontend/components/chat/bot-message-keyboard.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { BotInlineKeyboard } from '@/components/chat/bot-inline-keyboard';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { useRealtime } from '@/components/notifications/realtime-provider';
|
||||
import { submitBotCallback } from '@/lib/api';
|
||||
|
||||
const CALLBACK_ANSWER_TIMEOUT_MS = 30_000;
|
||||
|
||||
interface BotMessageKeyboardProps {
|
||||
botRef: string;
|
||||
messageId: number;
|
||||
markup: unknown;
|
||||
token: string | null;
|
||||
botId?: string;
|
||||
onOpenMiniApp?: (url: string) => void;
|
||||
}
|
||||
|
||||
export function BotMessageKeyboard({
|
||||
botRef,
|
||||
messageId,
|
||||
markup,
|
||||
token,
|
||||
botId,
|
||||
onOpenMiniApp
|
||||
}: BotMessageKeyboardProps) {
|
||||
const { showToast } = useToast();
|
||||
const { subscribe } = useRealtime();
|
||||
const [loadingButtonKey, setLoadingButtonKey] = useState<string | null>(null);
|
||||
const pendingQueriesRef = useRef(new Map<string, ReturnType<typeof setTimeout>>());
|
||||
|
||||
const clearPendingQuery = useCallback((callbackQueryId: string) => {
|
||||
const timer = pendingQueriesRef.current.get(callbackQueryId);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
pendingQueriesRef.current.delete(callbackQueryId);
|
||||
}
|
||||
setLoadingButtonKey(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
pendingQueriesRef.current.forEach((timer) => clearTimeout(timer));
|
||||
pendingQueriesRef.current.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return subscribe((event) => {
|
||||
if (event.type !== 'bot_callback_answer') return;
|
||||
|
||||
const payload = event.payload ?? {};
|
||||
const callbackQueryId = typeof payload.callbackQueryId === 'string' ? payload.callbackQueryId : null;
|
||||
if (!callbackQueryId || !pendingQueriesRef.current.has(callbackQueryId)) return;
|
||||
|
||||
const eventBotId = typeof payload.botId === 'string' ? payload.botId : null;
|
||||
if (botId && eventBotId && eventBotId !== botId) return;
|
||||
|
||||
clearPendingQuery(callbackQueryId);
|
||||
|
||||
const text = typeof payload.text === 'string' ? payload.text.trim() : '';
|
||||
const showAlert = Boolean(payload.showAlert);
|
||||
const url = typeof payload.url === 'string' ? payload.url.trim() : '';
|
||||
|
||||
if (url && onOpenMiniApp) {
|
||||
onOpenMiniApp(url);
|
||||
}
|
||||
|
||||
if (text) {
|
||||
if (showAlert) {
|
||||
window.alert(text);
|
||||
} else {
|
||||
showToast(text);
|
||||
}
|
||||
}
|
||||
});
|
||||
}, [botId, clearPendingQuery, onOpenMiniApp, showToast, subscribe]);
|
||||
|
||||
async function handleCallbackClick(callbackData: string, buttonKey: string) {
|
||||
if (!token) return;
|
||||
|
||||
setLoadingButtonKey(buttonKey);
|
||||
try {
|
||||
const response = await submitBotCallback(botRef, messageId, callbackData, token);
|
||||
const callbackQueryId = response.callbackQueryId;
|
||||
if (!callbackQueryId) {
|
||||
setLoadingButtonKey(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => clearPendingQuery(callbackQueryId), CALLBACK_ANSWER_TIMEOUT_MS);
|
||||
pendingQueriesRef.current.set(callbackQueryId, timer);
|
||||
} catch (error) {
|
||||
setLoadingButtonKey(null);
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось отправить действие');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<BotInlineKeyboard
|
||||
markup={markup}
|
||||
messageId={messageId}
|
||||
loadingButtonKey={loadingButtonKey}
|
||||
onCallbackClick={handleCallbackClick}
|
||||
onOpenMiniApp={onOpenMiniApp}
|
||||
/>
|
||||
);
|
||||
}
|
||||
46
apps/frontend/components/chat/chat-delete-message-dialog.tsx
Normal file
46
apps/frontend/components/chat/chat-delete-message-dialog.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
'use client';
|
||||
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
|
||||
interface ChatDeleteMessageDialogProps {
|
||||
open: boolean;
|
||||
count: number;
|
||||
loading?: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function ChatDeleteMessageDialog({ open, count, loading, onOpenChange, onConfirm }: ChatDeleteMessageDialogProps) {
|
||||
const plural =
|
||||
count === 1 ? 'это сообщение' : count < 5 ? `${count} сообщения` : `${count} сообщений`;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="rounded-[24px] sm:max-w-[420px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Удалить сообщение?</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-[#667085]">
|
||||
{count === 1
|
||||
? 'Сообщение будет удалено для всех участников чата. Это действие нельзя отменить.'
|
||||
: `Будут удалены ${plural}. Это действие нельзя отменить.`}
|
||||
</p>
|
||||
<div className="mt-6 flex justify-end gap-2">
|
||||
<Button type="button" variant="secondary" className="rounded-xl" disabled={loading} onClick={() => onOpenChange(false)}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="rounded-xl bg-red-600 text-white hover:bg-red-700"
|
||||
disabled={loading}
|
||||
onClick={() => void onConfirm()}
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Удалить'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
28
apps/frontend/components/chat/chat-emoji-content.tsx
Normal file
28
apps/frontend/components/chat/chat-emoji-content.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
'use client';
|
||||
|
||||
import { isEmojiId } from '@/lib/emoji-catalog';
|
||||
import { emojiIdToNative, resolveNativeEmojiContent } from '@/lib/emoji-native-map';
|
||||
|
||||
export function ChatEmojiContent({ content, size = 22 }: { content?: string | null; size?: number }) {
|
||||
if (!content) return null;
|
||||
|
||||
if (isEmojiId(content)) {
|
||||
const native = emojiIdToNative(content);
|
||||
if (native) {
|
||||
return (
|
||||
<span
|
||||
className="text-[length:var(--emoji-size)] leading-none"
|
||||
style={{ ['--emoji-size' as string]: `${size + 8}px` }}
|
||||
>
|
||||
{native}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (/:([a-z0-9-]+):/.test(content)) {
|
||||
return <span className="whitespace-pre-wrap break-words">{resolveNativeEmojiContent(content)}</span>;
|
||||
}
|
||||
|
||||
return <span className="whitespace-pre-wrap break-words">{content}</span>;
|
||||
}
|
||||
69
apps/frontend/components/chat/chat-forward-dialog.tsx
Normal file
69
apps/frontend/components/chat/chat-forward-dialog.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
'use client';
|
||||
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { ChatRoomAvatarDisplay } from '@/components/family/chat-room-avatar-display';
|
||||
import type { ChatRoom } from '@/lib/api';
|
||||
import { roomDisplayLabel } from '@/lib/family-chat';
|
||||
|
||||
interface ChatForwardDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
rooms: ChatRoom[];
|
||||
viewerUserId: string;
|
||||
token: string | null;
|
||||
currentRoomId?: string;
|
||||
forwarding?: boolean;
|
||||
onSelectRoom: (roomId: string) => void;
|
||||
}
|
||||
|
||||
export function ChatForwardDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
rooms,
|
||||
viewerUserId,
|
||||
token,
|
||||
currentRoomId,
|
||||
forwarding,
|
||||
onSelectRoom
|
||||
}: ChatForwardDialogProps) {
|
||||
const targets = rooms.filter((room) => room.id !== currentRoomId && room.type !== 'BOT');
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md rounded-[24px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Переслать в чат</DialogTitle>
|
||||
</DialogHeader>
|
||||
{forwarding ? (
|
||||
<div className="flex items-center justify-center gap-2 py-8 text-sm text-[#667085]">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Пересылка...
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-[360px] space-y-1 overflow-y-auto">
|
||||
{targets.length ? (
|
||||
targets.map((room) => (
|
||||
<button
|
||||
key={room.id}
|
||||
type="button"
|
||||
className="flex w-full items-center gap-3 rounded-xl px-2 py-2 text-left transition hover:bg-[#f4f5f8]"
|
||||
onClick={() => onSelectRoom(room.id)}
|
||||
>
|
||||
<ChatRoomAvatarDisplay room={room} viewerUserId={viewerUserId} token={token} size="sm" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{roomDisplayLabel(room, viewerUserId)}</p>
|
||||
<p className="text-xs text-[#667085]">{room.members.length} участников</p>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<p className="py-6 text-center text-sm text-[#667085]">Нет доступных чатов для пересылки</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
173
apps/frontend/components/chat/chat-message-context-menu.tsx
Normal file
173
apps/frontend/components/chat/chat-message-context-menu.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
'use client';
|
||||
|
||||
import { CheckCircle2, Copy, Forward, Pencil, Reply, Trash2 } from 'lucide-react';
|
||||
import { ChatMessageReactions } from '@/components/chat/chat-message-reactions';
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger
|
||||
} from '@/components/ui/context-menu';
|
||||
import type { ChatMessage } from '@/lib/api';
|
||||
import { QUICK_REACTIONS, canDeleteMessage, canEditMessage, getMessageCopyText } from '@/lib/chat-message-utils';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ChatMessageContextMenuProps {
|
||||
message: ChatMessage;
|
||||
userId?: string;
|
||||
isE2E?: boolean;
|
||||
visibleText?: string;
|
||||
children: React.ReactNode;
|
||||
onEdit?: () => void;
|
||||
onDelete?: () => void;
|
||||
onReply?: () => void;
|
||||
onForward?: () => void;
|
||||
onSelect?: () => void;
|
||||
onToggleReaction?: (emoji: string) => void;
|
||||
onCopy?: () => void;
|
||||
}
|
||||
|
||||
export function ChatMessageContextMenu({
|
||||
message,
|
||||
userId,
|
||||
isE2E,
|
||||
visibleText,
|
||||
children,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onReply,
|
||||
onForward,
|
||||
onSelect,
|
||||
onToggleReaction,
|
||||
onCopy
|
||||
}: ChatMessageContextMenuProps) {
|
||||
const editable = canEditMessage(message, userId, isE2E);
|
||||
const deletable = canDeleteMessage(message, userId);
|
||||
const copyText = getMessageCopyText(message, visibleText);
|
||||
const disabled = message.isDeleted;
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
<ContextMenuContent className="min-w-[240px]">
|
||||
{!disabled ? (
|
||||
<>
|
||||
<div className="mb-1 flex items-center gap-1 overflow-x-auto px-1 py-1">
|
||||
{QUICK_REACTIONS.map((emoji) => (
|
||||
<button
|
||||
key={emoji}
|
||||
type="button"
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-lg transition hover:bg-[#eef1f6]"
|
||||
onClick={() => onToggleReaction?.(emoji)}
|
||||
>
|
||||
{emoji}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<ContextMenuSeparator />
|
||||
</>
|
||||
) : null}
|
||||
{onReply && !disabled ? (
|
||||
<ContextMenuItem onClick={onReply}>
|
||||
<Reply className="h-4 w-4" />
|
||||
Ответить
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
{editable ? (
|
||||
<ContextMenuItem onClick={onEdit}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
Изменить
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
{copyText ? (
|
||||
<ContextMenuItem
|
||||
onClick={() => {
|
||||
void navigator.clipboard.writeText(copyText);
|
||||
onCopy?.();
|
||||
}}
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
Копировать текст
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
{onForward && !disabled && !message.isEncrypted ? (
|
||||
<ContextMenuItem onClick={onForward}>
|
||||
<Forward className="h-4 w-4" />
|
||||
Переслать
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
{deletable ? (
|
||||
<ContextMenuItem className="text-red-600 data-[highlighted]:bg-red-50 data-[highlighted]:text-red-700" onClick={onDelete}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Удалить
|
||||
</ContextMenuItem>
|
||||
) : null}
|
||||
{onSelect && !disabled ? (
|
||||
<>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onClick={onSelect}>
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
Выделить
|
||||
</ContextMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
{!disabled && message.reactions?.length ? (
|
||||
<div className="px-2 pb-1 pt-2">
|
||||
<ChatMessageReactions reactions={message.reactions} onToggle={onToggleReaction} compact />
|
||||
</div>
|
||||
) : null}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
);
|
||||
}
|
||||
|
||||
interface SelectableMessageWrapperProps {
|
||||
selected?: boolean;
|
||||
selectionMode?: boolean;
|
||||
align?: 'left' | 'right';
|
||||
onClick?: () => void;
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function SelectableMessageWrapper({
|
||||
selected,
|
||||
selectionMode,
|
||||
align = 'left',
|
||||
onClick,
|
||||
className,
|
||||
children
|
||||
}: SelectableMessageWrapperProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative w-fit max-w-[78%] shrink-0',
|
||||
selectionMode && 'cursor-pointer',
|
||||
selectionMode && (align === 'right' ? 'mr-7' : 'ml-7'),
|
||||
className
|
||||
)}
|
||||
onClick={selectionMode ? onClick : undefined}
|
||||
>
|
||||
{selectionMode ? (
|
||||
<span
|
||||
className={cn(
|
||||
'absolute top-1/2 z-10 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full border text-[10px] shadow-sm transition',
|
||||
align === 'right' ? 'right-0 translate-x-[calc(100%+8px)]' : 'left-0 -translate-x-[calc(100%+8px)]',
|
||||
selected ? 'border-[#3390ec] bg-[#3390ec] text-white' : 'border-[#dce3ec] bg-white text-transparent'
|
||||
)}
|
||||
>
|
||||
✓
|
||||
</span>
|
||||
) : null}
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-[18px] transition',
|
||||
selected && 'ring-2 ring-[#3390ec] ring-offset-2 ring-offset-[#eef1f6]'
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
26
apps/frontend/components/chat/chat-message-edit-banner.tsx
Normal file
26
apps/frontend/components/chat/chat-message-edit-banner.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import { Pencil, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface ChatMessageEditBannerProps {
|
||||
preview?: string;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function ChatMessageEditBanner({ preview, onCancel }: ChatMessageEditBannerProps) {
|
||||
return (
|
||||
<div className="mb-2 flex items-center gap-3 rounded-xl border border-[#3390ec]/20 bg-[#eef4ff] px-3 py-2 animate-in fade-in slide-in-from-bottom-1 duration-200">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[#3390ec]/15 text-[#3390ec]">
|
||||
<Pencil className="h-4 w-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-[#3390ec]">Редактирование сообщения</p>
|
||||
{preview ? <p className="truncate text-xs text-[#667085]">{preview}</p> : null}
|
||||
</div>
|
||||
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0 rounded-lg" aria-label="Отменить редактирование" onClick={onCancel}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
35
apps/frontend/components/chat/chat-message-reactions.tsx
Normal file
35
apps/frontend/components/chat/chat-message-reactions.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
'use client';
|
||||
|
||||
import type { ChatMessageReaction } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ChatMessageReactionsProps {
|
||||
reactions?: ChatMessageReaction[];
|
||||
onToggle?: (emoji: string) => void;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export function ChatMessageReactions({ reactions, onToggle, compact }: ChatMessageReactionsProps) {
|
||||
if (!reactions?.length) return null;
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-wrap gap-1', compact ? 'mt-1' : 'mt-1.5')}>
|
||||
{reactions.map((reaction) => (
|
||||
<button
|
||||
key={reaction.emoji}
|
||||
type="button"
|
||||
onClick={() => onToggle?.(reaction.emoji)}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs transition',
|
||||
reaction.reactedByMe
|
||||
? 'border-[#3390ec]/40 bg-[#3390ec]/15 text-[#1f2430]'
|
||||
: 'border-[#dce3ec] bg-white/80 text-[#667085] hover:bg-white'
|
||||
)}
|
||||
>
|
||||
<span>{reaction.emoji}</span>
|
||||
<span>{reaction.count}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
apps/frontend/components/chat/chat-selection-toolbar.tsx
Normal file
43
apps/frontend/components/chat/chat-selection-toolbar.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { Copy, Forward, Loader2, Trash2, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface ChatSelectionToolbarProps {
|
||||
count: number;
|
||||
deleting?: boolean;
|
||||
onCancel: () => void;
|
||||
onCopy: () => void;
|
||||
onForward: () => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
export function ChatSelectionToolbar({ count, deleting, onCancel, onCopy, onForward, onDelete }: ChatSelectionToolbarProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 border-t border-[#dce3ec] bg-white px-4 py-3 shadow-[0_-8px_24px_rgba(31,36,48,0.08)] animate-in fade-in slide-in-from-bottom-2 duration-200">
|
||||
<Button type="button" variant="ghost" size="icon" className="h-9 w-9 shrink-0 rounded-xl" onClick={onCancel}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
<p className="min-w-0 flex-1 text-sm font-medium">{count} выбрано</p>
|
||||
<Button type="button" variant="secondary" size="sm" className="rounded-xl" onClick={onCopy}>
|
||||
<Copy className="mr-1 h-4 w-4" />
|
||||
Копировать
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" size="sm" className="rounded-xl" onClick={onForward}>
|
||||
<Forward className="mr-1 h-4 w-4" />
|
||||
Переслать
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="rounded-xl text-red-600 hover:text-red-700"
|
||||
disabled={deleting}
|
||||
onClick={onDelete}
|
||||
>
|
||||
{deleting ? <Loader2 className="mr-1 h-4 w-4 animate-spin" /> : <Trash2 className="mr-1 h-4 w-4" />}
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
84
apps/frontend/components/chat/emoji-picker.tsx
Normal file
84
apps/frontend/components/chat/emoji-picker.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { Search } from 'lucide-react';
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
import { EMOJI_CATEGORIES, EMOJI_DEFINITIONS, searchEmojis, type EmojiCategoryId } from '@/lib/emoji-catalog';
|
||||
|
||||
import { emojiIdToNative } from '@/lib/emoji-native-map';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
|
||||
|
||||
interface EmojiPickerProps {
|
||||
|
||||
onSelect: (nativeEmoji: string) => void;
|
||||
|
||||
className?: string;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function EmojiPicker({ onSelect, className }: EmojiPickerProps) {
|
||||
|
||||
const [category, setCategory] = useState<EmojiCategoryId>('smileys');
|
||||
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
|
||||
|
||||
const items = useMemo(() => {
|
||||
|
||||
const filtered = searchEmojis(query);
|
||||
|
||||
if (query.trim()) return filtered;
|
||||
|
||||
return filtered.filter((item) => item.category === category);
|
||||
|
||||
}, [category, query]);
|
||||
|
||||
|
||||
|
||||
return (
|
||||
|
||||
<div className={cn('rounded-2xl border border-[#dce3ec] bg-white shadow-lg', className)}>
|
||||
|
||||
<div className="border-b border-[#eceef4] p-2">
|
||||
|
||||
<div className="relative">
|
||||
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#a8adbc]" />
|
||||
|
||||
<Input
|
||||
|
||||
value={query}
|
||||
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
|
||||
placeholder="Поиск смайликов"
|
||||
|
||||
className="rounded-xl pl-9"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{!query.trim() ? (
|
||||
|
||||
<div className="flex gap-1 overflow-x-auto border-b border-[#eceef4] px-2 py-2">
|
||||
|
||||
{EMOJI_CATEGORIES.map((item) => {
|
||||
|
||||
const native = emojiIdToNative(item.icon) ?? '✨';
|
||||
|
||||
return (
|
||||
|
||||
25
apps/frontend/components/chat/emoji-sprite-provider.tsx
Normal file
25
apps/frontend/components/chat/emoji-sprite-provider.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
|
||||
let spriteInjected = false;
|
||||
|
||||
export function EmojiSpriteProvider() {
|
||||
useEffect(() => {
|
||||
if (spriteInjected || typeof document === 'undefined') return;
|
||||
fetch('/emojis/lendry-emojis.svg')
|
||||
.then((response) => response.text())
|
||||
.then((markup) => {
|
||||
if (spriteInjected) return;
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = markup;
|
||||
container.style.display = 'none';
|
||||
container.setAttribute('aria-hidden', 'true');
|
||||
document.body.appendChild(container);
|
||||
spriteInjected = true;
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
27
apps/frontend/components/chat/emoji-sprite.tsx
Normal file
27
apps/frontend/components/chat/emoji-sprite.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export const EMOJI_SPRITE_PATH = '/emojis/lendry-emojis.svg';
|
||||
|
||||
interface EmojiSpriteProps {
|
||||
id: string;
|
||||
size?: number;
|
||||
className?: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export function EmojiSprite({ id, size = 24, className, title }: EmojiSpriteProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 36 36"
|
||||
className={cn('inline-block shrink-0 align-middle', className)}
|
||||
role="img"
|
||||
aria-label={title}
|
||||
>
|
||||
<use href={`${EMOJI_SPRITE_PATH}#${id}`} xlinkHref={`${EMOJI_SPRITE_PATH}#${id}`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
105
apps/frontend/components/chat/inline-editable-title.tsx
Normal file
105
apps/frontend/components/chat/inline-editable-title.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Loader2, Pencil } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface InlineEditableTitleProps {
|
||||
value: string;
|
||||
onSave: (nextValue: string) => Promise<void> | void;
|
||||
className?: string;
|
||||
inputClassName?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function InlineEditableTitle({
|
||||
value,
|
||||
onSave,
|
||||
className,
|
||||
inputClassName,
|
||||
disabled = false
|
||||
}: InlineEditableTitleProps) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(value);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editing) setDraft(value);
|
||||
}, [editing, value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editing) {
|
||||
inputRef.current?.focus();
|
||||
inputRef.current?.select();
|
||||
}
|
||||
}, [editing]);
|
||||
|
||||
async function commit() {
|
||||
const trimmed = draft.trim();
|
||||
if (!trimmed || trimmed === value) {
|
||||
setDraft(value);
|
||||
setEditing(false);
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSave(trimmed);
|
||||
setEditing(false);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
return (
|
||||
<div className={cn('relative min-w-0', className)}>
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={draft}
|
||||
disabled={saving}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onBlur={() => void commit()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void commit();
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
setDraft(value);
|
||||
setEditing(false);
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
'w-full border-0 bg-transparent p-0 text-base font-semibold leading-tight text-[#1f2430] outline-none ring-0',
|
||||
inputClassName
|
||||
)}
|
||||
/>
|
||||
{saving ? <Loader2 className="absolute -right-5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 animate-spin text-[#667085]" /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('group/title flex min-w-0 items-center gap-1.5', className)}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => !disabled && setEditing(true)}
|
||||
className="min-w-0 truncate text-left text-base font-semibold leading-tight text-[#1f2430] transition hover:text-[#3390ec] disabled:cursor-default disabled:hover:text-[#1f2430]"
|
||||
>
|
||||
{value}
|
||||
</button>
|
||||
{!disabled ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Изменить название"
|
||||
onClick={() => setEditing(true)}
|
||||
className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[#667085] opacity-0 transition hover:bg-[#f4f5f8] hover:text-[#3390ec] group-hover/title:opacity-100"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
45
apps/frontend/components/chat/replied-message-preview.tsx
Normal file
45
apps/frontend/components/chat/replied-message-preview.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface RepliedMessagePreviewProps {
|
||||
senderName: string;
|
||||
preview: string;
|
||||
accentClassName?: string;
|
||||
onClick?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RepliedMessagePreview({
|
||||
senderName,
|
||||
preview,
|
||||
accentClassName = 'bg-[#3390ec]',
|
||||
onClick,
|
||||
className
|
||||
}: RepliedMessagePreviewProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'mb-2 flex w-full items-stretch gap-2 rounded-xl bg-black/[0.04] px-2 py-1.5 text-left transition hover:bg-black/[0.07]',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className={cn('w-0.5 shrink-0 rounded-full', accentClassName)} aria-hidden />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-xs font-semibold text-[#3390ec]">{senderName}</span>
|
||||
<span className="block truncate text-xs text-[#667085]">{preview || 'Сообщение'}</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function scrollToChatMessage(messageId: string) {
|
||||
const element = document.getElementById(`msg-${messageId}`);
|
||||
if (!element) return false;
|
||||
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
element.classList.add('blink-highlight');
|
||||
window.setTimeout(() => element.classList.remove('blink-highlight'), 2000);
|
||||
return true;
|
||||
}
|
||||
48
apps/frontend/components/chat/typing-indicator.tsx
Normal file
48
apps/frontend/components/chat/typing-indicator.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface TypingIndicatorProps {
|
||||
roomType?: string;
|
||||
typers: Array<{ userId: string; userName: string }>;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function isGroupRoomType(type?: string) {
|
||||
return type === 'GROUP' || type === 'GENERAL';
|
||||
}
|
||||
|
||||
export function TypingIndicator({ roomType, typers, className }: TypingIndicatorProps) {
|
||||
if (!typers.length) return null;
|
||||
|
||||
const group = isGroupRoomType(roomType);
|
||||
let label = 'печатает';
|
||||
|
||||
if (group) {
|
||||
if (typers.length === 1) {
|
||||
label = `${typers[0]!.userName} печатает`;
|
||||
} else if (typers.length === 2) {
|
||||
label = `${typers[0]!.userName} и ${typers[1]!.userName} печатают`;
|
||||
} else {
|
||||
label = `${typers.length} участника печатают`;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-2 px-4 py-1 text-xs text-[#667085] transition-all duration-300 animate-in fade-in slide-in-from-bottom-1',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="inline-flex gap-0.5">
|
||||
<span className="h-1.5 w-1.5 animate-bounce rounded-full bg-[#3390ec]/70 [animation-delay:0ms]" />
|
||||
<span className="h-1.5 w-1.5 animate-bounce rounded-full bg-[#3390ec]/70 [animation-delay:120ms]" />
|
||||
<span className="h-1.5 w-1.5 animate-bounce rounded-full bg-[#3390ec]/70 [animation-delay:240ms]" />
|
||||
</span>
|
||||
</span>
|
||||
<span>{group ? label : 'печатает…'}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
83
apps/frontend/components/family/chat-room-avatar-display.tsx
Normal file
83
apps/frontend/components/family/chat-room-avatar-display.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
'use client';
|
||||
|
||||
import { Bot } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { UserAvatar } from '@/components/id/user-avatar';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { ChatRoom, apiFetch } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ChatRoomAvatarDisplayProps {
|
||||
room: ChatRoom;
|
||||
viewerUserId: string;
|
||||
token: string | null;
|
||||
className?: string;
|
||||
size?: 'sm' | 'md';
|
||||
}
|
||||
|
||||
function sizeClass(size: 'sm' | 'md') {
|
||||
return size === 'sm' ? 'h-9 w-9 text-xs' : 'h-11 w-11 text-sm';
|
||||
}
|
||||
|
||||
export function ChatRoomAvatarDisplay({ room, viewerUserId, token, className, size = 'md' }: ChatRoomAvatarDisplayProps) {
|
||||
const [roomAvatarUrl, setRoomAvatarUrl] = useState<string | null>(null);
|
||||
const peerMember = useMemo(
|
||||
() =>
|
||||
room.type === 'DIRECT' || room.type === 'E2E' || room.type === 'BOT'
|
||||
? room.members.find((member) => member.userId !== viewerUserId)
|
||||
: undefined,
|
||||
[room.members, room.type, viewerUserId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !room.hasAvatar || room.type === 'DIRECT' || room.type === 'E2E' || room.type === 'BOT') {
|
||||
setRoomAvatarUrl(null);
|
||||
return;
|
||||
}
|
||||
apiFetch<{ accessUrl: string }>(`/media/chat/${room.id}/avatar/url`, {}, token)
|
||||
.then((response) => setRoomAvatarUrl(response.accessUrl))
|
||||
.catch(() => setRoomAvatarUrl(null));
|
||||
}, [room.hasAvatar, room.id, room.type, token]);
|
||||
|
||||
if (peerMember && (room.type === 'DIRECT' || room.type === 'E2E')) {
|
||||
return (
|
||||
<UserAvatar
|
||||
userId={peerMember.userId}
|
||||
displayName={peerMember.displayName}
|
||||
hasAvatar={peerMember.hasAvatar}
|
||||
token={token}
|
||||
isVerified={peerMember.isVerified}
|
||||
verificationIcon={peerMember.verificationIcon}
|
||||
className={cn(sizeClass(size), className)}
|
||||
badgeSize="xs"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (room.type === 'BOT') {
|
||||
return (
|
||||
<Avatar className={cn(sizeClass(size), className)}>
|
||||
<AvatarFallback className="bg-[#3390ec]/15 text-[#3390ec]">
|
||||
<Bot className={size === 'sm' ? 'h-4 w-4' : 'h-5 w-5'} />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
if (room.hasAvatar && roomAvatarUrl) {
|
||||
return (
|
||||
<Avatar className={cn(sizeClass(size), className)}>
|
||||
<AvatarImage src={roomAvatarUrl} alt={room.name} />
|
||||
<AvatarFallback>{room.name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Avatar className={cn(sizeClass(size), className)}>
|
||||
<AvatarFallback className={room.type === 'GENERAL' ? 'bg-[#3390ec]/15 text-[#3390ec]' : undefined}>
|
||||
{room.type === 'GENERAL' ? 'В' : room.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
309
apps/frontend/components/family/family-bot-chat.tsx
Normal file
309
apps/frontend/components/family/family-bot-chat.tsx
Normal file
@@ -0,0 +1,309 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { LayoutGrid, Loader2, Send, X } from 'lucide-react';
|
||||
import { BotMessageKeyboard } from '@/components/chat/bot-message-keyboard';
|
||||
import { BotChatMessageContextMenu } from '@/components/chat/bot-chat-message-context-menu';
|
||||
import { useRealtime } from '@/components/notifications/realtime-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
BotChatMessage,
|
||||
BotChatMeta,
|
||||
fetchBotChatMessages,
|
||||
sendBotMessage
|
||||
} from '@/lib/api';
|
||||
import { extractMessageReplyMarkup, serializeInlineKeyboardMarkup } from '@/lib/bot-reply-markup';
|
||||
import { resolveComposerMenuButton, type ComposerMenuButton } from '@/lib/bot-menu-button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
|
||||
function formatMessageTime(value: string) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(value));
|
||||
}
|
||||
|
||||
function resolveBotRef(botRef: string, payloadBotUsername?: unknown) {
|
||||
if (typeof payloadBotUsername === 'string' && payloadBotUsername.trim()) {
|
||||
return payloadBotUsername.trim();
|
||||
}
|
||||
return botRef;
|
||||
}
|
||||
|
||||
function markupJsonFromPayload(payload: Record<string, unknown>) {
|
||||
const rows = extractMessageReplyMarkup({
|
||||
replyMarkup: payload.replyMarkup,
|
||||
telegramReplyMarkup: payload.telegramReplyMarkup,
|
||||
reply_markup: payload.reply_markup
|
||||
});
|
||||
return serializeInlineKeyboardMarkup(rows);
|
||||
}
|
||||
|
||||
interface FamilyBotChatProps {
|
||||
botRef: string;
|
||||
botName: string;
|
||||
token: string | null;
|
||||
className?: string;
|
||||
inputPlaceholder?: string;
|
||||
onOpenMiniApp?: (url: string) => void;
|
||||
onBotMetaChange?: (meta: BotChatMeta) => void;
|
||||
}
|
||||
|
||||
export function FamilyBotChat({
|
||||
botRef,
|
||||
botName,
|
||||
token,
|
||||
className,
|
||||
inputPlaceholder = 'Сообщение боту',
|
||||
onOpenMiniApp,
|
||||
onBotMetaChange
|
||||
}: FamilyBotChatProps) {
|
||||
const [messages, setMessages] = useState<BotChatMessage[]>([]);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [composerMenuButton, setComposerMenuButton] = useState<ComposerMenuButton | null>(null);
|
||||
const [internalMiniAppUrl, setInternalMiniAppUrl] = useState<string | null>(null);
|
||||
const [botMeta, setBotMeta] = useState<BotChatMeta | null>(null);
|
||||
const { subscribe } = useRealtime();
|
||||
const { showToast } = useToast();
|
||||
|
||||
const openMiniApp = useCallback(
|
||||
(url: string) => {
|
||||
if (onOpenMiniApp) {
|
||||
onOpenMiniApp(url);
|
||||
return;
|
||||
}
|
||||
setInternalMiniAppUrl(url);
|
||||
},
|
||||
[onOpenMiniApp]
|
||||
);
|
||||
|
||||
const loadMessages = useCallback(async () => {
|
||||
if (!token) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetchBotChatMessages(botRef, token);
|
||||
setMessages(response.messages ?? []);
|
||||
const menuButton = resolveComposerMenuButton({
|
||||
composerMenuButtonJson: response.composerMenuButtonJson,
|
||||
composerWebAppUrl: response.composerWebAppUrl
|
||||
});
|
||||
setComposerMenuButton(menuButton);
|
||||
const meta: BotChatMeta = {
|
||||
botId: response.botId,
|
||||
botOwnerId: response.botOwnerId,
|
||||
botUsername: response.botUsername,
|
||||
botDisplayName: response.botDisplayName,
|
||||
composerWebAppUrl: menuButton?.web_app.url ?? (response.composerWebAppUrl?.trim() || null),
|
||||
composerMenuButtonJson: response.composerMenuButtonJson ?? (menuButton ? JSON.stringify(menuButton) : null),
|
||||
manageWebAppUrl: response.manageWebAppUrl
|
||||
};
|
||||
setBotMeta(meta);
|
||||
onBotMetaChange?.(meta);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [botRef, onBotMetaChange, token]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadMessages();
|
||||
}, [loadMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
return subscribe((event) => {
|
||||
const payload = event.payload ?? {};
|
||||
const eventBotRef = resolveBotRef(botRef, payload.botUsername);
|
||||
if (eventBotRef !== botRef && eventBotRef.replace(/_bot$/i, '') !== botRef.replace(/_bot$/i, '')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'bot_message') {
|
||||
const messageId = Number(payload.messageId);
|
||||
if (!Number.isFinite(messageId)) {
|
||||
void loadMessages();
|
||||
return;
|
||||
}
|
||||
|
||||
const replyMarkupJson = markupJsonFromPayload(payload);
|
||||
const outbound: BotChatMessage = {
|
||||
id: `out-ws-${messageId}`,
|
||||
direction: 'out',
|
||||
text: typeof payload.text === 'string' ? payload.text : '',
|
||||
messageType: typeof payload.messageType === 'string' ? payload.messageType : 'text',
|
||||
messageId,
|
||||
createdAt: new Date().toISOString(),
|
||||
replyMarkupJson
|
||||
};
|
||||
|
||||
setMessages((current) => {
|
||||
const withoutDuplicate = current.filter((item) => item.messageId !== messageId || item.direction !== 'out');
|
||||
return [...withoutDuplicate, outbound].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'bot_menu_button_updated') {
|
||||
const menuButton = resolveComposerMenuButton({
|
||||
composerMenuButtonJson:
|
||||
typeof payload.composerMenuButtonJson === 'string' ? payload.composerMenuButtonJson : null,
|
||||
composerWebAppUrl: typeof payload.composerWebAppUrl === 'string' ? payload.composerWebAppUrl : null
|
||||
});
|
||||
setComposerMenuButton(menuButton);
|
||||
setBotMeta((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
composerWebAppUrl: menuButton?.web_app.url ?? null,
|
||||
composerMenuButtonJson: menuButton ? JSON.stringify(menuButton) : null
|
||||
}
|
||||
: current
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'bot_message_edited') {
|
||||
const messageId = Number(payload.messageId);
|
||||
if (!Number.isFinite(messageId)) {
|
||||
void loadMessages();
|
||||
return;
|
||||
}
|
||||
|
||||
const replyMarkupJson = markupJsonFromPayload(payload);
|
||||
setMessages((current) =>
|
||||
current.map((item) =>
|
||||
item.messageId === messageId && item.direction === 'out'
|
||||
? {
|
||||
...item,
|
||||
text: typeof payload.text === 'string' ? payload.text : item.text,
|
||||
replyMarkupJson: replyMarkupJson ?? item.replyMarkupJson ?? null
|
||||
}
|
||||
: item
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
}, [botRef, loadMessages, subscribe]);
|
||||
|
||||
async function handleSend() {
|
||||
if (!token || !draft.trim() || sending) return;
|
||||
const text = draft.trim();
|
||||
setSending(true);
|
||||
setDraft('');
|
||||
setMessages((current) => [
|
||||
...current,
|
||||
{
|
||||
id: `in-local-${Date.now()}`,
|
||||
direction: 'in',
|
||||
text,
|
||||
messageType: 'text',
|
||||
messageId: 0,
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
]);
|
||||
try {
|
||||
await sendBotMessage(botRef, text, token);
|
||||
await loadMessages();
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('flex min-h-0 flex-1 flex-col', className)}>
|
||||
<div className="flex-1 space-y-2 overflow-y-auto px-4 py-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center gap-2 py-8 text-sm text-[#667085]">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Загрузка...
|
||||
</div>
|
||||
) : messages.length ? (
|
||||
messages.map((message) => {
|
||||
const mine = message.direction === 'in';
|
||||
const hasKeyboard = Boolean(message.replyMarkupJson?.trim());
|
||||
return (
|
||||
<div key={message.id} className={cn('flex', mine ? 'justify-end' : 'justify-start')}>
|
||||
<BotChatMessageContextMenu text={message.text} onCopy={() => showToast('Текст скопирован')}>
|
||||
<div className={cn('max-w-[78%] rounded-[18px] px-3 py-2 shadow-sm', mine ? 'rounded-br-md bg-[#effdde]' : 'rounded-bl-md bg-white')}>
|
||||
{!mine ? <p className="mb-0.5 text-[11px] font-semibold text-[#3390ec]">{botName}</p> : null}
|
||||
<p className="whitespace-pre-wrap text-sm">{message.text || '…'}</p>
|
||||
{!mine && hasKeyboard && message.messageId > 0 ? (
|
||||
<BotMessageKeyboard
|
||||
botRef={botRef}
|
||||
botId={botMeta?.botId}
|
||||
messageId={message.messageId}
|
||||
markup={message.replyMarkupJson}
|
||||
token={token}
|
||||
onOpenMiniApp={openMiniApp}
|
||||
/>
|
||||
) : null}
|
||||
<p className="mt-1 text-[10px] text-[#a8adbc]">{formatMessageTime(message.createdAt)}</p>
|
||||
</div>
|
||||
</BotChatMessageContextMenu>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<p className="py-8 text-center text-sm text-[#667085]">Напишите /help, чтобы начать</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 border-t border-[#dce3ec] bg-white px-4 py-3">
|
||||
{composerMenuButton ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-10 shrink-0 rounded-full border border-[#3390ec]/20 bg-[#3390ec]/10 px-3 text-[#3390ec] transition hover:bg-[#3390ec]/15"
|
||||
aria-label={composerMenuButton.text}
|
||||
title={composerMenuButton.text}
|
||||
onClick={() => openMiniApp(composerMenuButton.web_app.url)}
|
||||
>
|
||||
<LayoutGrid className="mr-1.5 h-4 w-4" />
|
||||
<span className="max-w-[96px] truncate text-xs font-medium">{composerMenuButton.text}</span>
|
||||
</Button>
|
||||
) : null}
|
||||
<Input
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
placeholder={inputPlaceholder}
|
||||
className="rounded-xl"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
void handleSend();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button className="h-10 w-10 shrink-0 rounded-full p-0" disabled={sending || !draft.trim()} onClick={() => void handleSend()}>
|
||||
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<BotMiniAppSheet
|
||||
url={internalMiniAppUrl}
|
||||
title={composerMenuButton?.text ?? 'Mini App'}
|
||||
onClose={() => setInternalMiniAppUrl(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface BotMiniAppSheetProps {
|
||||
url: string | null;
|
||||
title?: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function BotMiniAppSheet({ url, title = 'Mini App', onClose }: BotMiniAppSheetProps) {
|
||||
if (!url) return null;
|
||||
return (
|
||||
<div className="fixed inset-0 z-[70] flex items-end justify-center bg-black/40 p-4 sm:items-center">
|
||||
<div className="flex h-[min(88vh,720px)] w-full max-w-[520px] flex-col overflow-hidden rounded-[24px] bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-[#eceef4] px-4 py-3">
|
||||
<p className="font-semibold">{title}</p>
|
||||
<Button type="button" variant="ghost" size="icon" className="h-8 w-8" aria-label="Закрыть" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<iframe src={url} title={title} className="min-h-0 flex-1 border-0" allow="clipboard-read; clipboard-write" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,22 +1,34 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Bot, Loader2 } from 'lucide-react';
|
||||
import { AvatarWithPresence } from '@/components/family/avatar-with-presence';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { FamilyInviteCandidate, getApiErrorMessage, searchFamilyInviteUsers, sendFamilyInvite } from '@/lib/api';
|
||||
import {
|
||||
FamilyGroup,
|
||||
FamilyInviteCandidate,
|
||||
ManagedBot,
|
||||
addBotFatherToFamily,
|
||||
addBotToFamily,
|
||||
fetchMyBots,
|
||||
getApiErrorMessage,
|
||||
searchFamilyInviteUsers,
|
||||
sendFamilyInvite
|
||||
} from '@/lib/api';
|
||||
|
||||
export function FamilyInviteDialog({
|
||||
groupId,
|
||||
group,
|
||||
open,
|
||||
onOpenChange,
|
||||
onInvited
|
||||
}: {
|
||||
groupId: string;
|
||||
group?: FamilyGroup | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onInvited?: () => void;
|
||||
@@ -28,14 +40,39 @@ export function FamilyInviteDialog({
|
||||
const [inviteSearching, setInviteSearching] = useState(false);
|
||||
const [selectedInviteUser, setSelectedInviteUser] = useState<FamilyInviteCandidate | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [myBots, setMyBots] = useState<ManagedBot[]>([]);
|
||||
const [myBotsLoading, setMyBotsLoading] = useState(false);
|
||||
const [addingBotId, setAddingBotId] = useState<string | null>(null);
|
||||
|
||||
const familyBotUsernames = useMemo(
|
||||
() => new Set((group?.members ?? []).map((member) => member.botUsername).filter(Boolean) as string[]),
|
||||
[group?.members]
|
||||
);
|
||||
|
||||
const availableMyBots = useMemo(
|
||||
() => myBots.filter((bot) => !familyBotUsernames.has(bot.username)),
|
||||
[familyBotUsernames, myBots]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setInviteQuery('');
|
||||
setInviteResults([]);
|
||||
setSelectedInviteUser(null);
|
||||
setMyBots([]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token) return;
|
||||
setMyBotsLoading(true);
|
||||
fetchMyBots(token)
|
||||
.then((response) => setMyBots(response.bots ?? []))
|
||||
.catch(() => setMyBots([]))
|
||||
.finally(() => setMyBotsLoading(false));
|
||||
}, [open, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (!token || inviteQuery.trim().length < 2) {
|
||||
setInviteResults([]);
|
||||
return;
|
||||
@@ -52,21 +89,71 @@ export function FamilyInviteDialog({
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [groupId, inviteQuery, open, token]);
|
||||
|
||||
async function addBotById(botId: string, displayName: string) {
|
||||
if (!token) return;
|
||||
setAddingBotId(botId);
|
||||
try {
|
||||
await addBotToFamily(groupId, botId, token);
|
||||
showToast(`${displayName} добавлен в семью`);
|
||||
onOpenChange(false);
|
||||
onInvited?.();
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось добавить бота') ?? 'Ошибка');
|
||||
} finally {
|
||||
setAddingBotId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitInvite() {
|
||||
if (!token || !selectedInviteUser) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await sendFamilyInvite(groupId, { inviteeUserId: selectedInviteUser.id }, token);
|
||||
showToast('Приглашение отправлено');
|
||||
if (selectedInviteUser.isBot) {
|
||||
if (selectedInviteUser.botId) {
|
||||
await addBotToFamily(groupId, selectedInviteUser.botId, token);
|
||||
showToast(`${selectedInviteUser.displayName} добавлен в семью`);
|
||||
} else {
|
||||
await addBotFatherToFamily(groupId, token);
|
||||
showToast('BotFather добавлен в семью');
|
||||
}
|
||||
} else {
|
||||
await sendFamilyInvite(groupId, { inviteeUserId: selectedInviteUser.id }, token);
|
||||
showToast('Приглашение отправлено');
|
||||
}
|
||||
onOpenChange(false);
|
||||
onInvited?.();
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось отправить приглашение') ?? 'Ошибка');
|
||||
showToast(
|
||||
getApiErrorMessage(
|
||||
error,
|
||||
selectedInviteUser.isBot ? 'Не удалось добавить бота' : 'Не удалось отправить приглашение'
|
||||
) ?? 'Ошибка'
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function botCandidateLabel(candidate: FamilyInviteCandidate) {
|
||||
if (!candidate.isBot) {
|
||||
return candidate.email ?? candidate.phone ?? candidate.username ?? 'Без контактов';
|
||||
}
|
||||
const handle = `@${candidate.botUsername ?? 'bot'}`;
|
||||
if (candidate.ownerDisplayName) {
|
||||
return `${handle} · владелец: ${candidate.ownerDisplayName}`;
|
||||
}
|
||||
if (candidate.botUsername === 'BotFather_bot') {
|
||||
return `${handle} — создавайте ботов через чат`;
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
function submitButtonLabel() {
|
||||
if (!selectedInviteUser?.isBot) return 'Отправить приглашение';
|
||||
if (selectedInviteUser.botId) return 'Добавить бота';
|
||||
return 'Добавить BotFather';
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[420px]">
|
||||
@@ -75,33 +162,70 @@ export function FamilyInviteDialog({
|
||||
</DialogHeader>
|
||||
{selectedInviteUser ? (
|
||||
<div className="rounded-2xl bg-[#f4f5f8] px-4 py-3">
|
||||
<p className="font-medium">{selectedInviteUser.displayName}</p>
|
||||
<p className="text-sm text-[#667085]">
|
||||
{selectedInviteUser.email ?? selectedInviteUser.phone ?? selectedInviteUser.username ?? 'Контакт не указан'}
|
||||
<p className="font-medium">
|
||||
{selectedInviteUser.displayName}
|
||||
{selectedInviteUser.isBot ? ' 🤖' : ''}
|
||||
</p>
|
||||
<p className="text-sm text-[#667085]">{botCandidateLabel(selectedInviteUser)}</p>
|
||||
<button type="button" className="mt-2 text-sm text-[#667085] underline" onClick={() => setSelectedInviteUser(null)}>
|
||||
Выбрать другого пользователя
|
||||
Выбрать другого
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Input
|
||||
placeholder="ФИО, почта, телефон или логин"
|
||||
placeholder="ФИО, почта, телефон, логин или @бот"
|
||||
value={inviteQuery}
|
||||
onChange={(event) => setInviteQuery(event.target.value)}
|
||||
/>
|
||||
{inviteQuery.trim().length < 2 ? (
|
||||
<div className="mt-3">
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-[#667085]">Мои боты</p>
|
||||
<div className="max-h-40 overflow-y-auto rounded-2xl border border-[#eceef4]">
|
||||
{myBotsLoading ? (
|
||||
<div className="flex items-center gap-2 px-4 py-3 text-sm text-[#667085]">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Загрузка ботов...
|
||||
</div>
|
||||
) : availableMyBots.length ? (
|
||||
availableMyBots.map((bot) => (
|
||||
<button
|
||||
key={bot.id}
|
||||
type="button"
|
||||
disabled={addingBotId === bot.id}
|
||||
className="flex w-full items-center gap-3 border-b border-[#eceef4] px-4 py-3 text-left last:border-b-0 hover:bg-[#fafbfd] disabled:opacity-60"
|
||||
onClick={() => void addBotById(bot.id, bot.name)}
|
||||
>
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-full bg-[#eef4ff] text-[#3390ec]">
|
||||
{addingBotId === bot.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bot className="h-4 w-4" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium">{bot.name}</p>
|
||||
<p className="truncate text-sm text-[#667085]">@{bot.username}</p>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<p className="px-4 py-3 text-sm text-[#667085]">
|
||||
{myBots.length ? 'Все ваши боты уже в семье' : 'У вас пока нет ботов. Создайте через BotFather.'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-[#667085]">Или найдите пользователя / бота другого владельца через поиск выше</p>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="mt-2 max-h-56 overflow-y-auto rounded-2xl border border-[#eceef4]">
|
||||
{inviteSearching ? (
|
||||
<div className="flex items-center gap-2 px-4 py-3 text-sm text-[#667085]">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Ищем пользователей...
|
||||
Ищем...
|
||||
</div>
|
||||
) : inviteQuery.trim().length < 2 ? (
|
||||
<p className="px-4 py-3 text-sm text-[#667085]">Введите минимум 2 символа для поиска</p>
|
||||
<p className="px-4 py-3 text-sm text-[#667085]">Введите минимум 2 символа для поиска пользователей и ботов</p>
|
||||
) : inviteResults.length ? (
|
||||
inviteResults.map((candidate) => (
|
||||
<button
|
||||
key={candidate.id}
|
||||
key={`${candidate.id}-${candidate.botId ?? 'user'}`}
|
||||
type="button"
|
||||
className="flex w-full items-center gap-3 border-b border-[#eceef4] px-4 py-3 text-left last:border-b-0 hover:bg-[#fafbfd]"
|
||||
onClick={() => {
|
||||
@@ -109,31 +233,38 @@ export function FamilyInviteDialog({
|
||||
setInviteResults([]);
|
||||
}}
|
||||
>
|
||||
<AvatarWithPresence
|
||||
userId={candidate.id}
|
||||
displayName={candidate.displayName}
|
||||
hasAvatar={candidate.hasAvatar}
|
||||
token={token}
|
||||
isVerified={candidate.isVerified}
|
||||
verificationIcon={candidate.verificationIcon}
|
||||
className="h-9 w-9"
|
||||
/>
|
||||
{candidate.isBot ? (
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-full bg-[#eef4ff] text-[#3390ec]">
|
||||
<Bot className="h-4 w-4" />
|
||||
</div>
|
||||
) : (
|
||||
<AvatarWithPresence
|
||||
userId={candidate.id}
|
||||
displayName={candidate.displayName}
|
||||
hasAvatar={candidate.hasAvatar}
|
||||
token={token}
|
||||
isVerified={candidate.isVerified}
|
||||
verificationIcon={candidate.verificationIcon}
|
||||
className="h-9 w-9"
|
||||
/>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium">{candidate.displayName}</p>
|
||||
<p className="truncate text-sm text-[#667085]">
|
||||
{candidate.email ?? candidate.phone ?? candidate.username ?? 'Без контактов'}
|
||||
<p className="truncate font-medium">
|
||||
{candidate.displayName}
|
||||
{candidate.isBot ? ' 🤖' : ''}
|
||||
</p>
|
||||
<p className="truncate text-sm text-[#667085]">{botCandidateLabel(candidate)}</p>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<p className="px-4 py-3 text-sm text-[#667085]">Пользователи не найдены</p>
|
||||
<p className="px-4 py-3 text-sm text-[#667085]">Ничего не найдено</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<Button className="mt-4 w-full rounded-xl" disabled={!selectedInviteUser || submitting} onClick={() => void submitInvite()}>
|
||||
{submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Отправить приглашение'}
|
||||
{submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : submitButtonLabel()}
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -7,11 +7,11 @@ const SELECTED_FAMILY_STORAGE_KEY = 'id-selected-family-group-id';
|
||||
type FamilyOverlayContextValue = {
|
||||
openMiniChat: () => void;
|
||||
openChatRoom: (roomId: string) => void;
|
||||
openChatWithMember: (memberUserId: string, memberName: string) => void;
|
||||
openChatWithMember: (memberUserId: string, memberName: string, options?: { isBot?: boolean; botUsername?: string }) => void;
|
||||
closeMiniChat: () => void;
|
||||
miniChatOpen: boolean;
|
||||
pendingRoomId: string | null;
|
||||
pendingMember: { userId: string; name: string } | null;
|
||||
pendingMember: { userId: string; name: string; isBot?: boolean; botUsername?: string } | null;
|
||||
clearPending: () => void;
|
||||
selectedGroupId: string | null;
|
||||
setSelectedGroupId: (groupId: string | null) => void;
|
||||
@@ -22,9 +22,9 @@ const FamilyOverlayContext = createContext<FamilyOverlayContextValue | null>(nul
|
||||
export function FamilyOverlayProvider({ children }: { children: React.ReactNode }) {
|
||||
const [miniChatOpen, setMiniChatOpen] = useState(false);
|
||||
const [pendingRoomId, setPendingRoomId] = useState<string | null>(null);
|
||||
const [pendingMember, setPendingMember] = useState<{ userId: string; name: string } | null>(null);
|
||||
const [pendingMember, setPendingMember] = useState<{ userId: string; name: string; isBot?: boolean; botUsername?: string } | null>(null);
|
||||
const [selectedGroupId, setSelectedGroupIdState] = useState<string | null>(null);
|
||||
const pendingMemberRef = useRef<{ userId: string; name: string } | null>(null);
|
||||
const pendingMemberRef = useRef<{ userId: string; name: string; isBot?: boolean; botUsername?: string } | null>(null);
|
||||
const selectionHydratedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -58,13 +58,16 @@ export function FamilyOverlayProvider({ children }: { children: React.ReactNode
|
||||
setMiniChatOpen(true);
|
||||
}, []);
|
||||
|
||||
const openChatWithMember = useCallback((memberUserId: string, memberName: string) => {
|
||||
const payload = { userId: memberUserId, name: memberName };
|
||||
setPendingMember(payload);
|
||||
pendingMemberRef.current = payload;
|
||||
setPendingRoomId(null);
|
||||
setMiniChatOpen(true);
|
||||
}, []);
|
||||
const openChatWithMember = useCallback(
|
||||
(memberUserId: string, memberName: string, options?: { isBot?: boolean; botUsername?: string }) => {
|
||||
const payload = { userId: memberUserId, name: memberName, ...options };
|
||||
setPendingMember(payload);
|
||||
pendingMemberRef.current = payload;
|
||||
setPendingRoomId(null);
|
||||
setMiniChatOpen(true);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const clearPending = useCallback(() => {
|
||||
setPendingRoomId(null);
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useState } from 'react';
|
||||
import { Loader2, Search, UsersRound } from 'lucide-react';
|
||||
import { Loader2, Plus, Search, UsersRound } from 'lucide-react';
|
||||
import { AvatarWithPresence } from '@/components/family/avatar-with-presence';
|
||||
import { FamilyGroupSelector } from '@/components/family/family-group-selector';
|
||||
import { FamilyInviteDialog } from '@/components/family/family-invite-dialog';
|
||||
import { useFamilyOverlay } from '@/components/family/family-overlay-provider';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useSelectedFamily } from '@/hooks/use-primary-family';
|
||||
import { addBotFatherToFamily, getApiErrorMessage } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function FamilySidebarPanel() {
|
||||
@@ -25,7 +27,9 @@ export function FamilySidebarPanel() {
|
||||
refresh
|
||||
} = useSelectedFamily(Boolean(user && token));
|
||||
const { openChatWithMember } = useFamilyOverlay();
|
||||
const { showToast } = useToast();
|
||||
const [inviteOpen, setInviteOpen] = useState(false);
|
||||
const [addingBotFather, setAddingBotFather] = useState(false);
|
||||
|
||||
if (!user || !token) return null;
|
||||
|
||||
@@ -81,7 +85,12 @@ export function FamilySidebarPanel() {
|
||||
'flex w-full items-center gap-2 rounded-xl px-2 py-1.5 text-left transition hover:bg-[#f4f5f8]',
|
||||
isSelf && 'bg-[#fafbfd]'
|
||||
)}
|
||||
onClick={() => openChatWithMember(member.userId, member.displayName)}
|
||||
onClick={() =>
|
||||
openChatWithMember(member.userId, member.displayName, {
|
||||
isBot: member.isBot,
|
||||
botUsername: member.botUsername
|
||||
})
|
||||
}
|
||||
title={isSelf ? 'Вы' : `Написать ${member.displayName}`}
|
||||
>
|
||||
<AvatarWithPresence
|
||||
@@ -97,17 +106,44 @@ export function FamilySidebarPanel() {
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-[12px] font-medium leading-tight">
|
||||
{member.displayName}
|
||||
{member.isBot ? ' 🤖' : ''}
|
||||
{isSelf ? ' (Вы)' : ''}
|
||||
</p>
|
||||
{!isSelf ? (
|
||||
<p className={cn('truncate text-[10px]', presence?.online ? 'text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{presence?.online ? 'В сети' : 'Не в сети'}
|
||||
<p className={cn('truncate text-[10px]', member.isBot ? 'text-[#3390ec]' : presence?.online ? 'text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{member.isBot ? 'Бот' : presence?.online ? 'В сети' : 'Не в сети'}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{group?.botFatherAvailable ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={addingBotFather}
|
||||
className="flex w-full items-center gap-2 rounded-xl border border-dashed border-[#d5dbe8] px-2 py-2 text-left transition hover:bg-[#f4f5f8] disabled:opacity-60"
|
||||
onClick={() => {
|
||||
if (!group || !token) return;
|
||||
setAddingBotFather(true);
|
||||
void addBotFatherToFamily(group.id, token)
|
||||
.then(() => {
|
||||
showToast('BotFather добавлен в семью');
|
||||
void refresh();
|
||||
})
|
||||
.catch((error) => showToast(getApiErrorMessage(error, 'Не удалось добавить BotFather') ?? 'Ошибка'))
|
||||
.finally(() => setAddingBotFather(false));
|
||||
}}
|
||||
>
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-[#eef4ff] text-[#3390ec]">
|
||||
{addingBotFather ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-[12px] font-medium leading-tight">Добавить BotFather 🤖</p>
|
||||
<p className="truncate text-[10px] text-[#667085]">Создавайте ботов через чат</p>
|
||||
</div>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-xl bg-[#f4f5f8] px-2 py-3 text-[11px] text-[#667085]">
|
||||
@@ -120,6 +156,7 @@ export function FamilySidebarPanel() {
|
||||
{hasFamily ? (
|
||||
<FamilyInviteDialog
|
||||
groupId={group!.id}
|
||||
group={group}
|
||||
open={inviteOpen}
|
||||
onOpenChange={setInviteOpen}
|
||||
onInvited={() => void refresh()}
|
||||
|
||||
62
apps/frontend/components/family/hover-upload-avatar.tsx
Normal file
62
apps/frontend/components/family/hover-upload-avatar.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
'use client';
|
||||
|
||||
import { Camera, Loader2 } from 'lucide-react';
|
||||
import { useId } from 'react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface HoverUploadAvatarProps {
|
||||
name: string;
|
||||
imageUrl?: string | null;
|
||||
uploading?: boolean;
|
||||
onFileSelect: (file: File) => void;
|
||||
className?: string;
|
||||
fallbackClassName?: string;
|
||||
}
|
||||
|
||||
export function HoverUploadAvatar({
|
||||
name,
|
||||
imageUrl,
|
||||
uploading = false,
|
||||
onFileSelect,
|
||||
className,
|
||||
fallbackClassName
|
||||
}: HoverUploadAvatarProps) {
|
||||
const inputId = useId();
|
||||
|
||||
return (
|
||||
<label
|
||||
htmlFor={inputId}
|
||||
className={cn(
|
||||
'group/avatar relative block cursor-pointer overflow-hidden rounded-full transition',
|
||||
uploading && 'pointer-events-none',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Avatar className="h-full w-full">
|
||||
{imageUrl ? <AvatarImage src={imageUrl} alt={name} /> : null}
|
||||
<AvatarFallback className={fallbackClassName}>{name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span
|
||||
className={cn(
|
||||
'absolute inset-0 flex items-center justify-center bg-black/45 text-white opacity-0 transition-opacity duration-200 group-hover/avatar:opacity-100',
|
||||
uploading && 'opacity-100'
|
||||
)}
|
||||
>
|
||||
{uploading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Camera className="h-5 w-5" />}
|
||||
</span>
|
||||
<input
|
||||
id={inputId}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="sr-only"
|
||||
disabled={uploading}
|
||||
onChange={(event) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) onFileSelect(file);
|
||||
event.target.value = '';
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { Boxes, Settings2, ShieldCheck, Users } from 'lucide-react';
|
||||
import { Bot, Boxes, Settings2, ShieldCheck, Users } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { PublicUser } from '@/lib/api';
|
||||
|
||||
@@ -12,6 +12,12 @@ const links = [
|
||||
icon: Users,
|
||||
permissions: ['canViewUsers', 'canManageUsers'] as const
|
||||
},
|
||||
{
|
||||
href: '/admin/bots',
|
||||
label: 'Боты',
|
||||
icon: Bot,
|
||||
permissions: ['canManageBots'] as const
|
||||
},
|
||||
{
|
||||
href: '/admin/oauth',
|
||||
label: 'OAuth',
|
||||
|
||||
@@ -100,10 +100,10 @@ export function OAuthClientDetailDialog({
|
||||
Быстрый старт
|
||||
</div>
|
||||
<ol className="list-decimal space-y-1 pl-5 text-xs text-[#667085]">
|
||||
<li>Авторизуйте пользователя в IdP и получите userId.</li>
|
||||
<li>Перенаправьте на authorization endpoint с clientId, redirectUri, scope, userId.</li>
|
||||
<li>На backend обменяйте code через POST /oauth/token с client_secret.</li>
|
||||
<li>Запросите профиль через GET /oauth/userinfo с access token.</li>
|
||||
<li>Укажите issuer = PUBLIC_API_URL в OIDC-клиенте (PHP, Keycloak, Grafana и т.д.).</li>
|
||||
<li>Перенаправьте пользователя на authorization endpoint — стандартные параметры client_id, redirect_uri, response_type=code.</li>
|
||||
<li>IdP покажет вход и экран «Разрешить доступ», затем вернёт code на redirect_uri.</li>
|
||||
<li>На backend обменяйте code через POST /oauth/token (form-urlencoded или JSON).</li>
|
||||
</ol>
|
||||
<a
|
||||
href={endpoints.openIdConfigurationUrl}
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
import { Sidebar } from './sidebar';
|
||||
import { UserMenu } from './user-menu';
|
||||
import { NotificationBell } from '@/components/notifications/notification-bell';
|
||||
import { EmojiSpriteProvider } from '@/components/chat/emoji-sprite-provider';
|
||||
import { FamilyOverlayProvider } from '@/components/family/family-overlay-provider';
|
||||
import { MiniFamilyChat } from '@/components/family/mini-family-chat';
|
||||
|
||||
export function IdShell({ active, children, wide = false }: { active: string; children: React.ReactNode; wide?: boolean }) {
|
||||
return (
|
||||
<FamilyOverlayProvider>
|
||||
<EmojiSpriteProvider />
|
||||
<div className="min-h-screen bg-white">
|
||||
<Sidebar active={active} />
|
||||
<div className="fixed right-4 top-4 z-40 flex items-center gap-2 lg:right-8 lg:top-6">
|
||||
|
||||
39
apps/frontend/components/ui/context-menu.tsx
Normal file
39
apps/frontend/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
'use client';
|
||||
|
||||
import * as ContextMenuPrimitive from '@radix-ui/react-context-menu';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export const ContextMenu = ContextMenuPrimitive.Root;
|
||||
export const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
|
||||
export const ContextMenuPortal = ContextMenuPrimitive.Portal;
|
||||
|
||||
export function ContextMenuContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
className={cn(
|
||||
'z-50 min-w-[220px] overflow-hidden rounded-2xl border border-[#dce3ec] bg-white p-1.5 text-[#1f2430] shadow-[0_12px_40px_rgba(31,36,48,0.12)] animate-in fade-in zoom-in-95 duration-150',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ContextMenuItem({ className, inset, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Item> & { inset?: boolean }) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
className={cn(
|
||||
'flex cursor-pointer select-none items-center gap-3 rounded-xl px-3 py-2.5 text-sm outline-none data-[highlighted]:bg-[#f4f5f8] data-[highlighted]:text-[#1f2430]',
|
||||
inset && 'pl-8',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ContextMenuSeparator({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return <ContextMenuPrimitive.Separator className={cn('my-1 h-px bg-[#eceef4]', className)} {...props} />;
|
||||
}
|
||||
Reference in New Issue
Block a user