feat: add header channel selector & adding channel modal menu
This commit is contained in:
@@ -11,7 +11,6 @@ import {
|
||||
LayoutDashboard,
|
||||
Megaphone,
|
||||
ShoppingCart,
|
||||
Target,
|
||||
TrendingUp,
|
||||
Settings2,
|
||||
ExternalLink,
|
||||
@@ -36,17 +35,6 @@ const data = {
|
||||
icon: LayoutDashboard,
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
title: "Целевые каналы",
|
||||
url: "/channels",
|
||||
icon: Target,
|
||||
items: [
|
||||
{
|
||||
title: "Все каналы",
|
||||
url: "/channels",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Внешние каналы",
|
||||
url: "/external-channels",
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb";
|
||||
import { ThemeToggle } from "@/components/theme-toggle";
|
||||
import { TargetChannelSelector } from "@/components/target-channel-selector";
|
||||
import React from "react";
|
||||
|
||||
interface BreadcrumbItem {
|
||||
@@ -53,7 +54,8 @@ export const DashboardHeader: React.FC<DashboardHeaderProps> = ({
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)}
|
||||
<div className="ml-auto">
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<TargetChannelSelector />
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
6
components/providers/index.ts
Normal file
6
components/providers/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
// ============================================================================
|
||||
// Providers Export
|
||||
// ============================================================================
|
||||
|
||||
export { TargetChannelProvider, useTargetChannel } from "./target-channel-provider";
|
||||
|
||||
101
components/providers/target-channel-provider.tsx
Normal file
101
components/providers/target-channel-provider.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
"use client";
|
||||
|
||||
// ============================================================================
|
||||
// Target Channel Provider
|
||||
// ============================================================================
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect } from "react";
|
||||
import { channelsApi } from "@/lib/api";
|
||||
import type { TargetChannel } from "@/lib/types/api";
|
||||
|
||||
interface TargetChannelContextType {
|
||||
channels: TargetChannel[];
|
||||
selectedChannel: TargetChannel | null;
|
||||
setSelectedChannel: (channel: TargetChannel | null) => void;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
refreshChannels: () => Promise<void>;
|
||||
}
|
||||
|
||||
const TargetChannelContext = createContext<TargetChannelContextType | undefined>(
|
||||
undefined
|
||||
);
|
||||
|
||||
export const useTargetChannel = () => {
|
||||
const context = useContext(TargetChannelContext);
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"useTargetChannel must be used within TargetChannelProvider"
|
||||
);
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const TargetChannelProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
children,
|
||||
}) => {
|
||||
const [channels, setChannels] = useState<TargetChannel[]>([]);
|
||||
const [selectedChannel, setSelectedChannelState] = useState<TargetChannel | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadChannels = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const response = await channelsApi.list();
|
||||
const activeChannels = response.target_channels.filter((c) => c.is_active);
|
||||
setChannels(activeChannels);
|
||||
|
||||
// Загружаем сохраненный канал из localStorage
|
||||
const savedChannelId = localStorage.getItem("selected_channel_id");
|
||||
if (savedChannelId && activeChannels.length > 0) {
|
||||
const savedChannel = activeChannels.find((c) => c.id === savedChannelId);
|
||||
if (savedChannel) {
|
||||
setSelectedChannelState(savedChannel);
|
||||
} else {
|
||||
// Если сохраненный канал не найден, выбираем первый
|
||||
setSelectedChannelState(activeChannels[0]);
|
||||
localStorage.setItem("selected_channel_id", activeChannels[0].id);
|
||||
}
|
||||
} else if (activeChannels.length > 0) {
|
||||
// Если нет сохраненного канала, выбираем первый
|
||||
setSelectedChannelState(activeChannels[0]);
|
||||
localStorage.setItem("selected_channel_id", activeChannels[0].id);
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err?.error?.message || "Ошибка загрузки каналов");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const setSelectedChannel = (channel: TargetChannel | null) => {
|
||||
setSelectedChannelState(channel);
|
||||
if (channel) {
|
||||
localStorage.setItem("selected_channel_id", channel.id);
|
||||
} else {
|
||||
localStorage.removeItem("selected_channel_id");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadChannels();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<TargetChannelContext.Provider
|
||||
value={{
|
||||
channels,
|
||||
selectedChannel,
|
||||
setSelectedChannel,
|
||||
isLoading,
|
||||
error,
|
||||
refreshChannels: loadChannels,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</TargetChannelContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
279
components/target-channel-selector.tsx
Normal file
279
components/target-channel-selector.tsx
Normal file
@@ -0,0 +1,279 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTargetChannel } from "@/components/providers/target-channel-provider";
|
||||
import {
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
Plus,
|
||||
ExternalLink,
|
||||
CheckCircle2,
|
||||
ArrowUpRightIcon,
|
||||
} from "lucide-react";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { BOT_USERNAME } from "@/lib/utils/constants";
|
||||
import { channelsApi } from "@/lib/api";
|
||||
|
||||
export const TargetChannelSelector: React.FC = () => {
|
||||
const { channels, selectedChannel, setSelectedChannel, isLoading, error } =
|
||||
useTargetChannel();
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
|
||||
const [isSuccess, setIsSuccess] = useState(false);
|
||||
const [initialChannelCount, setInitialChannelCount] = useState(0);
|
||||
const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Очистка интервала при размонтировании
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Автоматический запуск polling при открытии диалога
|
||||
useEffect(() => {
|
||||
if (isAddDialogOpen && !isSuccess && initialChannelCount > 0) {
|
||||
// Polling каждую секунду
|
||||
pollingIntervalRef.current = setInterval(() => {
|
||||
checkForNewChannels();
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current);
|
||||
pollingIntervalRef.current = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [isAddDialogOpen, isSuccess, initialChannelCount]);
|
||||
|
||||
const checkForNewChannels = async () => {
|
||||
try {
|
||||
const response = await channelsApi.list();
|
||||
const activeChannels = response.target_channels.filter(
|
||||
(c) => c.is_active
|
||||
);
|
||||
|
||||
if (activeChannels.length > initialChannelCount) {
|
||||
// Новый канал добавлен!
|
||||
setIsSuccess(true);
|
||||
|
||||
// Останавливаем polling
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current);
|
||||
pollingIntervalRef.current = null;
|
||||
}
|
||||
|
||||
// Закрываем диалог через 2 секунды
|
||||
setTimeout(() => {
|
||||
setIsAddDialogOpen(false);
|
||||
setIsSuccess(false);
|
||||
// Обновляем список каналов через провайдер
|
||||
window.location.reload();
|
||||
}, 2000);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error polling channels:", err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddChannel = () => {
|
||||
setInitialChannelCount(channels.length);
|
||||
setIsSuccess(false);
|
||||
setIsAddDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDialogClose = () => {
|
||||
if (!isSuccess) {
|
||||
// Не даем закрыть диалог во время ожидания
|
||||
return;
|
||||
}
|
||||
setIsAddDialogOpen(false);
|
||||
setIsSuccess(false);
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current);
|
||||
pollingIntervalRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Загрузка каналов...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Alert variant="destructive" className="p-2 h-auto">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">Ошибка: {error}</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (channels.length === 0) {
|
||||
return (
|
||||
<Button variant="outline" size="sm" onClick={handleAddChannel}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Добавить канал
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Select
|
||||
value={selectedChannel?.id || "add-new"}
|
||||
onValueChange={(value) => {
|
||||
if (value === "add-new") {
|
||||
handleAddChannel();
|
||||
} else {
|
||||
const channel = channels.find((c) => c.id === value);
|
||||
if (channel) {
|
||||
setSelectedChannel(channel);
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-[260px] h-auto min-h-[52px] py-2 rounded-lg">
|
||||
<SelectValue placeholder="Выберите канал">
|
||||
{selectedChannel && (
|
||||
<div className="flex flex-col items-start gap-0.5">
|
||||
<span className="font-semibold text-base">
|
||||
{selectedChannel.title}
|
||||
</span>
|
||||
{selectedChannel.username && (
|
||||
<span className="text-xs text-muted-foreground -mt-1">
|
||||
@{selectedChannel.username}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{channels.map((channel) => (
|
||||
<SelectItem
|
||||
key={channel.id}
|
||||
value={channel.id}
|
||||
className="cursor-pointer py-3"
|
||||
>
|
||||
<div className="flex items-center justify-between w-full gap-2">
|
||||
<div className="flex flex-col items-start flex-1 min-w-0 gap-0.5">
|
||||
<span className="font-semibold text-base truncate w-full">
|
||||
{channel.title}
|
||||
</span>
|
||||
{channel.username && (
|
||||
<span className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
@{channel.username}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
<SelectItem
|
||||
value="add-new"
|
||||
className="cursor-pointer border-t mt-1 py-3"
|
||||
>
|
||||
<div className="flex items-center gap-2 text-primary">
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="font-medium">Добавить канал</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Dialog open={isAddDialogOpen} onOpenChange={handleDialogClose}>
|
||||
<DialogContent
|
||||
className="sm:max-w-md"
|
||||
onInteractOutside={(e) => !isSuccess && e.preventDefault()}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Добавить целевой канал</DialogTitle>
|
||||
<DialogDescription>
|
||||
Следуйте инструкциям ниже, чтобы подключить новый канал
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isSuccess ? (
|
||||
<div className="flex flex-col items-center justify-center py-8 space-y-4">
|
||||
<div className="rounded-full bg-green-100 dark:bg-green-900 p-3">
|
||||
<CheckCircle2 className="h-8 w-8 text-green-600 dark:text-green-400" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Канал успешно добавлен!
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Страница обновится автоматически...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<AlertDescription className="space-y-2">
|
||||
<p className="font-medium">Шаги для добавления канала:</p>
|
||||
<ol className="list-decimal list-inside space-y-1.5 text-sm">
|
||||
<li>Откройте свой Telegram канал</li>
|
||||
<li>Перейдите в настройки канала → Администраторы</li>
|
||||
<li>
|
||||
Добавьте бота{" "}
|
||||
<a
|
||||
href={`https://t.me/${BOT_USERNAME}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-mono text-primary hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
@{BOT_USERNAME}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>{" "}
|
||||
как администратора
|
||||
</li>
|
||||
<li>
|
||||
Предоставьте боту права:{" "}
|
||||
<span className="font-medium">
|
||||
Публикация сообщений, Удаление сообщений
|
||||
</span>
|
||||
</li>
|
||||
</ol>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="flex flex-col items-center justify-center py-6 space-y-3">
|
||||
<Loader2 className="h-10 w-10 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
Ждем добавления бота...
|
||||
<br />
|
||||
<span className="text-xs">
|
||||
Как только вы добавите бота, канал автоматически появится
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user