global update and global fix
This commit is contained in:
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
Reference in New Issue
Block a user