6738 lines
230 KiB
Plaintext
6738 lines
230 KiB
Plaintext
|
|
// file: app/components/app-layout.tsx
|
|
import React from "react";
|
|
import { useMatches } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
import { CreateServerButton } from "./custom-ui/create-server-button";
|
|
import { HomeButton } from "./custom-ui/home-button";
|
|
import { ServerButton } from "./custom-ui/server-button";
|
|
import UserStatus from "./custom-ui/user-status";
|
|
import { ScrollArea } from "./ui/scroll-area";
|
|
import { Separator } from "./ui/separator";
|
|
|
|
interface AppLayoutProps {
|
|
children: React.ReactNode;
|
|
}
|
|
|
|
export default function AppLayout({ children }: AppLayoutProps) {
|
|
const servers = Object.values(useServerListStore(useShallow((state) => state.servers)));
|
|
|
|
const matches = useMatches();
|
|
|
|
const list = React.useMemo(() => {
|
|
return matches
|
|
.map(
|
|
(match) =>
|
|
(
|
|
match.handle as {
|
|
listComponent?: React.ReactNode;
|
|
}
|
|
)?.listComponent,
|
|
)
|
|
.reverse()
|
|
.find((component) => !!component);
|
|
}, [matches]);
|
|
|
|
return (
|
|
<div className="flex h-screen w-screen overflow-hidden">
|
|
<div
|
|
className="grid h-full max-h-screen bg-background min-w-80 border-r-2"
|
|
style={{
|
|
gridTemplateColumns: "auto 1fr",
|
|
gridTemplateRows: "1fr auto",
|
|
}}
|
|
>
|
|
<div className="col-start-1 row-start-1 col-span-1 row-span-1 overflow-hidden border-r-2 min-w-fit">
|
|
<ScrollArea className="h-full px-1" scrollbarSize="none">
|
|
<aside className="flex flex-col gap-2 p-2 h-full">
|
|
<HomeButton />
|
|
<Separator />
|
|
{servers.map((server) => (
|
|
<React.Fragment key={server.id}>
|
|
<ServerButton server={server} />
|
|
</React.Fragment>
|
|
))}
|
|
{servers.length > 0 && <Separator />}
|
|
<CreateServerButton />
|
|
</aside>
|
|
</ScrollArea>
|
|
</div>
|
|
<div className="col-start-2 row-start-1 col-span-1 row-span-1 overflow-hidden">{list}</div>
|
|
|
|
<div className="col-start-1 row-start-2 col-span-2 row-span-1 mb-2 mx-2 min-w-fit z-1">
|
|
<UserStatus />
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grow">{children}</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/components/channel-area.tsx
|
|
import { useInfiniteQuery, type QueryFunctionContext } from "@tanstack/react-query";
|
|
import type { Channel, Message, MessageId } from "~/lib/api/types";
|
|
import ChatMessage from "./chat-message";
|
|
import MessageBox from "./message-box";
|
|
import { Separator } from "./ui/separator";
|
|
import VisibleTrigger from "./visible-trigger";
|
|
|
|
interface ChannelAreaProps {
|
|
channel: Channel;
|
|
}
|
|
|
|
export default function ChannelArea({ channel }: ChannelAreaProps) {
|
|
const channelId = channel.id;
|
|
|
|
const fetchMessages = async ({ pageParam }: QueryFunctionContext) => {
|
|
return await import("~/lib/api/client/channel").then((m) =>
|
|
m.default.paginatedMessages(channelId, 50, pageParam as MessageId | undefined),
|
|
);
|
|
};
|
|
|
|
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isPending, status } = useInfiniteQuery({
|
|
queryKey: ["messages", channelId],
|
|
initialPageParam: undefined,
|
|
queryFn: fetchMessages,
|
|
getNextPageParam: (lastPage) => (lastPage.length < 50 ? undefined : lastPage[lastPage.length - 1]?.id),
|
|
staleTime: Infinity,
|
|
});
|
|
|
|
const fetchNextPageVisible = () => {
|
|
if (!isFetchingNextPage && hasNextPage) fetchNextPage();
|
|
};
|
|
|
|
let messageArea = null;
|
|
|
|
if (isPending) {
|
|
messageArea = (
|
|
<div className="flex items-center justify-center size-full">
|
|
<span>Loading...</span>
|
|
</div>
|
|
);
|
|
} else {
|
|
messageArea = (
|
|
<>
|
|
<div className="flex-1" />
|
|
<div className="flex flex-col-reverse overflow-auto gap-2 pb-2 pr-2">
|
|
{status === "success" && renderMessages(data.pages)}
|
|
<VisibleTrigger triggerOnce={false} onVisible={fetchNextPageVisible} />
|
|
</div>
|
|
</>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<div className="flex flex-col size-full">
|
|
<div className="w-full min-h-12 border-b-2 flex items-center justify-center">{channel?.name}</div>
|
|
<div className="flex-1 overflow-y-auto flex flex-col pl-2 pr-0.5">{messageArea}</div>
|
|
<div className="w-full">
|
|
<MessageBox channelId={channelId} />
|
|
</div>
|
|
</div>
|
|
</>
|
|
);
|
|
}
|
|
|
|
function renderMessages(pages: Message[][]) {
|
|
const messageElements: React.ReactNode[] = [];
|
|
let lastDate: string | null = null;
|
|
|
|
const formatMessageDate = (date: Date) => {
|
|
const now = new Date();
|
|
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
const yesterday = new Date(today);
|
|
yesterday.setDate(yesterday.getDate() - 1);
|
|
|
|
const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
|
|
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
|
|
|
|
if (messageDate.getTime() === today.getTime()) {
|
|
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
|
numeric: "auto",
|
|
});
|
|
return capitalize(rtf.format(0, "day"));
|
|
} else if (messageDate.getTime() === yesterday.getTime()) {
|
|
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
|
numeric: "auto",
|
|
});
|
|
return capitalize(rtf.format(-1, "day"));
|
|
} else {
|
|
return date.toLocaleDateString(undefined, {
|
|
month: "short",
|
|
day: "numeric",
|
|
});
|
|
}
|
|
};
|
|
|
|
pages.forEach((page) => {
|
|
page.forEach((message) => {
|
|
const messageDate = message.createdAt.toDateString();
|
|
if (messageDate != lastDate) {
|
|
if (lastDate)
|
|
messageElements.push(
|
|
<div className="flex items-center justify-center py-2 w-full">
|
|
<Separator className="flex-1" />
|
|
<span className="mx-4 text-sm text-muted-foreground">
|
|
{formatMessageDate(new Date(lastDate))}
|
|
</span>
|
|
<Separator className="flex-1" />
|
|
</div>,
|
|
);
|
|
lastDate = messageDate;
|
|
}
|
|
|
|
messageElements.push(
|
|
<div key={message.id} className="w-full">
|
|
<ChatMessage message={message} />
|
|
</div>,
|
|
);
|
|
});
|
|
});
|
|
|
|
return messageElements;
|
|
}
|
|
|
|
// file: app/components/chat-message-attachment.tsx
|
|
import { Download, ExternalLink, Maximize } from "lucide-react";
|
|
import { AspectRatio } from "~/components/ui/aspect-ratio"; // Shadcn UI AspectRatio
|
|
import { Button } from "~/components/ui/button"; // Shadcn UI Button
|
|
import {
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogTrigger,
|
|
} from "~/components/ui/dialog"; // Shadcn UI Dialog
|
|
import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip"; // Shadcn UI Tooltip
|
|
import type { UploadedFile } from "~/lib/api/types"; // Adjust path as needed
|
|
import { formatFileSize } from "~/lib/utils"; // Adjust path
|
|
import { FileIcon } from "./file-icon";
|
|
|
|
interface ChatMessageAttachmentProps {
|
|
file: UploadedFile;
|
|
}
|
|
|
|
export default function ChatMessageAttachment({ file }: ChatMessageAttachmentProps) {
|
|
if (file.contentType.startsWith("image/")) {
|
|
return <ImageAttachment file={file} />;
|
|
}
|
|
return <GenericFileAttachment file={file} />;
|
|
}
|
|
|
|
function GenericFileAttachment({ file }: ChatMessageAttachmentProps) {
|
|
return (
|
|
<div className="flex items-center gap-3 rounded-lg border bg-card p-3 shadow-sm ">
|
|
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md">
|
|
<FileIcon className="h-8 w-8 text-muted-foreground" contentType={file.contentType} />
|
|
</div>
|
|
<div className="flex-1 overflow-hidden">
|
|
<p className="truncate text-sm font-medium text-card-foreground">{file.filename}</p>
|
|
<p className="text-xs text-muted-foreground">{formatFileSize(file.size)}</p>
|
|
</div>
|
|
<div className="flex items-center gap-1">
|
|
<Tooltip disableHoverableContent>
|
|
<TooltipTrigger asChild>
|
|
<Button variant="ghost" size="icon" asChild>
|
|
<a href={file.url} target="_blank" rel="noreferrer" download={file.filename}>
|
|
<Download className="h-4 w-4" />
|
|
<span className="sr-only">Download</span>
|
|
</a>
|
|
</Button>
|
|
</TooltipTrigger>
|
|
<TooltipContent>Download</TooltipContent>
|
|
</Tooltip>
|
|
<Tooltip disableHoverableContent>
|
|
<TooltipTrigger asChild>
|
|
<Button variant="ghost" size="icon" asChild>
|
|
<a href={file.url} target="_blank" rel="noreferrer">
|
|
<ExternalLink className="h-4 w-4" />
|
|
<span className="sr-only">Open in new tab</span>
|
|
</a>
|
|
</Button>
|
|
</TooltipTrigger>
|
|
<TooltipContent>Open in new tab</TooltipContent>
|
|
</Tooltip>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function ImageAttachment({ file }: ChatMessageAttachmentProps) {
|
|
return (
|
|
<Dialog>
|
|
<div className="relative w-48 sm:w-64">
|
|
<DialogTrigger asChild>
|
|
<AspectRatio
|
|
ratio={16 / 9}
|
|
className="group cursor-pointer overflow-hidden rounded-lg border bg-muted"
|
|
>
|
|
<img
|
|
src={file.url}
|
|
alt={file.filename}
|
|
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
|
/>
|
|
<div className="absolute inset-0 flex items-center justify-center bg-black/30 opacity-0 transition-opacity group-hover:opacity-100">
|
|
<Maximize className="h-8 w-8 text-white" />
|
|
</div>
|
|
</AspectRatio>
|
|
</DialogTrigger>
|
|
<div className="mt-1">
|
|
<p className="truncate text-xs text-muted-foreground">
|
|
{file.filename} ({formatFileSize(file.size)})
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<DialogContent className="max-w-3xl p-0">
|
|
<DialogHeader className="p-4 pb-0">
|
|
<DialogTitle className="truncate">{file.filename}</DialogTitle>
|
|
</DialogHeader>
|
|
<div className="p-4 pt-0 max-h-[70vh] overflow-y-auto">
|
|
<img
|
|
src={file.url}
|
|
alt={file.filename}
|
|
className="mx-auto max-h-full w-auto rounded-md object-contain"
|
|
/>
|
|
</div>
|
|
<DialogFooter className="flex-col items-stretch gap-2 border-t p-4 sm:flex-row sm:justify-end sm:space-x-2">
|
|
<Button variant="outline" asChild>
|
|
<a href={file.url} target="_blank" rel="noreferrer">
|
|
<ExternalLink className="mr-2 h-4 w-4" /> Open original
|
|
</a>
|
|
</Button>
|
|
<Button asChild>
|
|
<a href={file.url} download={file.filename}>
|
|
<Download className="mr-2 h-4 w-4" /> Download
|
|
</a>
|
|
</Button>
|
|
<DialogClose asChild>
|
|
<Button variant="ghost">Close</Button>
|
|
</DialogClose>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
// file: app/components/chat-message.tsx
|
|
import { Clock } from "lucide-react";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { useFetchUser } from "~/hooks/use-fetch-user";
|
|
import type { Message } from "~/lib/api/types";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import ChatMessageAttachment from "./chat-message-attachment";
|
|
import UserAvatar from "./user-avatar";
|
|
import UserContextMenu from "./user-context-menu";
|
|
|
|
interface ChatMessageProps {
|
|
message: Message;
|
|
}
|
|
|
|
export default function ChatMessage({ message }: ChatMessageProps) {
|
|
const { user } = useUsersStore(
|
|
useShallow((state) => ({
|
|
user: state.users[message.authorId],
|
|
})),
|
|
);
|
|
|
|
useFetchUser(message.authorId);
|
|
|
|
const formatMessageDate = (date: Date) => {
|
|
const now = new Date();
|
|
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
const yesterday = new Date(today);
|
|
yesterday.setDate(yesterday.getDate() - 1);
|
|
|
|
const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
|
|
// Get localized time string
|
|
const timeString = date.toLocaleTimeString(undefined, {
|
|
hour: "2-digit",
|
|
minute: "2-digit",
|
|
hour12: false,
|
|
});
|
|
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
|
|
|
|
if (messageDate.getTime() === today.getTime()) {
|
|
// Use Intl.RelativeTimeFormat for localized "Today"
|
|
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
|
numeric: "auto",
|
|
});
|
|
return `${capitalize(rtf.format(0, "day"))}, ${timeString}`;
|
|
} else if (messageDate.getTime() === yesterday.getTime()) {
|
|
// Use Intl.RelativeTimeFormat for localized "Yesterday"
|
|
const rtf = new Intl.RelativeTimeFormat(undefined, {
|
|
numeric: "auto",
|
|
});
|
|
return `${capitalize(rtf.format(-1, "day"))}, ${timeString}`;
|
|
} else {
|
|
return date.toLocaleDateString(undefined, {
|
|
month: "short",
|
|
day: "numeric",
|
|
hour: "2-digit",
|
|
minute: "2-digit",
|
|
hour12: false,
|
|
});
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div
|
|
className="grid gap-x-2"
|
|
style={{
|
|
gridTemplateColumns: "auto 1fr",
|
|
gridTemplateRows: "auto 1fr",
|
|
}}
|
|
>
|
|
<div className="row-start-1 col-start-1 row-span-2 col-span-1">
|
|
<UserContextMenu userId={message.authorId}>
|
|
<UserAvatar user={user} />
|
|
</UserContextMenu>
|
|
</div>
|
|
<div className="row-start-1 col-start-2 row-span-1 col-span-1 flex items-center gap-2">
|
|
<span className="font-medium text-sm">
|
|
<UserContextMenu userId={message.authorId}>
|
|
<div>{user?.displayName || user?.username}</div>
|
|
</UserContextMenu>
|
|
</span>
|
|
<div className="flex items-center gap-0.5 text-xs text-muted-foreground whitespace-nowrap">
|
|
<Clock className="size-3" />
|
|
<span>{formatMessageDate(message.createdAt)}</span>
|
|
</div>
|
|
</div>
|
|
<div className="row-start-2 col-start-2 row-span-1 col-span-1">
|
|
<div className="wrap-break-word contain-inline-size">{message.content}</div>
|
|
<div className="grid gap-2 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 justify-start">
|
|
{message.attachments.map((file) => (
|
|
<div key={file.id}>
|
|
<ChatMessageAttachment file={file} />
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/channel-list-item.tsx
|
|
import { ChevronDown, Hash, Volume2 } from "lucide-react";
|
|
import React from "react";
|
|
import { NavLink } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { useFetchUsers } from "~/hooks/use-fetch-user";
|
|
import { deleteChannel } from "~/lib/api/client/server";
|
|
import { ChannelType, type ServerChannel } from "~/lib/api/types";
|
|
import { cn } from "~/lib/utils";
|
|
import { useChannelsVoiceStateStore } from "~/stores/channels-voice-state";
|
|
import { useGatewayStore } from "~/stores/gateway-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import { useVoiceStateStore } from "~/stores/voice-state-store";
|
|
import { Button } from "../ui/button";
|
|
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "../ui/context-menu";
|
|
import UserAvatar from "../user-avatar";
|
|
import UserContextMenu from "../user-context-menu";
|
|
|
|
interface ChannelListItemProps {
|
|
channel: ServerChannel;
|
|
}
|
|
|
|
const onDeleteChannel = async (channel: ServerChannel) => {
|
|
await deleteChannel(channel.serverId, channel.id);
|
|
};
|
|
|
|
interface ChannelItemWrapperProps {
|
|
channel: ServerChannel;
|
|
icon: React.ReactNode;
|
|
onButtonClick?: () => void; // For direct button clicks (e.g., join voice)
|
|
navTo?: string; // If provided, the button becomes a NavLink
|
|
isExplicitlyActive?: boolean; // To set active state externally (e.g., current voice channel)
|
|
}
|
|
|
|
function ChannelItemWrapper({ channel, icon, onButtonClick, navTo, isExplicitlyActive }: ChannelItemWrapperProps) {
|
|
const buttonInnerContent = (
|
|
<div className="flex items-center gap-2 max-w-72">
|
|
<div>{icon}</div>
|
|
<div className="truncate">{channel.name}</div>
|
|
</div>
|
|
);
|
|
|
|
const renderButton = (isNavLinkActive?: boolean) => {
|
|
// Active state priority: explicit prop > NavLink state > default (false)
|
|
const isActive = isExplicitlyActive ?? isNavLinkActive ?? false;
|
|
return (
|
|
<Button
|
|
variant="secondary"
|
|
size="sm"
|
|
className={cn(
|
|
"justify-start w-full shadow-sm",
|
|
isActive ? "bg-accent hover:bg-accent" : "bg-secondary",
|
|
)}
|
|
onClick={!navTo ? onButtonClick : undefined}
|
|
>
|
|
{buttonInnerContent}
|
|
</Button>
|
|
);
|
|
};
|
|
|
|
let triggerContent: React.ReactNode;
|
|
if (navTo) {
|
|
triggerContent = (
|
|
<NavLink to={navTo} discover="none">
|
|
{({ isActive: navLinkIsActive }) => renderButton(navLinkIsActive)}
|
|
</NavLink>
|
|
);
|
|
} else {
|
|
// For non-NavLink cases (like voice channel), active state is determined by isExplicitlyActive
|
|
triggerContent = renderButton();
|
|
}
|
|
|
|
return (
|
|
<ContextMenu>
|
|
<ContextMenuTrigger asChild>{triggerContent}</ContextMenuTrigger>
|
|
<ContextMenuContent>
|
|
<ContextMenuItem variant="destructive" onClick={() => onDeleteChannel(channel)}>
|
|
Delete
|
|
</ContextMenuItem>
|
|
</ContextMenuContent>
|
|
</ContextMenu>
|
|
);
|
|
}
|
|
|
|
function ServerCategory({ channel }: ChannelListItemProps) {
|
|
return (
|
|
<div className="text-xs flex flex-row justify-between mt-4">
|
|
<div className="grow">
|
|
<div className="flex items-center gap-1">
|
|
{channel.name}
|
|
<ChevronDown className="size-4" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function ServerVoice({ channel }: ChannelListItemProps) {
|
|
const updateVoiceState = useGatewayStore((state) => state.updateVoiceState);
|
|
const voiceStateChannel = useVoiceStateStore((state) => state.activeChannel);
|
|
const channelVoiceState = useChannelsVoiceStateStore((state) => state.channels[channel.id]) || {};
|
|
const userIds = Object.keys(channelVoiceState.users ?? {});
|
|
useFetchUsers(userIds);
|
|
|
|
const users = useUsersStore(useShallow((state) => state.users));
|
|
|
|
const channelUsers = React.useMemo(() => userIds.map((userId) => users[userId]).filter(Boolean), [userIds, users]);
|
|
|
|
const isCurrentVoiceChannel =
|
|
voiceStateChannel?.serverId === channel.serverId && voiceStateChannel.channelId === channel.id;
|
|
|
|
const handleJoinVoiceChannel = () => {
|
|
if (isCurrentVoiceChannel) return;
|
|
updateVoiceState(channel.serverId, channel.id);
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<ChannelItemWrapper
|
|
channel={channel}
|
|
icon={<Volume2 />}
|
|
onButtonClick={handleJoinVoiceChannel}
|
|
isExplicitlyActive={isCurrentVoiceChannel}
|
|
/>
|
|
{channelUsers.length > 0 && (
|
|
<div className="ml-2 border-l-2 flex flex-col gap-1 pl-4 py-1">
|
|
{" "}
|
|
{/* Added py-1 for spacing */}
|
|
{channelUsers.map((user) => (
|
|
<React.Fragment key={user.id}>
|
|
<UserContextMenu userId={user.id}>
|
|
<div className="flex items-center gap-2 max-w-72 p-1 hover:bg-secondary/80 rounded">
|
|
{" "}
|
|
{/* Added padding and hover for better UX */}
|
|
<UserAvatar user={user} className="size-6" />
|
|
{user.displayName || user.username}
|
|
</div>
|
|
</UserContextMenu>
|
|
</React.Fragment>
|
|
))}
|
|
</div>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function ServerText({ channel }: ChannelListItemProps) {
|
|
return (
|
|
<ChannelItemWrapper channel={channel} icon={<Hash />} navTo={`/app/server/${channel.serverId}/${channel.id}`} />
|
|
);
|
|
}
|
|
|
|
export default function ServerChannelListItem({ channel }: ChannelListItemProps) {
|
|
switch (channel.type) {
|
|
case ChannelType.SERVER_CATEGORY:
|
|
return <ServerCategory channel={channel} />;
|
|
case ChannelType.SERVER_VOICE:
|
|
return <ServerVoice channel={channel} />;
|
|
case ChannelType.SERVER_TEXT:
|
|
return <ServerText channel={channel} />;
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// file: app/components/custom-ui/create-server-button.tsx
|
|
import { CirclePlus } from "lucide-react";
|
|
|
|
import { Button } from "~/components/ui/button";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
|
|
export function CreateServerButton() {
|
|
const onOpen = useModalStore((state) => state.onOpen);
|
|
|
|
return (
|
|
<Button variant="outline" size="none" onClick={() => onOpen(ModalType.CREATE_SERVER)}>
|
|
<CirclePlus className="size-8 m-2" />
|
|
</Button>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/home-button.tsx
|
|
import { NavLink } from "react-router";
|
|
import Discord from "../icons/Discord";
|
|
import { Button } from "../ui/button";
|
|
|
|
export function HomeButton() {
|
|
return (
|
|
<NavLink to={`/app/@me`}>
|
|
{({ isActive }) => (
|
|
<Button variant="outline" size="none" className={isActive ? "bg-accent" : ""}>
|
|
<div className="size-12 p-2 flex items-center justify-center">
|
|
<Discord className="size-full" />
|
|
</div>
|
|
</Button>
|
|
)}
|
|
</NavLink>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/online-status.tsx
|
|
import { Circle, MinusCircle, Moon } from "lucide-react";
|
|
import { cn } from "~/lib/utils"; // Assuming you have a cn utility
|
|
|
|
// Define status type for better type safety if used elsewhere
|
|
export type UserStatusType = "online" | "dnd" | "idle" | "offline";
|
|
|
|
interface OnlineStatusProps extends React.ComponentProps<"div"> {
|
|
status: UserStatusType;
|
|
}
|
|
|
|
export function OnlineStatus({ status, className, ...rest }: OnlineStatusProps) {
|
|
const statusTitle = status.charAt(0).toUpperCase() + status.slice(1);
|
|
|
|
let statusIndicatorIcon: React.ReactNode = null;
|
|
|
|
switch (status) {
|
|
case "online":
|
|
statusIndicatorIcon = <Circle className="size-full fill-emerald-500 stroke-none" />;
|
|
break;
|
|
case "dnd":
|
|
statusIndicatorIcon = (
|
|
<MinusCircle className="size-full fill-red-500 stroke-background" strokeWidth={2.5} />
|
|
);
|
|
break;
|
|
case "idle":
|
|
statusIndicatorIcon = <Moon className="size-full fill-amber-400 stroke-amber-400" />;
|
|
break;
|
|
case "offline":
|
|
statusIndicatorIcon = <Circle className="size-full fill-transparent stroke-gray-500 stroke-[4px]" />;
|
|
break;
|
|
}
|
|
|
|
return (
|
|
<div className="relative inline-block align-middle">
|
|
<div className={className} {...rest} />
|
|
<div
|
|
title={statusTitle}
|
|
className={cn(
|
|
"absolute bottom-0 right-0 flex items-center justify-center",
|
|
"rounded-full bg-background",
|
|
"size-1/2 p-0.5",
|
|
)}
|
|
>
|
|
{statusIndicatorIcon}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/password-input.tsx
|
|
import { EyeIcon, EyeOffIcon } from "lucide-react";
|
|
import React from "react";
|
|
import { Button } from "../ui/button";
|
|
import { Input } from "../ui/input";
|
|
|
|
export function PasswordInput(props: React.ComponentProps<"input">) {
|
|
const [showPassword, setShowPassword] = React.useState(false);
|
|
const disabled = props.value === "" || props.value === undefined || props.disabled;
|
|
|
|
return (
|
|
<div className="relative">
|
|
<Input type={showPassword ? "text" : "password"} {...props} />
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
|
onClick={() => setShowPassword((prev) => !prev)}
|
|
disabled={disabled}
|
|
>
|
|
{showPassword && !disabled ? (
|
|
<EyeIcon className="h-4 w-4" aria-hidden="true" />
|
|
) : (
|
|
<EyeOffIcon className="h-4 w-4" aria-hidden="true" />
|
|
)}
|
|
<span className="sr-only">{showPassword ? "Hide password" : "Show password"}</span>
|
|
</Button>
|
|
<style>
|
|
{`
|
|
.hide-password-toggle::-ms-reveal,
|
|
.hide-password-toggle::-ms-clear {
|
|
visibility: hidden;
|
|
pointer-events: none;
|
|
display: none;
|
|
}
|
|
`}
|
|
</style>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/private-channel-list-item.tsx
|
|
import { Check } from "lucide-react";
|
|
import { NavLink } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { useFetchUsers } from "~/hooks/use-fetch-user";
|
|
import type { RecipientChannel } from "~/lib/api/types";
|
|
import { cn } from "~/lib/utils";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import { Badge } from "../ui/badge";
|
|
import { Button } from "../ui/button";
|
|
import UserAvatar from "../user-avatar";
|
|
import { OnlineStatus } from "./online-status";
|
|
|
|
interface PrivateChannelListItemProps {
|
|
channel: RecipientChannel;
|
|
}
|
|
|
|
export default function PrivateChannelListItem({ channel }: PrivateChannelListItemProps) {
|
|
const currentUserId = useUsersStore((state) => state.currentUserId);
|
|
|
|
const recipients = channel.recipients.filter((recipient) => recipient !== currentUserId);
|
|
|
|
useFetchUsers(recipients);
|
|
|
|
const recipientsUsers = useUsersStore(
|
|
useShallow((state) => recipients.map((recipient) => state.users[recipient]).filter(Boolean)),
|
|
);
|
|
|
|
const renderSystemBadge = recipientsUsers.some((recipient) => recipient.system) && recipients.length === 1;
|
|
|
|
return (
|
|
<>
|
|
<NavLink to={`/app/@me/channels/${channel.id}`}>
|
|
{({ isActive }) => (
|
|
<Button
|
|
variant="secondary"
|
|
size="none"
|
|
asChild
|
|
className={cn(
|
|
"w-full flex flex-row justify-start shadow-sm",
|
|
isActive ? "bg-accent hover:bg-accent" : "",
|
|
)}
|
|
>
|
|
<div className="flex items-center gap-2 max-w-72 p-2">
|
|
<div>
|
|
<OnlineStatus status="online">
|
|
<UserAvatar
|
|
user={recipientsUsers.find((recipient) => recipient.id !== currentUserId)}
|
|
/>
|
|
</OnlineStatus>
|
|
</div>
|
|
<div className="truncate">
|
|
{recipientsUsers
|
|
.map((recipient) => recipient.displayName || recipient.username)
|
|
.join(", ")}
|
|
</div>
|
|
{renderSystemBadge && (
|
|
<Badge variant="default">
|
|
{" "}
|
|
<Check /> System
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
</Button>
|
|
)}
|
|
</NavLink>
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/server-button.tsx
|
|
import { Avatar, AvatarFallback, AvatarImage } from "@radix-ui/react-avatar";
|
|
import { NavLink } from "react-router";
|
|
import type { Server } from "~/lib/api/types";
|
|
import { cn, getFirstLetters } from "~/lib/utils";
|
|
import { Button } from "../ui/button";
|
|
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
|
|
|
|
export interface ServerButtonProps {
|
|
server: Server;
|
|
}
|
|
|
|
export function ServerButton({ server }: ServerButtonProps) {
|
|
return (
|
|
<NavLink to={`/app/server/${server.id}`}>
|
|
{({ isActive }) => (
|
|
<Tooltip disableHoverableContent>
|
|
<TooltipTrigger asChild>
|
|
<Button
|
|
variant="outline"
|
|
size="none"
|
|
className={cn("overflow-hidden", isActive ? "bg-accent" : "")}
|
|
>
|
|
<div className="flex items-center justify-center size-12">
|
|
<Avatar className="rounded-none">
|
|
<AvatarImage src={server.iconUrl} className="rounded-none" />
|
|
<AvatarFallback>{getFirstLetters(server.name, 4)}</AvatarFallback>
|
|
</Avatar>
|
|
</div>
|
|
</Button>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="right">
|
|
<p className="text-xs">{server.name}</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
)}
|
|
</NavLink>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/settings-button.tsx
|
|
import { Settings } from "lucide-react";
|
|
import { useNavigate } from "react-router";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
import { Button } from "../ui/button";
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuItem,
|
|
DropdownMenuSeparator,
|
|
DropdownMenuTrigger,
|
|
} from "../ui/dropdown-menu";
|
|
|
|
export function SettingsButton() {
|
|
const setToken = useTokenStore((state) => state.setToken);
|
|
const navigate = useNavigate();
|
|
|
|
const onOpenSettings = () => {
|
|
navigate("/app/settings");
|
|
};
|
|
|
|
const onLogout = () => {
|
|
setToken(undefined);
|
|
window.location.reload();
|
|
};
|
|
|
|
return (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="ghost" size="icon">
|
|
<Settings className="size-5" />
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent>
|
|
<DropdownMenuItem onClick={onOpenSettings}>Settings</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuItem variant="destructive" onClick={onLogout}>
|
|
Logout
|
|
</DropdownMenuItem>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
);
|
|
}
|
|
|
|
// file: app/components/custom-ui/text-box.tsx
|
|
import React, { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
|
|
import { cn } from "~/lib/utils";
|
|
|
|
export interface TextBoxProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange" | "value"> {
|
|
value: string;
|
|
onChange: (value: string) => void;
|
|
placeholder?: string;
|
|
wrapperClassName?: string;
|
|
inputClassName?: string;
|
|
disabled?: boolean;
|
|
autoFocus?: boolean;
|
|
spellCheck?: boolean;
|
|
}
|
|
|
|
export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
|
(
|
|
{
|
|
value,
|
|
onChange,
|
|
placeholder,
|
|
wrapperClassName,
|
|
inputClassName,
|
|
disabled = false,
|
|
autoFocus = false,
|
|
spellCheck = true,
|
|
onInput,
|
|
onBlur,
|
|
onFocus,
|
|
...rest
|
|
},
|
|
ref,
|
|
) => {
|
|
const localRef = useRef<HTMLDivElement>(null);
|
|
useImperativeHandle(ref, () => localRef.current as HTMLDivElement);
|
|
|
|
// Function to handle DOM updates
|
|
const updateDOM = (newValue: string) => {
|
|
if (localRef.current) {
|
|
// Only update if different to avoid selection issues
|
|
if (localRef.current.textContent !== newValue) {
|
|
localRef.current.textContent = newValue;
|
|
|
|
// Clear any <br> elements if the content is empty
|
|
if (!newValue && localRef.current.innerHTML.includes("<br>")) {
|
|
localRef.current.innerHTML = "";
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
// Update DOM when value prop changes
|
|
useEffect(() => {
|
|
updateDOM(value);
|
|
}, [value]);
|
|
|
|
useEffect(() => {
|
|
if (autoFocus && localRef.current) {
|
|
localRef.current.focus();
|
|
}
|
|
}, [autoFocus]);
|
|
|
|
const handleInput = (event: React.FormEvent<HTMLDivElement>) => {
|
|
const newValue = event.currentTarget.textContent || "";
|
|
|
|
// Handle the case where the content is empty but contains a <br>
|
|
if (!newValue && event.currentTarget.innerHTML.includes("<br>")) {
|
|
event.currentTarget.innerHTML = "";
|
|
}
|
|
|
|
onChange(newValue);
|
|
onInput?.(event);
|
|
};
|
|
|
|
const handlePaste = (event: React.ClipboardEvent<HTMLDivElement>) => {
|
|
event.preventDefault();
|
|
const text = event.clipboardData.getData("text/plain");
|
|
|
|
// Use document.execCommand to maintain undo stack
|
|
document.execCommand("insertText", false, text);
|
|
|
|
// Manually trigger input event
|
|
const inputEvent = new Event("input", { bubbles: true });
|
|
event.currentTarget.dispatchEvent(inputEvent);
|
|
};
|
|
|
|
return (
|
|
<div
|
|
className={cn("overflow-y-auto overflow-x-hidden w-full min-h-6", wrapperClassName)}
|
|
onClick={() => localRef.current?.focus()}
|
|
>
|
|
<div
|
|
ref={localRef}
|
|
contentEditable={!disabled}
|
|
onInput={handleInput}
|
|
onPaste={handlePaste}
|
|
onBlur={onBlur}
|
|
onFocus={onFocus}
|
|
className={cn(
|
|
"outline-none break-all",
|
|
"empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:cursor-text",
|
|
disabled && "cursor-not-allowed opacity-50",
|
|
inputClassName,
|
|
)}
|
|
data-placeholder={placeholder}
|
|
role="textbox"
|
|
aria-multiline="true"
|
|
aria-disabled={disabled}
|
|
aria-placeholder={placeholder}
|
|
spellCheck={spellCheck}
|
|
suppressContentEditableWarning
|
|
tabIndex={0}
|
|
{...rest}
|
|
/>
|
|
</div>
|
|
);
|
|
},
|
|
);
|
|
|
|
TextBox.displayName = "TextBox";
|
|
|
|
export default TextBox;
|
|
|
|
// file: app/components/custom-ui/user-status.tsx
|
|
import { PhoneMissed, Signal } from "lucide-react";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { useServerChannelsStore } from "~/stores/server-channels-store";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import { useVoiceStateStore } from "~/stores/voice-state-store";
|
|
import { ThemeToggle } from "../theme/theme-toggle";
|
|
import { Button } from "../ui/button";
|
|
import { Separator } from "../ui/separator";
|
|
import UserAvatar from "../user-avatar";
|
|
import { OnlineStatus } from "./online-status";
|
|
import { SettingsButton } from "./settings-button";
|
|
|
|
function VoiceStatus({ voiceState }: { voiceState: { serverId: string; channelId: string } }) {
|
|
const leaveVoiceChannel = () => {
|
|
useVoiceStateStore.getState().leaveVoiceChannel();
|
|
};
|
|
|
|
const channel = useServerChannelsStore(
|
|
useShallow((state) => state.channels[voiceState.serverId]?.[voiceState.channelId]),
|
|
);
|
|
const server = useServerListStore(useShallow((state) => state.servers[voiceState.serverId]));
|
|
|
|
return (
|
|
<div className="gap-1 flex justify-between items-center ">
|
|
<div className="flex items-center gap-2 text-green-500">
|
|
<Signal className="size-5" />
|
|
<div className="truncate max-w-60 text-sm">
|
|
{channel?.name || "Unknown channel"} / {server?.name}
|
|
</div>
|
|
</div>
|
|
|
|
<Button variant="destructive" size="icon" onClick={leaveVoiceChannel}>
|
|
<PhoneMissed className="size-5" />
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function UserStatus() {
|
|
const user = useUsersStore((state) => state.getCurrentUser()!);
|
|
const voiceState = useVoiceStateStore((state) => state.activeChannel);
|
|
|
|
return (
|
|
<div className="outline-1 outline-none border border-input p-2 h-full rounded-xl flex flex-col gap-2 shadow-sm">
|
|
{voiceState && (
|
|
<>
|
|
<VoiceStatus voiceState={voiceState} />
|
|
<Separator />
|
|
</>
|
|
)}
|
|
<div className="flex justify-between items-center gap-2">
|
|
<div className="grow flex flex-row gap-2">
|
|
<OnlineStatus status="online">
|
|
<UserAvatar user={user} className="size-10" />
|
|
</OnlineStatus>
|
|
|
|
<div className="flex flex-col text-sm justify-center">
|
|
<div className="truncate max-w-30">{user?.displayName || user?.username || "Unknown user"}</div>
|
|
<span className="text-muted-foreground text-xs">@{user?.username}</span>
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<div className="flex flex-row-reverse gap-2 items-center">
|
|
<SettingsButton />
|
|
<ThemeToggle />
|
|
{/* <Button variant="secondary" size="none">
|
|
<Headphones className="size-5 m-1.5" />
|
|
</Button> */}
|
|
{/* <Button variant="secondary" size="none">
|
|
<Mic className="size-5 m-1.5" />
|
|
</Button> */}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/components/file-icon.tsx
|
|
import {
|
|
FileArchive,
|
|
FileAudio,
|
|
FileImage,
|
|
FileQuestion,
|
|
FileSpreadsheet,
|
|
FileText,
|
|
FileVideo,
|
|
type LucideProps,
|
|
} from "lucide-react";
|
|
|
|
interface FileIconProps extends LucideProps {
|
|
contentType: string;
|
|
className?: string;
|
|
}
|
|
|
|
export function FileIcon({ contentType, className, ...props }: FileIconProps) {
|
|
const commonProps = { className: className ?? "h-5 w-5", ...props };
|
|
|
|
if (contentType.startsWith("image/")) {
|
|
return <FileImage {...commonProps} />;
|
|
}
|
|
if (contentType.startsWith("audio/")) {
|
|
return <FileAudio {...commonProps} />;
|
|
}
|
|
if (contentType.startsWith("video/")) {
|
|
return <FileVideo {...commonProps} />;
|
|
}
|
|
if (contentType === "application/pdf") {
|
|
return <FileText {...commonProps} />;
|
|
}
|
|
if (
|
|
contentType.startsWith("application/vnd.ms-excel") ||
|
|
contentType.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml")
|
|
) {
|
|
return <FileSpreadsheet {...commonProps} />; // Could use a specific Excel icon if available/desired
|
|
}
|
|
if (
|
|
contentType.startsWith("application/msword") ||
|
|
contentType.startsWith("application/vnd.openxmlformats-officedocument.wordprocessingml")
|
|
) {
|
|
return <FileText {...commonProps} />;
|
|
}
|
|
if (
|
|
contentType.startsWith("application/vnd.ms-powerpoint") ||
|
|
contentType.startsWith("application/vnd.openxmlformats-officedocument.presentationml")
|
|
) {
|
|
return <FileText {...commonProps} />;
|
|
}
|
|
if (
|
|
contentType === "application/zip" ||
|
|
contentType === "application/x-rar-compressed" ||
|
|
contentType === "application/x-7z-compressed" ||
|
|
contentType === "application/gzip" ||
|
|
contentType === "application/x-tar"
|
|
) {
|
|
return <FileArchive {...commonProps} />;
|
|
}
|
|
if (contentType.startsWith("text/")) {
|
|
return <FileText {...commonProps} />;
|
|
}
|
|
return <FileQuestion {...commonProps} />; // Default for unknown types
|
|
}
|
|
|
|
// file: app/components/icons/Discord.tsx
|
|
import type { SVGProps } from "react";
|
|
|
|
const Discord = (props: SVGProps<SVGSVGElement>) => (
|
|
<svg
|
|
xmlns="http://www.w3.org/2000/svg"
|
|
width="1em"
|
|
height="1em"
|
|
preserveAspectRatio="xMidYMid"
|
|
viewBox="0 0 256 226"
|
|
{...props}
|
|
>
|
|
<path
|
|
fill="#1185FE"
|
|
d="M55.491 15.172c29.35 22.035 60.917 66.712 72.509 90.686 11.592-23.974 43.159-68.651 72.509-90.686C221.686-.727 256-13.028 256 26.116c0 7.818-4.482 65.674-7.111 75.068-9.138 32.654-42.436 40.983-72.057 35.942 51.775 8.812 64.946 38 36.501 67.187-54.021 55.433-77.644-13.908-83.696-31.676-1.11-3.257-1.63-4.78-1.637-3.485-.008-1.296-.527.228-1.637 3.485-6.052 17.768-29.675 87.11-83.696 31.676-28.445-29.187-15.274-58.375 36.5-67.187-29.62 5.041-62.918-3.288-72.056-35.942C4.482 91.79 0 33.934 0 26.116 0-13.028 34.314-.727 55.491 15.172Z"
|
|
/>
|
|
</svg>
|
|
);
|
|
|
|
export default Discord;
|
|
|
|
// file: app/components/manager/gateway-websocket-connection-manager.tsx
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import { useEffect } from "react";
|
|
import { ConnectionState } from "~/lib/websocket/gateway/types";
|
|
import { useGatewayStore } from "~/stores/gateway-store";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
|
|
export function GatewayWebSocketConnectionManager() {
|
|
const token = useTokenStore((state) => state.token);
|
|
|
|
const setQueryClient = useGatewayStore((state) => state.setQueryClient);
|
|
|
|
const queryClient = useQueryClient();
|
|
useEffect(() => {
|
|
setQueryClient(queryClient);
|
|
}, [queryClient]);
|
|
|
|
useEffect(() => {
|
|
const { status, connect, disconnect } = useGatewayStore.getState();
|
|
|
|
if (token) {
|
|
connect(token);
|
|
} else {
|
|
if (status === ConnectionState.CONNECTED) {
|
|
disconnect();
|
|
}
|
|
}
|
|
|
|
return () => {
|
|
if (status === ConnectionState.CONNECTED) {
|
|
disconnect();
|
|
}
|
|
};
|
|
}, [token]);
|
|
|
|
return null;
|
|
}
|
|
|
|
// file: app/components/manager/webrtc-connection-manager.tsx
|
|
import { useEffect, useRef } from "react";
|
|
import { ConnectionState } from "~/lib/websocket/voice/types";
|
|
import { useGatewayStore } from "~/stores/gateway-store";
|
|
import { useVoiceStateStore } from "~/stores/voice-state-store";
|
|
import { useWebRTCStore } from "~/stores/webrtc-store";
|
|
|
|
export function WebRTCConnectionManager() {
|
|
const gateway = useGatewayStore();
|
|
const voiceState = useVoiceStateStore();
|
|
const webrtc = useWebRTCStore();
|
|
|
|
const remoteStream = useWebRTCStore((state) => state.remoteStream);
|
|
const audioRef = useRef<HTMLAudioElement>(null);
|
|
|
|
if (audioRef.current) {
|
|
audioRef.current.srcObject = remoteStream;
|
|
}
|
|
|
|
useEffect(() => {
|
|
const unsubscribe = gateway.onVoiceServerUpdate(async (event) => {
|
|
await webrtc.connect(event.token);
|
|
voiceState.joinVoiceChannel(event.serverId, event.channelId);
|
|
|
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
audio: {
|
|
noiseSuppression: false,
|
|
},
|
|
video: false,
|
|
});
|
|
|
|
webrtc.createOffer(stream);
|
|
});
|
|
|
|
return () => {
|
|
voiceState.leaveVoiceChannel();
|
|
unsubscribe();
|
|
};
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (webrtc.status === ConnectionState.DISCONNECTED) {
|
|
voiceState.leaveVoiceChannel();
|
|
}
|
|
}, [webrtc.status]);
|
|
|
|
return (
|
|
<>
|
|
<audio autoPlay ref={audioRef} className="hidden" />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/components/message-box.tsx
|
|
import { Loader2, Paperclip, Send, X } from "lucide-react";
|
|
import React from "react";
|
|
import { FileIcon } from "~/components/file-icon"; // Adjust path
|
|
import { sendMessage } from "~/lib/api/client/channel"; // Adjust path
|
|
import { uploadFiles } from "~/lib/api/client/file"; // Adjust path
|
|
import type { Uuid } from "~/lib/api/types"; // Adjust path
|
|
import { cn, formatFileSize } from "~/lib/utils"; // Adjust path
|
|
import TextBox from "./custom-ui/text-box"; // Adjust path, assuming TextBox is in ./custom-ui/
|
|
import { Button } from "./ui/button"; // Adjust path
|
|
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip"; // Adjust path
|
|
|
|
export interface MessageBoxProps {
|
|
channelId: string;
|
|
}
|
|
|
|
export default function MessageBox({ channelId }: MessageBoxProps) {
|
|
const [text, setText] = React.useState("");
|
|
const [attachments, setAttachments] = React.useState<File[]>([]);
|
|
const [isLoading, setIsLoading] = React.useState(false);
|
|
|
|
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
|
const textBoxRef = React.useRef<HTMLDivElement>(null);
|
|
|
|
const handleSendMessage = async () => {
|
|
const content = text.trim();
|
|
if ((!content && attachments.length === 0) || isLoading) return;
|
|
|
|
setIsLoading(true);
|
|
try {
|
|
let uploadedAttachments: Uuid[] = [];
|
|
if (attachments.length > 0) {
|
|
uploadedAttachments = await uploadFiles(attachments);
|
|
}
|
|
await sendMessage(channelId, text, uploadedAttachments);
|
|
setText("");
|
|
setAttachments([]);
|
|
|
|
setTimeout(() => textBoxRef.current?.focus(), 0);
|
|
} catch (error) {
|
|
console.error("Failed to send message:", error);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const addAttachment = () => {
|
|
if (attachments.length >= 10 || isLoading) return;
|
|
fileInputRef.current?.click();
|
|
};
|
|
|
|
const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const files = Array.from(e.target.files || []);
|
|
if (files.length === 0) return;
|
|
|
|
setAttachments((prev) => {
|
|
const newAttachments = [...prev, ...files];
|
|
return newAttachments.slice(0, 10);
|
|
});
|
|
|
|
if (fileInputRef.current) {
|
|
fileInputRef.current.value = "";
|
|
}
|
|
setTimeout(() => textBoxRef.current?.focus(), 0);
|
|
};
|
|
|
|
const removeAttachment = (indexToRemove: number) => {
|
|
setAttachments((prev) => prev.filter((_, i) => i !== indexToRemove));
|
|
setTimeout(() => textBoxRef.current?.focus(), 0);
|
|
};
|
|
|
|
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
|
|
if (e.key === "Enter" && !e.shiftKey) {
|
|
e.preventDefault();
|
|
handleSendMessage();
|
|
}
|
|
};
|
|
|
|
React.useEffect(() => {
|
|
setText("");
|
|
setAttachments([]);
|
|
setIsLoading(false);
|
|
setTimeout(() => textBoxRef.current?.focus(), 0);
|
|
}, [channelId]);
|
|
|
|
const canSend = (text.trim().length > 0 || attachments.length > 0) && !isLoading;
|
|
const attachmentsRemaining = 10 - attachments.length;
|
|
|
|
return (
|
|
<div className="border-t bg-background p-2">
|
|
{attachments.length > 0 && (
|
|
<div className="mb-2 max-h-44 space-y-2 overflow-y-auto rounded-md border bg-muted/20 p-2 scrollbar-thin scrollbar-thumb-muted-foreground/30 scrollbar-track-transparent">
|
|
{attachments.map((file, i) => (
|
|
<div
|
|
key={`${file.name}-${file.lastModified}-${i}`}
|
|
className="flex items-center gap-2.5 rounded-md border bg-card p-2 text-sm shadow-sm"
|
|
>
|
|
<FileIcon contentType={file.type} className="h-7 w-7 flex-shrink-0 text-muted-foreground" />
|
|
<div className="min-w-0 flex-1">
|
|
<p className="font-medium text-card-foreground">{file.name}</p>
|
|
<p className="text-xs text-muted-foreground">{formatFileSize(file.size)}</p>
|
|
</div>
|
|
<Tooltip disableHoverableContent>
|
|
<TooltipTrigger asChild>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-7 w-7 flex-shrink-0 text-muted-foreground hover:text-destructive"
|
|
onClick={() => removeAttachment(i)}
|
|
disabled={isLoading}
|
|
aria-label={`Remove ${file.name}`}
|
|
>
|
|
<X className="h-4 w-4" />
|
|
</Button>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="top">
|
|
<p>Remove attachment</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
<div
|
|
className={cn(
|
|
"grid gap-x-2 rounded-xl border bg-card p-2.5 shadow-sm transition-all",
|
|
"focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/30",
|
|
)}
|
|
style={{
|
|
gridTemplateColumns: "auto 1fr auto",
|
|
gridTemplateRows: "auto 1fr",
|
|
}}
|
|
>
|
|
<Tooltip disableHoverableContent>
|
|
<TooltipTrigger asChild>
|
|
<div className="self-start row-start-1 col-start-1 row-span-2 col-span-1">
|
|
<input
|
|
type="file"
|
|
multiple
|
|
className="hidden"
|
|
ref={fileInputRef}
|
|
onChange={onFileChange}
|
|
accept="image/*,application/pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar,audio/*,video/*"
|
|
disabled={isLoading}
|
|
/>
|
|
<Button
|
|
type="button"
|
|
size="icon"
|
|
variant="ghost"
|
|
onClick={addAttachment}
|
|
disabled={attachments.length >= 10 || isLoading}
|
|
aria-label="Add attachment"
|
|
>
|
|
<Paperclip className="h-5 w-5" />
|
|
</Button>
|
|
</div>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="top">
|
|
{attachments.length >= 10 ? (
|
|
<p>Maximum 10 attachments</p>
|
|
) : (
|
|
<p>Add attachment ({attachmentsRemaining} remaining)</p>
|
|
)}
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
|
|
<div className="self-center row-start-1 col-start-2 row-span-2 col-span-1">
|
|
<TextBox
|
|
ref={textBoxRef}
|
|
value={text}
|
|
onChange={setText}
|
|
placeholder="Message..."
|
|
aria-label="Message input"
|
|
onKeyDown={handleKeyDown}
|
|
wrapperClassName="max-h-40"
|
|
disabled={isLoading}
|
|
/>
|
|
</div>
|
|
|
|
<div className="self-start row-start-1 col-start-3 row-span-2 col-span-1">
|
|
<Button
|
|
type="button"
|
|
size="icon"
|
|
onClick={handleSendMessage}
|
|
disabled={!canSend}
|
|
aria-label="Send message"
|
|
>
|
|
{isLoading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Send className="h-5 w-5" />}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/components/modals/create-server-channel-modal.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import { ChannelType } from "~/lib/api/types";
|
|
import { ModalType, useModalStore, type CreateServerChannelModalData } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "../ui/dialog";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
|
import { Input } from "../ui/input";
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
|
|
|
|
const schema = z.object({
|
|
name: z.string().min(1).max(32),
|
|
type: z.nativeEnum(ChannelType),
|
|
});
|
|
|
|
export default function CreateServerChannelModal() {
|
|
const { type, data, isOpen, onClose } = useModalStore();
|
|
|
|
const isModalOpen = type === ModalType.CREATE_SERVER_CHANNEL && isOpen;
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
defaultValues: {
|
|
type: ChannelType.SERVER_TEXT,
|
|
},
|
|
});
|
|
|
|
const onOpenChange = () => {
|
|
form.reset();
|
|
onClose();
|
|
};
|
|
|
|
const onSubmit = async (values: z.infer<typeof schema>) => {
|
|
await import("~/lib/api/client/server").then((m) =>
|
|
m.default.createChannel((data as CreateServerChannelModalData["data"]).serverId, values),
|
|
);
|
|
|
|
form.reset();
|
|
onClose();
|
|
};
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Create channel</DialogTitle>
|
|
<DialogDescription>Give your channel a name and choose a channel type.</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
|
<FormField
|
|
control={form.control}
|
|
name="name"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="type"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.type.isOptional()}>Type</FormLabel>
|
|
<Select defaultValue={field.value} onValueChange={field.onChange}>
|
|
<FormControl>
|
|
<SelectTrigger className="w-full">
|
|
<SelectValue placeholder="Select a channel type" />
|
|
</SelectTrigger>
|
|
</FormControl>
|
|
<SelectContent>
|
|
{Object.entries({
|
|
[ChannelType.SERVER_TEXT]: "Text",
|
|
[ChannelType.SERVER_VOICE]: "Voice",
|
|
}).map(([type, label]) => (
|
|
<SelectItem key={type} value={type}>
|
|
{label}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<DialogFooter className=" justify-between">
|
|
<DialogClose asChild>
|
|
<Button type="button" variant="secondary">
|
|
Close
|
|
</Button>
|
|
</DialogClose>
|
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
|
{form.formState.isSubmitting ? "Creating..." : "Create"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</Form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
// file: app/components/modals/create-server-invite-modal.tsx
|
|
import { Check, Copy, RefreshCw } from "lucide-react";
|
|
import React from "react";
|
|
import { useOrigin } from "~/hooks/use-origin";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
|
import { Input } from "../ui/input";
|
|
import { Label } from "../ui/label";
|
|
|
|
export default function CreateServerInviteModal() {
|
|
const { type, data, isOpen, onClose } = useModalStore();
|
|
const [inviteCode, setInviteCode] = React.useState<string | undefined>(undefined);
|
|
const origin = useOrigin();
|
|
const [isCopied, setCopied] = React.useState(false);
|
|
|
|
const isModalOpen = type === ModalType.CREATE_SERVER_INVITE && isOpen;
|
|
const inviteLink = `${origin}/app/invite/${inviteCode}`;
|
|
|
|
const onOpenChange = () => {
|
|
onClose();
|
|
};
|
|
|
|
const regenerateInviteCode = () => {
|
|
import("~/lib/api/client/server")
|
|
.then((m) => m.default.createInvite((data as { serverId: string }).serverId))
|
|
.then((invite) => {
|
|
setInviteCode(invite.code);
|
|
});
|
|
};
|
|
|
|
const onCopy = () => {
|
|
navigator.clipboard.writeText(inviteLink);
|
|
setCopied(true);
|
|
|
|
setTimeout(() => setCopied(false), 1000);
|
|
};
|
|
|
|
React.useEffect(() => {
|
|
if (isModalOpen) {
|
|
import("~/lib/api/client/server")
|
|
.then((m) => m.default.createInvite((data as { serverId: string }).serverId))
|
|
.then((invite) => {
|
|
setInviteCode(invite.code);
|
|
});
|
|
} else {
|
|
setInviteCode(undefined);
|
|
}
|
|
}, [isModalOpen]);
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Invite your friends</DialogTitle>
|
|
</DialogHeader>
|
|
|
|
<Label>Server invite link</Label>
|
|
<div className="flex items-center gap-x-2">
|
|
<Input value={inviteLink} readOnly />
|
|
<Button variant="ghost" size="icon" onClick={onCopy}>
|
|
{isCopied ? <Check className="size-4" /> : <Copy className="size-4" />}
|
|
</Button>
|
|
</div>
|
|
<DialogFooter>
|
|
<Button variant="link" size="none" className="h-9 py-2" onClick={regenerateInviteCode}>
|
|
Generate a new invite
|
|
<RefreshCw />
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
// file: app/components/modals/create-server-modal.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import file from "~/lib/api/client/file";
|
|
import server from "~/lib/api/client/server";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "../ui/dialog";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
|
import { IconUploadField } from "../ui/icon-upload-field";
|
|
import { Input } from "../ui/input";
|
|
|
|
const schema = z.object({
|
|
name: z.string().min(1).max(32),
|
|
icon: z.instanceof(File).optional(),
|
|
});
|
|
|
|
export default function CreateServerModal() {
|
|
const { type, isOpen, onClose } = useModalStore();
|
|
|
|
const isModalOpen = type === ModalType.CREATE_SERVER && isOpen;
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
});
|
|
|
|
const onOpenChange = () => {
|
|
form.reset();
|
|
onClose();
|
|
};
|
|
|
|
const onSubmit = async (values: z.infer<typeof schema>) => {
|
|
let iconId = undefined;
|
|
if (values.icon) {
|
|
iconId = (await file.uploadFile(values.icon))[0];
|
|
}
|
|
|
|
await server.create({
|
|
name: values.name,
|
|
iconId,
|
|
});
|
|
|
|
form.reset();
|
|
onClose();
|
|
};
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Create server</DialogTitle>
|
|
<DialogDescription>Give your server a name and choose a server icon.</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
|
<FormField
|
|
control={form.control}
|
|
name="icon"
|
|
render={({ field, fieldState }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.icon.isOptional()}>Icon</FormLabel>
|
|
<FormControl>
|
|
<div className="flex flex-col items-center justify-center">
|
|
<IconUploadField field={field} error={fieldState.error} />
|
|
</div>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="name"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<DialogFooter className=" justify-between">
|
|
<DialogClose asChild>
|
|
<Button type="button" variant="secondary">
|
|
Close
|
|
</Button>
|
|
</DialogClose>
|
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
|
{form.formState.isSubmitting ? "Creating..." : "Create"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</Form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
// file: app/components/modals/delete-server-confirm-modal.tsx
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
|
|
|
export default function DeleteServerConfirmModal() {
|
|
const { type, data, isOpen, onClose } = useModalStore();
|
|
|
|
const isModalOpen = type === ModalType.DELETE_SERVER_CONFIRM && isOpen;
|
|
|
|
const onOpenChange = () => {
|
|
onClose();
|
|
};
|
|
|
|
const onConfirm = async () => {
|
|
await import("~/lib/api/client/server").then((m) => m.default.deleteServer((data as { serverId: string }).serverId));
|
|
onClose();
|
|
};
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Are you sure?</DialogTitle>
|
|
<DialogDescription>This action cannot be undone.</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<DialogFooter className="justify-between">
|
|
<Button variant="default" onClick={onClose}>
|
|
No
|
|
</Button>
|
|
<Button variant="destructive" onClick={onConfirm}>
|
|
Yes
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
// file: app/components/modals/update-profile-modal.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import file from "~/lib/api/client/file";
|
|
import { patchUser } from "~/lib/api/client/user";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import { Button } from "../ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "../ui/dialog";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
|
import { IconUploadField } from "../ui/icon-upload-field";
|
|
import { Input } from "../ui/input";
|
|
|
|
const schema = z.object({
|
|
displayName: z.string().min(1).max(32).optional().nullable(),
|
|
avatar: z.instanceof(File).optional().nullable(),
|
|
});
|
|
|
|
export default function UpdateProfileModal() {
|
|
const { type, isOpen, onClose } = useModalStore();
|
|
const user = useUsersStore(useShallow((state) => state.getCurrentUser()));
|
|
|
|
const isModalOpen = type === ModalType.UPDATE_PROFILE && isOpen;
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
});
|
|
|
|
const onOpenChange = () => {
|
|
form.reset();
|
|
onClose();
|
|
};
|
|
|
|
const onSubmit = async (values: z.infer<typeof schema>) => {
|
|
console.log("values", values);
|
|
|
|
if (!values) return;
|
|
|
|
let avatarId: string | null | undefined = values.avatar === null ? null : undefined;
|
|
if (values.avatar) {
|
|
avatarId = (await file.uploadFile(values.avatar))[0];
|
|
}
|
|
|
|
await patchUser({
|
|
displayName: values.displayName,
|
|
avatarId,
|
|
});
|
|
|
|
form.reset();
|
|
onClose();
|
|
};
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Update profile</DialogTitle>
|
|
<DialogDescription>Update your profile.</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
|
<FormField
|
|
control={form.control}
|
|
name="avatar"
|
|
render={({ field, fieldState }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.avatar.isOptional()}>Avatar</FormLabel>
|
|
<FormControl>
|
|
<div className="flex flex-col items-center justify-center">
|
|
<IconUploadField
|
|
defaultPreview={user?.avatarUrl}
|
|
formDefaultValue={user?.avatarUrl}
|
|
field={field}
|
|
error={fieldState.error}
|
|
/>
|
|
</div>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="displayName"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.displayName.isOptional()}>
|
|
Display Name
|
|
</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} placeholder={user?.displayName} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<DialogFooter className=" justify-between">
|
|
<DialogClose asChild>
|
|
<Button type="button" variant="secondary">
|
|
Close
|
|
</Button>
|
|
</DialogClose>
|
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
|
{form.formState.isSubmitting ? "Updating..." : "Update"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</Form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
// file: app/components/providers/modal-provider.tsx
|
|
import React from "react";
|
|
import CreateServerChannelModal from "../modals/create-server-channel-modal";
|
|
import CreateServerInviteModal from "../modals/create-server-invite-modal";
|
|
import CreateServerModal from "../modals/create-server-modal";
|
|
import DeleteServerConfirmModal from "../modals/delete-server-confirm-modal";
|
|
import UpdateProfileModal from "../modals/update-profile-modal";
|
|
|
|
export default function ModalProvider() {
|
|
const [isMounted, setIsMounted] = React.useState(false);
|
|
|
|
React.useEffect(() => {
|
|
setIsMounted(true);
|
|
}, []);
|
|
|
|
if (!isMounted) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<CreateServerModal />
|
|
<CreateServerChannelModal />
|
|
<CreateServerInviteModal />
|
|
<DeleteServerConfirmModal />
|
|
<UpdateProfileModal />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/components/theme/theme-provider.tsx
|
|
import { createContext, useContext, useEffect, useState } from "react";
|
|
|
|
export type Theme = "dark" | "light" | "system";
|
|
|
|
type ThemeProviderProps = {
|
|
children: React.ReactNode;
|
|
defaultTheme?: Theme;
|
|
storageKey?: string;
|
|
};
|
|
|
|
type ThemeProviderState = {
|
|
theme: Theme;
|
|
setTheme: (theme: Theme) => void;
|
|
};
|
|
|
|
const initialState: ThemeProviderState = {
|
|
theme: "system",
|
|
setTheme: () => null,
|
|
};
|
|
|
|
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
|
|
|
export function ThemeProvider({
|
|
children,
|
|
defaultTheme = "system",
|
|
storageKey = "ui-theme",
|
|
...props
|
|
}: ThemeProviderProps) {
|
|
const [theme, setTheme] = useState<Theme>(() => (localStorage.getItem(storageKey) as Theme) || defaultTheme);
|
|
|
|
useEffect(() => {
|
|
const root = window.document.documentElement;
|
|
|
|
root.classList.remove("light", "dark");
|
|
|
|
if (theme === "system") {
|
|
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
|
|
|
root.classList.add(systemTheme);
|
|
return;
|
|
}
|
|
|
|
root.classList.add(theme);
|
|
}, [theme]);
|
|
|
|
const value = {
|
|
theme,
|
|
setTheme: (theme: Theme) => {
|
|
localStorage.setItem(storageKey, theme);
|
|
setTheme(theme);
|
|
},
|
|
};
|
|
|
|
return (
|
|
<ThemeProviderContext.Provider {...props} value={value}>
|
|
{children}
|
|
</ThemeProviderContext.Provider>
|
|
);
|
|
}
|
|
|
|
export const useTheme = () => {
|
|
const context = useContext(ThemeProviderContext);
|
|
|
|
if (context === undefined) throw new Error("useTheme must be used within a ThemeProvider");
|
|
|
|
return context;
|
|
};
|
|
|
|
// file: app/components/theme/theme-toggle.tsx
|
|
import { Moon, Sun } from "lucide-react";
|
|
|
|
import { useTheme, type Theme } from "~/components/theme/theme-provider";
|
|
import { Button } from "~/components/ui/button";
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuRadioGroup,
|
|
DropdownMenuRadioItem,
|
|
DropdownMenuTrigger,
|
|
} from "~/components/ui/dropdown-menu";
|
|
|
|
export function ThemeToggle() {
|
|
const { theme, setTheme } = useTheme();
|
|
|
|
return (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="outline" size="icon">
|
|
<Sun className="size-5 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
|
<Moon className="absolute size-5 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
|
<span className="sr-only">Toggle theme</span>
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent>
|
|
<DropdownMenuRadioGroup value={theme} onValueChange={(value) => setTheme(value as Theme)}>
|
|
<DropdownMenuRadioItem value="light">Light</DropdownMenuRadioItem>
|
|
<DropdownMenuRadioItem value="dark">Dark</DropdownMenuRadioItem>
|
|
<DropdownMenuRadioItem value="system">System</DropdownMenuRadioItem>
|
|
</DropdownMenuRadioGroup>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
);
|
|
}
|
|
|
|
// file: app/components/ui/aspect-ratio.tsx
|
|
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
|
|
|
|
function AspectRatio({ ...props }: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
|
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />;
|
|
}
|
|
|
|
export { AspectRatio };
|
|
|
|
// file: app/components/ui/avatar.tsx
|
|
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
|
return (
|
|
<AvatarPrimitive.Root
|
|
data-slot="avatar"
|
|
className={cn("relative flex size-8 shrink-0 overflow-hidden rounded-full", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
|
return (
|
|
<AvatarPrimitive.Image
|
|
data-slot="avatar-image"
|
|
className={cn("aspect-square size-full", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function AvatarFallback({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
|
return (
|
|
<AvatarPrimitive.Fallback
|
|
data-slot="avatar-fallback"
|
|
className={cn("bg-muted flex size-full items-center justify-center rounded-full", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export { Avatar, AvatarFallback, AvatarImage };
|
|
|
|
// file: app/components/ui/badge.tsx
|
|
import * as React from "react";
|
|
import { Slot } from "@radix-ui/react-slot";
|
|
import { cva, type VariantProps } from "class-variance-authority";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
const badgeVariants = cva(
|
|
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
|
{
|
|
variants: {
|
|
variant: {
|
|
default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
|
secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
|
destructive:
|
|
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
|
outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
|
},
|
|
},
|
|
defaultVariants: {
|
|
variant: "default",
|
|
},
|
|
},
|
|
);
|
|
|
|
function Badge({
|
|
className,
|
|
variant,
|
|
asChild = false,
|
|
...props
|
|
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
|
const Comp = asChild ? Slot : "span";
|
|
|
|
return <Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props} />;
|
|
}
|
|
|
|
export { Badge, badgeVariants };
|
|
|
|
// file: app/components/ui/button.tsx
|
|
import { Slot } from "@radix-ui/react-slot";
|
|
import { cva, type VariantProps } from "class-variance-authority";
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
const buttonVariants = cva(
|
|
"flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
|
{
|
|
variants: {
|
|
variant: {
|
|
default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
|
destructive:
|
|
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
|
outline:
|
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
|
secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
|
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
|
link: "text-primary underline-offset-4 hover:underline",
|
|
},
|
|
size: {
|
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
|
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
|
icon: "size-9",
|
|
none: "",
|
|
},
|
|
},
|
|
defaultVariants: {
|
|
variant: "default",
|
|
size: "default",
|
|
},
|
|
},
|
|
);
|
|
|
|
function Button({
|
|
className,
|
|
variant,
|
|
size,
|
|
asChild = false,
|
|
...props
|
|
}: React.ComponentProps<"button"> &
|
|
VariantProps<typeof buttonVariants> & {
|
|
asChild?: boolean;
|
|
}) {
|
|
const Comp = asChild ? Slot : "button";
|
|
|
|
return <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} />;
|
|
}
|
|
|
|
export { Button, buttonVariants };
|
|
|
|
// file: app/components/ui/card.tsx
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card"
|
|
className={cn(
|
|
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-header"
|
|
className={cn(
|
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|
return <div data-slot="card-title" className={cn("leading-none font-semibold", className)} {...props} />;
|
|
}
|
|
|
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
|
return <div data-slot="card-description" className={cn("text-muted-foreground text-sm", className)} {...props} />;
|
|
}
|
|
|
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-action"
|
|
className={cn("col-start-2 row-span-2 row-start-1 self-start justify-self-end", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
|
return <div data-slot="card-content" className={cn("px-6", className)} {...props} />;
|
|
}
|
|
|
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div data-slot="card-footer" className={cn("flex items-center px-6 [.border-t]:pt-6", className)} {...props} />
|
|
);
|
|
}
|
|
|
|
export { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle };
|
|
|
|
// file: app/components/ui/context-menu.tsx
|
|
import * as React from "react";
|
|
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
|
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
|
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />;
|
|
}
|
|
|
|
function ContextMenuTrigger({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
|
return <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />;
|
|
}
|
|
|
|
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
|
return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />;
|
|
}
|
|
|
|
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
|
return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />;
|
|
}
|
|
|
|
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
|
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />;
|
|
}
|
|
|
|
function ContextMenuRadioGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
|
return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />;
|
|
}
|
|
|
|
function ContextMenuSubTrigger({
|
|
className,
|
|
inset,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
|
inset?: boolean;
|
|
}) {
|
|
return (
|
|
<ContextMenuPrimitive.SubTrigger
|
|
data-slot="context-menu-sub-trigger"
|
|
data-inset={inset}
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<ChevronRightIcon className="ml-auto" />
|
|
</ContextMenuPrimitive.SubTrigger>
|
|
);
|
|
}
|
|
|
|
function ContextMenuSubContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
|
return (
|
|
<ContextMenuPrimitive.SubContent
|
|
data-slot="context-menu-sub-content"
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function ContextMenuContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
|
return (
|
|
<ContextMenuPrimitive.Portal>
|
|
<ContextMenuPrimitive.Content
|
|
data-slot="context-menu-content"
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
</ContextMenuPrimitive.Portal>
|
|
);
|
|
}
|
|
|
|
function ContextMenuItem({
|
|
className,
|
|
inset,
|
|
variant = "default",
|
|
...props
|
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
|
inset?: boolean;
|
|
variant?: "default" | "destructive";
|
|
}) {
|
|
return (
|
|
<ContextMenuPrimitive.Item
|
|
data-slot="context-menu-item"
|
|
data-inset={inset}
|
|
data-variant={variant}
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function ContextMenuCheckboxItem({
|
|
className,
|
|
children,
|
|
checked,
|
|
...props
|
|
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
|
return (
|
|
<ContextMenuPrimitive.CheckboxItem
|
|
data-slot="context-menu-checkbox-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
checked={checked}
|
|
{...props}
|
|
>
|
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
|
<ContextMenuPrimitive.ItemIndicator>
|
|
<CheckIcon className="size-4" />
|
|
</ContextMenuPrimitive.ItemIndicator>
|
|
</span>
|
|
{children}
|
|
</ContextMenuPrimitive.CheckboxItem>
|
|
);
|
|
}
|
|
|
|
function ContextMenuRadioItem({
|
|
className,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
|
return (
|
|
<ContextMenuPrimitive.RadioItem
|
|
data-slot="context-menu-radio-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
|
<ContextMenuPrimitive.ItemIndicator>
|
|
<CircleIcon className="size-2 fill-current" />
|
|
</ContextMenuPrimitive.ItemIndicator>
|
|
</span>
|
|
{children}
|
|
</ContextMenuPrimitive.RadioItem>
|
|
);
|
|
}
|
|
|
|
function ContextMenuLabel({
|
|
className,
|
|
inset,
|
|
...props
|
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
|
inset?: boolean;
|
|
}) {
|
|
return (
|
|
<ContextMenuPrimitive.Label
|
|
data-slot="context-menu-label"
|
|
data-inset={inset}
|
|
className={cn("text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function ContextMenuSeparator({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
|
return (
|
|
<ContextMenuPrimitive.Separator
|
|
data-slot="context-menu-separator"
|
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
|
|
return (
|
|
<span
|
|
data-slot="context-menu-shortcut"
|
|
className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export {
|
|
ContextMenu,
|
|
ContextMenuTrigger,
|
|
ContextMenuContent,
|
|
ContextMenuItem,
|
|
ContextMenuCheckboxItem,
|
|
ContextMenuRadioItem,
|
|
ContextMenuLabel,
|
|
ContextMenuSeparator,
|
|
ContextMenuShortcut,
|
|
ContextMenuGroup,
|
|
ContextMenuPortal,
|
|
ContextMenuSub,
|
|
ContextMenuSubContent,
|
|
ContextMenuSubTrigger,
|
|
ContextMenuRadioGroup,
|
|
};
|
|
|
|
// file: app/components/ui/dialog.tsx
|
|
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
|
import { XIcon } from "lucide-react";
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
|
}
|
|
|
|
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
|
}
|
|
|
|
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
|
}
|
|
|
|
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
|
}
|
|
|
|
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
|
return (
|
|
<DialogPrimitive.Overlay
|
|
data-slot="dialog-overlay"
|
|
className={cn(
|
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DialogContent({ className, children, ...props }: React.ComponentProps<typeof DialogPrimitive.Content>) {
|
|
return (
|
|
<DialogPortal data-slot="dialog-portal">
|
|
<DialogOverlay />
|
|
<DialogPrimitive.Content
|
|
data-slot="dialog-content"
|
|
className={cn(
|
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
|
<XIcon />
|
|
<span className="sr-only">Close</span>
|
|
</DialogPrimitive.Close>
|
|
</DialogPrimitive.Content>
|
|
</DialogPortal>
|
|
);
|
|
}
|
|
|
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="dialog-header"
|
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="dialog-footer"
|
|
className={cn("flex flex-col-reverse gap-2 sm:flex-row", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
|
return (
|
|
<DialogPrimitive.Title
|
|
data-slot="dialog-title"
|
|
className={cn("text-lg leading-none font-semibold", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
|
return (
|
|
<DialogPrimitive.Description
|
|
data-slot="dialog-description"
|
|
className={cn("text-muted-foreground text-sm", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export {
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogOverlay,
|
|
DialogPortal,
|
|
DialogTitle,
|
|
DialogTrigger,
|
|
};
|
|
|
|
// file: app/components/ui/dropdown-menu.tsx
|
|
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
|
}
|
|
|
|
function DropdownMenuPortal({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
|
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
|
|
}
|
|
|
|
function DropdownMenuTrigger({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
|
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
|
|
}
|
|
|
|
function DropdownMenuContent({
|
|
className,
|
|
sideOffset = 4,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
|
return (
|
|
<DropdownMenuPrimitive.Portal>
|
|
<DropdownMenuPrimitive.Content
|
|
data-slot="dropdown-menu-content"
|
|
sideOffset={sideOffset}
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
</DropdownMenuPrimitive.Portal>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
|
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
|
|
}
|
|
|
|
function DropdownMenuItem({
|
|
className,
|
|
inset,
|
|
variant = "default",
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
|
inset?: boolean;
|
|
variant?: "default" | "destructive";
|
|
}) {
|
|
return (
|
|
<DropdownMenuPrimitive.Item
|
|
data-slot="dropdown-menu-item"
|
|
data-inset={inset}
|
|
data-variant={variant}
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuCheckboxItem({
|
|
className,
|
|
children,
|
|
checked,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
|
return (
|
|
<DropdownMenuPrimitive.CheckboxItem
|
|
data-slot="dropdown-menu-checkbox-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
checked={checked}
|
|
{...props}
|
|
>
|
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
|
<DropdownMenuPrimitive.ItemIndicator>
|
|
<CheckIcon className="size-4" />
|
|
</DropdownMenuPrimitive.ItemIndicator>
|
|
</span>
|
|
{children}
|
|
</DropdownMenuPrimitive.CheckboxItem>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuRadioGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
|
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
|
|
}
|
|
|
|
function DropdownMenuRadioItem({
|
|
className,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
|
return (
|
|
<DropdownMenuPrimitive.RadioItem
|
|
data-slot="dropdown-menu-radio-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
|
<DropdownMenuPrimitive.ItemIndicator>
|
|
<CircleIcon className="size-2 fill-current" />
|
|
</DropdownMenuPrimitive.ItemIndicator>
|
|
</span>
|
|
{children}
|
|
</DropdownMenuPrimitive.RadioItem>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuLabel({
|
|
className,
|
|
inset,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
|
inset?: boolean;
|
|
}) {
|
|
return (
|
|
<DropdownMenuPrimitive.Label
|
|
data-slot="dropdown-menu-label"
|
|
data-inset={inset}
|
|
className={cn("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuSeparator({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
|
return (
|
|
<DropdownMenuPrimitive.Separator
|
|
data-slot="dropdown-menu-separator"
|
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
|
|
return (
|
|
<span
|
|
data-slot="dropdown-menu-shortcut"
|
|
className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
|
}
|
|
|
|
function DropdownMenuSubTrigger({
|
|
className,
|
|
inset,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
|
inset?: boolean;
|
|
}) {
|
|
return (
|
|
<DropdownMenuPrimitive.SubTrigger
|
|
data-slot="dropdown-menu-sub-trigger"
|
|
data-inset={inset}
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<ChevronRightIcon className="ml-auto size-4" />
|
|
</DropdownMenuPrimitive.SubTrigger>
|
|
);
|
|
}
|
|
|
|
function DropdownMenuSubContent({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
|
return (
|
|
<DropdownMenuPrimitive.SubContent
|
|
data-slot="dropdown-menu-sub-content"
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export {
|
|
DropdownMenu,
|
|
DropdownMenuCheckboxItem,
|
|
DropdownMenuContent,
|
|
DropdownMenuGroup,
|
|
DropdownMenuItem,
|
|
DropdownMenuLabel,
|
|
DropdownMenuPortal,
|
|
DropdownMenuRadioGroup,
|
|
DropdownMenuRadioItem,
|
|
DropdownMenuSeparator,
|
|
DropdownMenuShortcut,
|
|
DropdownMenuSub,
|
|
DropdownMenuSubContent,
|
|
DropdownMenuSubTrigger,
|
|
DropdownMenuTrigger,
|
|
};
|
|
|
|
// file: app/components/ui/form.tsx
|
|
import * as LabelPrimitive from "@radix-ui/react-label";
|
|
import { Slot } from "@radix-ui/react-slot";
|
|
import * as React from "react";
|
|
import {
|
|
Controller,
|
|
FormProvider,
|
|
useFormContext,
|
|
useFormState,
|
|
type ControllerProps,
|
|
type FieldPath,
|
|
type FieldValues,
|
|
} from "react-hook-form";
|
|
|
|
import { Label } from "~/components/ui/label";
|
|
import { cn } from "~/lib/utils";
|
|
|
|
const Form = FormProvider;
|
|
|
|
type FormFieldContextValue<
|
|
TFieldValues extends FieldValues = FieldValues,
|
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
|
> = {
|
|
name: TName;
|
|
};
|
|
|
|
const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue);
|
|
|
|
const FormField = <
|
|
TFieldValues extends FieldValues = FieldValues,
|
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
|
>({
|
|
...props
|
|
}: ControllerProps<TFieldValues, TName>) => {
|
|
return (
|
|
<FormFieldContext.Provider value={{ name: props.name }}>
|
|
<Controller {...props} />
|
|
</FormFieldContext.Provider>
|
|
);
|
|
};
|
|
|
|
const useFormField = () => {
|
|
const fieldContext = React.useContext(FormFieldContext);
|
|
const itemContext = React.useContext(FormItemContext);
|
|
const { getFieldState } = useFormContext();
|
|
const formState = useFormState({ name: fieldContext.name });
|
|
const fieldState = getFieldState(fieldContext.name, formState);
|
|
|
|
if (!fieldContext) {
|
|
throw new Error("useFormField should be used within <FormField>");
|
|
}
|
|
|
|
const { id } = itemContext;
|
|
|
|
return {
|
|
id,
|
|
name: fieldContext.name,
|
|
formItemId: `${id}-form-item`,
|
|
formDescriptionId: `${id}-form-item-description`,
|
|
formMessageId: `${id}-form-item-message`,
|
|
...fieldState,
|
|
};
|
|
};
|
|
|
|
type FormItemContextValue = {
|
|
id: string;
|
|
};
|
|
|
|
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);
|
|
|
|
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
|
const id = React.useId();
|
|
|
|
return (
|
|
<FormItemContext.Provider value={{ id }}>
|
|
<div data-slot="form-item" className={cn("grid gap-2", className)} {...props} />
|
|
</FormItemContext.Provider>
|
|
);
|
|
}
|
|
|
|
function FormLabel({
|
|
className,
|
|
required,
|
|
...props
|
|
}: React.ComponentProps<typeof LabelPrimitive.Root> & { required?: boolean }) {
|
|
const { error, formItemId } = useFormField();
|
|
|
|
return (
|
|
<div className="flex items-center gap-1">
|
|
<Label
|
|
data-slot="form-label"
|
|
data-error={!!error}
|
|
className={cn("data-[error=true]:text-destructive", className)}
|
|
htmlFor={formItemId}
|
|
{...props}
|
|
/>
|
|
{required && <Label className="text-destructive">*</Label>}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
|
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
|
|
|
|
return (
|
|
<Slot
|
|
data-slot="form-control"
|
|
id={formItemId}
|
|
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
|
|
aria-invalid={!!error}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
|
const { formDescriptionId } = useFormField();
|
|
|
|
return (
|
|
<p
|
|
data-slot="form-description"
|
|
id={formDescriptionId}
|
|
className={cn("text-muted-foreground text-sm", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
|
const { error, formMessageId } = useFormField();
|
|
const body = error ? String(error?.message ?? "") : props.children;
|
|
|
|
if (!body) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<p data-slot="form-message" id={formMessageId} className={cn("text-destructive text-sm", className)} {...props}>
|
|
{body}
|
|
</p>
|
|
);
|
|
}
|
|
|
|
export { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useFormField };
|
|
|
|
// file: app/components/ui/icon-upload-field.tsx
|
|
import { ImagePlus, RotateCcw, XCircle } from "lucide-react";
|
|
import React, { useCallback } from "react";
|
|
import type { ControllerRenderProps, FieldError } from "react-hook-form";
|
|
import { Button } from "./button";
|
|
|
|
// Props for our custom field component
|
|
interface IconUploadFieldProps {
|
|
field: ControllerRenderProps<any, string>; // field.value can be File | string (URL) | null | undefined
|
|
error?: FieldError;
|
|
accept?: string;
|
|
previewContainerClassName?: string;
|
|
defaultPreview?: string; // Visual fallback URL if field.value is initially undefined
|
|
formDefaultValue?: string | null | undefined; // The actual RHF default value for this field
|
|
}
|
|
|
|
export function IconUploadField({
|
|
field,
|
|
error,
|
|
accept = "image/*",
|
|
previewContainerClassName = "w-24 h-24 rounded-full",
|
|
defaultPreview,
|
|
formDefaultValue, // New prop
|
|
}: IconUploadFieldProps) {
|
|
const [previewUrl, setPreviewUrl] = React.useState<string | null>(null);
|
|
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
|
|
|
React.useEffect(() => {
|
|
let objectUrlToRevoke: string | null = null;
|
|
|
|
if (field.value instanceof File) {
|
|
objectUrlToRevoke = URL.createObjectURL(field.value);
|
|
setPreviewUrl(objectUrlToRevoke);
|
|
} else if (typeof field.value === "string" && field.value) {
|
|
setPreviewUrl(field.value);
|
|
} else if (field.value === null) {
|
|
setPreviewUrl(null);
|
|
} else if (field.value === undefined && defaultPreview) {
|
|
// Show visual default prop if field value is undefined
|
|
setPreviewUrl(defaultPreview);
|
|
} else {
|
|
setPreviewUrl(null);
|
|
}
|
|
|
|
return () => {
|
|
if (objectUrlToRevoke) {
|
|
URL.revokeObjectURL(objectUrlToRevoke);
|
|
}
|
|
};
|
|
}, [field.value, defaultPreview]);
|
|
|
|
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
const file = event.target.files?.[0];
|
|
field.onChange(file || undefined);
|
|
if (event.target) {
|
|
event.target.value = "";
|
|
}
|
|
};
|
|
|
|
const handleRemoveImage = useCallback(
|
|
(e: React.MouseEvent<HTMLButtonElement>) => {
|
|
e.preventDefault();
|
|
field.onChange(null); // Set RHF value to null
|
|
if (fileInputRef.current) {
|
|
fileInputRef.current.value = ""; // Clear the native file input
|
|
}
|
|
},
|
|
[field],
|
|
);
|
|
|
|
const handleResetToDefault = useCallback(
|
|
(e: React.MouseEvent<HTMLButtonElement>) => {
|
|
e.preventDefault();
|
|
// The button's visibility logic ensures formDefaultValue is relevant.
|
|
// This will set RHF value to string (URL), null, or undefined, as per formDefaultValue.
|
|
field.onChange(undefined);
|
|
|
|
if (fileInputRef.current) {
|
|
fileInputRef.current.value = ""; // Clear the native file input
|
|
}
|
|
},
|
|
[field, formDefaultValue],
|
|
);
|
|
|
|
const triggerFileInput = useCallback(() => {
|
|
fileInputRef.current?.click();
|
|
}, []);
|
|
|
|
// Visibility for the "Remove" button: show if there's a File or a URL string in field.value
|
|
const showRemoveButton =
|
|
(!!field.value && (field.value instanceof File || typeof field.value === "string")) ||
|
|
(formDefaultValue && field.value === undefined);
|
|
|
|
// Visibility for the "Reset to Default" button
|
|
const canReset = typeof formDefaultValue !== "undefined"; // Was a formDefaultValue prop provided?
|
|
// Is current value different from the formDefaultValue?
|
|
// (A File object is always different from a URL string/null/undefined default)
|
|
const isDifferentFromDefault =
|
|
(field.value instanceof File || (field.value !== formDefaultValue && field.value !== undefined)) &&
|
|
formDefaultValue;
|
|
const showResetButton = canReset && isDifferentFromDefault;
|
|
|
|
return (
|
|
<div className="flex items-center space-x-4">
|
|
<div
|
|
ref={field.ref}
|
|
className={`relative ${previewContainerClassName} border-2 ${
|
|
error ? "border-destructive" : "border-dashed border-muted-foreground"
|
|
} flex items-center justify-center cursor-pointer hover:border-primary transition-colors overflow-hidden`}
|
|
onClick={triggerFileInput}
|
|
onKeyDown={(e) => {
|
|
if (e.key === "Enter" || e.key === " ") {
|
|
e.preventDefault();
|
|
triggerFileInput();
|
|
}
|
|
}}
|
|
role="button"
|
|
tabIndex={0}
|
|
aria-label={previewUrl ? "Change icon" : "Upload icon"}
|
|
aria-invalid={!!error}
|
|
aria-describedby={error ? `${field.name}-error` : undefined}
|
|
>
|
|
{previewUrl ? (
|
|
<img src={previewUrl} alt="Icon preview" className="w-full h-full object-cover" />
|
|
) : (
|
|
<ImagePlus className={`w-10 h-10 ${error ? "text-destructive" : "text-muted-foreground"}`} />
|
|
)}
|
|
<input
|
|
type="file"
|
|
ref={fileInputRef}
|
|
className="hidden"
|
|
accept={accept}
|
|
onChange={handleFileChange}
|
|
onBlur={field.onBlur}
|
|
name={field.name}
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex flex-col space-y-2">
|
|
{/* Optional: A separate button to trigger file input, if needed. */}
|
|
{/* <Button type="button" variant="outline" size="sm" onClick={triggerFileInput}>
|
|
{previewUrl ? "Change Icon" : "Upload Icon"}
|
|
</Button> */}
|
|
|
|
{showRemoveButton && (
|
|
<Button type="button" variant="destructive" size="sm" onClick={handleRemoveImage}>
|
|
<XCircle className="mr-2 h-4 w-4" />
|
|
Remove
|
|
</Button>
|
|
)}
|
|
|
|
{showResetButton && (
|
|
<Button
|
|
type="button"
|
|
variant="outline" // Choose a suitable variant
|
|
size="sm"
|
|
onClick={handleResetToDefault}
|
|
>
|
|
<RotateCcw className="mr-2 h-4 w-4" />
|
|
Reset to Default
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/components/ui/input.tsx
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
|
return (
|
|
<input
|
|
type={type}
|
|
data-slot="input"
|
|
className={cn(
|
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
|
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
|
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export { Input };
|
|
|
|
// file: app/components/ui/label.tsx
|
|
"use client";
|
|
|
|
import * as React from "react";
|
|
import * as LabelPrimitive from "@radix-ui/react-label";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
|
return (
|
|
<LabelPrimitive.Root
|
|
data-slot="label"
|
|
className={cn(
|
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export { Label };
|
|
|
|
// file: app/components/ui/scroll-area.tsx
|
|
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function ScrollArea({
|
|
className,
|
|
children,
|
|
scrollbarSize,
|
|
viewportRef,
|
|
...props
|
|
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
|
|
scrollbarSize?: "default" | "narrow" | "none";
|
|
viewportRef?: React.Ref<HTMLDivElement>;
|
|
}) {
|
|
return (
|
|
<ScrollAreaPrimitive.Root data-slot="scroll-area" className={cn("relative", className)} {...props}>
|
|
<ScrollAreaPrimitive.Viewport
|
|
ref={viewportRef}
|
|
data-slot="scroll-area-viewport"
|
|
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
|
>
|
|
{children}
|
|
</ScrollAreaPrimitive.Viewport>
|
|
<ScrollBar size={scrollbarSize} />
|
|
<ScrollAreaPrimitive.Corner />
|
|
</ScrollAreaPrimitive.Root>
|
|
);
|
|
}
|
|
|
|
function ScrollBar({
|
|
className,
|
|
orientation = "vertical",
|
|
size = "default",
|
|
...props
|
|
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar> & {
|
|
size?: "default" | "narrow" | "none";
|
|
}) {
|
|
const classes = {
|
|
vertical: {
|
|
className: "h-full border-l border-l-transparent",
|
|
size: {
|
|
default: "w-2.5",
|
|
narrow: "w-1.5",
|
|
none: "hidden",
|
|
},
|
|
},
|
|
horizontal: {
|
|
className: "flex-col border-t border-t-transparent",
|
|
size: {
|
|
default: "h-2.5",
|
|
narrow: "h-1.5",
|
|
none: "hidden",
|
|
},
|
|
},
|
|
};
|
|
|
|
return (
|
|
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
|
data-slot="scroll-area-scrollbar"
|
|
orientation={orientation}
|
|
className={cn(
|
|
"flex touch-none p-px transition-colors select-none",
|
|
classes[orientation].className,
|
|
classes[orientation].size[size],
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
<ScrollAreaPrimitive.ScrollAreaThumb
|
|
data-slot="scroll-area-thumb"
|
|
className="bg-border relative flex-1 rounded-full"
|
|
/>
|
|
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
|
);
|
|
}
|
|
|
|
export { ScrollArea, ScrollBar };
|
|
|
|
// file: app/components/ui/select.tsx
|
|
import * as React from "react";
|
|
import * as SelectPrimitive from "@radix-ui/react-select";
|
|
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
|
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
|
}
|
|
|
|
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
|
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
|
}
|
|
|
|
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
|
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
|
}
|
|
|
|
function SelectTrigger({
|
|
className,
|
|
size = "default",
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
|
size?: "sm" | "default";
|
|
}) {
|
|
return (
|
|
<SelectPrimitive.Trigger
|
|
data-slot="select-trigger"
|
|
data-size={size}
|
|
className={cn(
|
|
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<SelectPrimitive.Icon asChild>
|
|
<ChevronDownIcon className="size-4 opacity-50" />
|
|
</SelectPrimitive.Icon>
|
|
</SelectPrimitive.Trigger>
|
|
);
|
|
}
|
|
|
|
function SelectContent({
|
|
className,
|
|
children,
|
|
position = "popper",
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
|
return (
|
|
<SelectPrimitive.Portal>
|
|
<SelectPrimitive.Content
|
|
data-slot="select-content"
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
|
position === "popper" &&
|
|
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
|
className,
|
|
)}
|
|
position={position}
|
|
{...props}
|
|
>
|
|
<SelectScrollUpButton />
|
|
<SelectPrimitive.Viewport
|
|
className={cn(
|
|
"p-1",
|
|
position === "popper" &&
|
|
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
|
)}
|
|
>
|
|
{children}
|
|
</SelectPrimitive.Viewport>
|
|
<SelectScrollDownButton />
|
|
</SelectPrimitive.Content>
|
|
</SelectPrimitive.Portal>
|
|
);
|
|
}
|
|
|
|
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
|
return (
|
|
<SelectPrimitive.Label
|
|
data-slot="select-label"
|
|
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function SelectItem({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
|
return (
|
|
<SelectPrimitive.Item
|
|
data-slot="select-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
|
<SelectPrimitive.ItemIndicator>
|
|
<CheckIcon className="size-4" />
|
|
</SelectPrimitive.ItemIndicator>
|
|
</span>
|
|
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
|
</SelectPrimitive.Item>
|
|
);
|
|
}
|
|
|
|
function SelectSeparator({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
|
return (
|
|
<SelectPrimitive.Separator
|
|
data-slot="select-separator"
|
|
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function SelectScrollUpButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
|
return (
|
|
<SelectPrimitive.ScrollUpButton
|
|
data-slot="select-scroll-up-button"
|
|
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
|
{...props}
|
|
>
|
|
<ChevronUpIcon className="size-4" />
|
|
</SelectPrimitive.ScrollUpButton>
|
|
);
|
|
}
|
|
|
|
function SelectScrollDownButton({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
|
return (
|
|
<SelectPrimitive.ScrollDownButton
|
|
data-slot="select-scroll-down-button"
|
|
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
|
{...props}
|
|
>
|
|
<ChevronDownIcon className="size-4" />
|
|
</SelectPrimitive.ScrollDownButton>
|
|
);
|
|
}
|
|
|
|
export {
|
|
Select,
|
|
SelectContent,
|
|
SelectGroup,
|
|
SelectItem,
|
|
SelectLabel,
|
|
SelectScrollDownButton,
|
|
SelectScrollUpButton,
|
|
SelectSeparator,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
};
|
|
|
|
// file: app/components/ui/separator.tsx
|
|
import * as React from "react";
|
|
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Separator({
|
|
className,
|
|
orientation = "horizontal",
|
|
decorative = true,
|
|
...props
|
|
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
|
return (
|
|
<SeparatorPrimitive.Root
|
|
data-slot="separator-root"
|
|
decorative={decorative}
|
|
orientation={orientation}
|
|
className={cn(
|
|
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export { Separator };
|
|
|
|
// file: app/components/ui/tabs.tsx
|
|
import * as React from "react";
|
|
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Tabs({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
|
return <TabsPrimitive.Root data-slot="tabs" className={cn("flex flex-col gap-2", className)} {...props} />;
|
|
}
|
|
|
|
function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
|
|
return (
|
|
<TabsPrimitive.List
|
|
data-slot="tabs-list"
|
|
className={cn(
|
|
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
|
return (
|
|
<TabsPrimitive.Trigger
|
|
data-slot="tabs-trigger"
|
|
className={cn(
|
|
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
|
return (
|
|
<TabsPrimitive.Content data-slot="tabs-content" className={cn("flex-1 outline-none", className)} {...props} />
|
|
);
|
|
}
|
|
|
|
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
|
|
|
// file: app/components/ui/textarea.tsx
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
|
return (
|
|
<textarea
|
|
data-slot="textarea"
|
|
className={cn(
|
|
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
|
className,
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export { Textarea };
|
|
|
|
// file: app/components/ui/tooltip.tsx
|
|
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
|
import * as React from "react";
|
|
|
|
import { cn } from "~/lib/utils";
|
|
|
|
function TooltipProvider({ delayDuration = 0, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
|
return <TooltipPrimitive.Provider data-slot="tooltip-provider" delayDuration={delayDuration} {...props} />;
|
|
}
|
|
|
|
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
|
return (
|
|
<TooltipProvider>
|
|
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
|
</TooltipProvider>
|
|
);
|
|
}
|
|
|
|
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
|
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
|
}
|
|
|
|
function TooltipContent({
|
|
className,
|
|
sideOffset = 0,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
|
return (
|
|
<TooltipPrimitive.Portal>
|
|
<TooltipPrimitive.Content
|
|
data-slot="tooltip-content"
|
|
sideOffset={sideOffset}
|
|
className={cn(
|
|
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
|
className,
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
|
</TooltipPrimitive.Content>
|
|
</TooltipPrimitive.Portal>
|
|
);
|
|
}
|
|
|
|
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
|
|
|
|
// file: app/components/user-avatar.tsx
|
|
import type { PartialUser } from "~/lib/api/types";
|
|
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar";
|
|
|
|
interface UserAvatarProps {
|
|
user: PartialUser | undefined;
|
|
}
|
|
|
|
export default function UserAvatar({ user, ...props }: UserAvatarProps & React.ComponentProps<typeof Avatar>) {
|
|
return (
|
|
<Avatar {...props}>
|
|
<AvatarImage src={user?.avatarUrl} />
|
|
<AvatarFallback className="text-muted-foreground">{user?.username?.[0]}</AvatarFallback>
|
|
</Avatar>
|
|
);
|
|
}
|
|
|
|
// file: app/components/user-context-menu.tsx
|
|
import { IdCard, Mail } from "lucide-react";
|
|
import { useNavigate } from "react-router";
|
|
import { createChannel } from "~/lib/api/client/user";
|
|
import type { UserId } from "~/lib/api/types";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import {
|
|
ContextMenu,
|
|
ContextMenuContent,
|
|
ContextMenuItem,
|
|
ContextMenuSeparator,
|
|
ContextMenuTrigger,
|
|
} from "./ui/context-menu";
|
|
|
|
interface UserContextMenuProps {
|
|
userId: UserId;
|
|
children: React.ReactNode;
|
|
}
|
|
|
|
export default function UserContextMenu({ userId, children }: UserContextMenuProps) {
|
|
const currentUser = useUsersStore((state) => state.getCurrentUser());
|
|
const navigate = useNavigate();
|
|
|
|
const onMessage = async () => {
|
|
const reponse = await createChannel([userId]);
|
|
|
|
navigate(`/app/@me/channels/${reponse.id}`);
|
|
};
|
|
|
|
const onCopyId = () => {
|
|
navigator.clipboard.writeText(userId);
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<ContextMenu>
|
|
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
|
<ContextMenuContent>
|
|
{currentUser?.id !== userId && (
|
|
<>
|
|
<ContextMenuItem asChild onClick={onMessage}>
|
|
<div className="flex justify-between gap-2">
|
|
Message
|
|
<Mail />
|
|
</div>
|
|
</ContextMenuItem>
|
|
<ContextMenuSeparator />
|
|
</>
|
|
)}
|
|
<ContextMenuItem asChild onClick={onCopyId}>
|
|
<div className="flex justify-between gap-2">
|
|
Copy ID
|
|
<IdCard />
|
|
</div>
|
|
</ContextMenuItem>
|
|
</ContextMenuContent>
|
|
</ContextMenu>
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/components/visible-trigger.tsx
|
|
import { useEffect, useRef } from "react";
|
|
|
|
interface VisibleTriggerProps {
|
|
onVisible: () => void | Promise<void>;
|
|
options?: IntersectionObserverInit;
|
|
triggerOnce?: boolean;
|
|
children?: React.ReactNode;
|
|
className?: string;
|
|
style?: React.CSSProperties;
|
|
}
|
|
|
|
/**
|
|
* A component that calls a function when it becomes visible in the viewport
|
|
* or a specified scrollable container.
|
|
*/
|
|
export default function VisibleTrigger({
|
|
onVisible, // Function to call when the element becomes visible
|
|
options = {}, // Optional: IntersectionObserver options (root, rootMargin, threshold)
|
|
triggerOnce = true, // Optional: If true, trigger only the first time it becomes visible
|
|
children,
|
|
style,
|
|
...props
|
|
}: VisibleTriggerProps & React.ComponentProps<"div">) {
|
|
const elementRef = useRef(null); // Ref to attach to the DOM element we want to observe
|
|
|
|
useEffect(() => {
|
|
const element = elementRef.current;
|
|
|
|
// Only proceed if we have the DOM element and the function to call
|
|
if (!element) {
|
|
return;
|
|
}
|
|
|
|
// Default IntersectionObserver options
|
|
const defaultOptions = {
|
|
root: null, // default is the viewport
|
|
rootMargin: "0px", // No margin by default
|
|
threshold: 0, // Trigger as soon as any part of the element is visible
|
|
};
|
|
|
|
// Merge provided options with defaults
|
|
const observerOptions = { ...defaultOptions, ...options };
|
|
|
|
// Create the Intersection Observer instance
|
|
const observer = new IntersectionObserver(
|
|
(entries) => {
|
|
const entry = entries[0]; // Assuming only one target element
|
|
|
|
// If the element is intersecting (visible)...
|
|
if (entry.isIntersecting) {
|
|
// console.log('VisibleTrigger: Element is intersecting.', entry);
|
|
|
|
// Call the provided function
|
|
onVisible();
|
|
|
|
// If triggerOnce is true, stop observing this element immediately
|
|
if (triggerOnce) {
|
|
// console.log('VisibleTrigger: Triggered once, disconnecting observer.');
|
|
observer.disconnect(); // Disconnect stops all observations by this instance
|
|
}
|
|
} else {
|
|
// console.log('VisibleTrigger: Element is NOT intersecting.', entry);
|
|
}
|
|
},
|
|
observerOptions, // Pass the options to the observer
|
|
);
|
|
|
|
// Start observing the element
|
|
// console.log('VisibleTrigger: Starting observation.', element);
|
|
observer.observe(element);
|
|
|
|
// Cleanup function: Disconnect the observer when the component unmounts
|
|
// or when the effect dependencies change.
|
|
return () => {
|
|
// console.log('VisibleTrigger: Cleaning up observer.');
|
|
if (observer) {
|
|
// Calling disconnect multiple times is safe.
|
|
observer.disconnect();
|
|
}
|
|
};
|
|
|
|
// Effect dependencies:
|
|
// - elementRef: Need the DOM element reference.
|
|
// - onVisible: If the function prop changes, we need a new observer with the new function.
|
|
// - options: If observer options change, we need a new observer.
|
|
// - triggerOnce: If triggerOnce changes, the logic inside the observer callback changes,
|
|
// so we need a new observer instance.
|
|
}, [elementRef, onVisible, options, triggerOnce]);
|
|
|
|
// Render a div that we will attach the ref to.
|
|
// Ensure it has some minimal dimension if no children are provided,
|
|
// so the observer can detect its presence.
|
|
return (
|
|
<div ref={elementRef} style={{ minHeight: children ? "auto" : "1px", ...style }} {...props}>
|
|
{children} {/* Render any children passed to the component */}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/hooks/use-fetch-user.ts
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { getUser } from "~/lib/api/client/user";
|
|
import type { UserId } from "~/lib/api/types";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
async function fetchCurrentUser() {
|
|
const { setCurrentUserId, addUser } = useUsersStore.getState();
|
|
|
|
const user = await import("~/lib/api/client/user").then((m) => m.default.me());
|
|
setCurrentUserId(user.id);
|
|
addUser(user);
|
|
|
|
return null;
|
|
}
|
|
|
|
export const useFetchCurrentUser = () => {
|
|
const query = useQuery({
|
|
queryKey: ["users", "@me"],
|
|
queryFn: fetchCurrentUser,
|
|
});
|
|
|
|
return query;
|
|
};
|
|
|
|
export const useFetchUser = (userId: UserId) => {
|
|
const query = useQuery({
|
|
queryKey: ["users", userId],
|
|
queryFn: async () => {
|
|
if (useUsersStore.getState().users[userId]) {
|
|
return null;
|
|
}
|
|
|
|
const response = await getUser(userId);
|
|
|
|
useUsersStore.getState().addUser(response);
|
|
|
|
return null;
|
|
},
|
|
});
|
|
|
|
return query;
|
|
};
|
|
|
|
export const useFetchUsers = (userIds: UserId[]) => {
|
|
const query = useQuery({
|
|
queryKey: ["users", ...userIds],
|
|
queryFn: async () => {
|
|
const userIdsToFetch = userIds.filter((userId) => !useUsersStore.getState().users[userId]);
|
|
|
|
if (userIdsToFetch.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
const response = await Promise.all(userIds.map(getUser));
|
|
|
|
for (const user of response) {
|
|
useUsersStore.getState().addUser(user);
|
|
}
|
|
|
|
return null;
|
|
},
|
|
});
|
|
|
|
return query;
|
|
};
|
|
|
|
// file: app/hooks/use-origin.ts
|
|
import React from "react";
|
|
|
|
export const useOrigin = () => {
|
|
const [isMounted, setIsMounted] = React.useState(false);
|
|
|
|
React.useEffect(() => {
|
|
setIsMounted(true);
|
|
}, []);
|
|
|
|
const origin = typeof window !== "undefined" && window.location.origin ? window.location.origin : "";
|
|
|
|
if (!isMounted) {
|
|
return "";
|
|
}
|
|
|
|
return origin;
|
|
};
|
|
|
|
// file: app/lib/api/client/auth.ts
|
|
import axios from "../http-client";
|
|
import type { FullUser } from "../types";
|
|
|
|
interface RegisterRequest {
|
|
email: string;
|
|
username: string;
|
|
displayName?: string;
|
|
password: string;
|
|
}
|
|
|
|
interface LoginRequest {
|
|
username: string;
|
|
password: string;
|
|
}
|
|
|
|
interface LoginResponse {
|
|
user: FullUser;
|
|
token: string;
|
|
}
|
|
|
|
export async function register(request: RegisterRequest) {
|
|
await axios.post("/auth/register", request);
|
|
}
|
|
|
|
export async function login(request: LoginRequest) {
|
|
const response = await axios.post("/auth/login", request);
|
|
|
|
return response.data as LoginResponse;
|
|
}
|
|
|
|
export default {
|
|
register,
|
|
login,
|
|
};
|
|
|
|
// file: app/lib/api/client/channel.ts
|
|
import axios from "../http-client";
|
|
import { messageSchema, type ChannelId, type Uuid } from "../types";
|
|
|
|
export async function paginatedMessages(channelId: ChannelId, limit: number, before: ChannelId | undefined) {
|
|
const response = await axios.get(`/channels/${channelId}/messages`, {
|
|
params: {
|
|
limit,
|
|
before,
|
|
},
|
|
});
|
|
|
|
return (response.data as unknown[]).map((value) => messageSchema.parse(value));
|
|
}
|
|
|
|
export async function sendMessage(channelId: ChannelId, content: string, attachments?: Uuid[]) {
|
|
const response = await axios.post(`/channels/${channelId}/messages`, {
|
|
content,
|
|
attachments,
|
|
});
|
|
|
|
return messageSchema.parse(response.data);
|
|
}
|
|
|
|
export default {
|
|
paginatedMessages,
|
|
sendMessage,
|
|
};
|
|
|
|
// file: app/lib/api/client/file.ts
|
|
import axios from "../http-client";
|
|
|
|
export async function uploadFile(file: File) {
|
|
const formData = new FormData();
|
|
formData.append("files", file);
|
|
|
|
const response = await axios.postForm(`/files`, formData);
|
|
|
|
return response.data as string[];
|
|
}
|
|
|
|
export async function uploadFiles(file: File[]) {
|
|
const formData = new FormData();
|
|
for (const f of file) {
|
|
formData.append("files", f);
|
|
}
|
|
|
|
const response = await axios.postForm(`/files`, formData);
|
|
|
|
return response.data as string[];
|
|
}
|
|
|
|
export default {
|
|
uploadFile,
|
|
uploadFiles,
|
|
};
|
|
|
|
// file: app/lib/api/client/server.ts
|
|
import axios from "../http-client";
|
|
import type { ChannelId, ChannelType, Server, ServerChannel, ServerId, ServerInvite } from "../types";
|
|
|
|
interface CreateServerRequest {
|
|
name: string;
|
|
iconId?: string;
|
|
}
|
|
|
|
interface CreateServerChannelRequest {
|
|
name: string;
|
|
type: ChannelType;
|
|
}
|
|
|
|
export async function list() {
|
|
const response = await axios.get("/servers");
|
|
|
|
return response.data as Server[];
|
|
}
|
|
|
|
export async function create(request: CreateServerRequest) {
|
|
const response = await axios.post("/servers", request);
|
|
|
|
return response.data as Server;
|
|
}
|
|
|
|
export async function get(serverId: ServerId) {
|
|
const response = await axios.get(`/servers/${serverId}`);
|
|
|
|
return response.data as Server;
|
|
}
|
|
|
|
export async function deleteServer(serverId: ServerId) {
|
|
const response = await axios.delete(`/servers/${serverId}`);
|
|
|
|
return response.data as Server;
|
|
}
|
|
|
|
export async function listChannels(serverId: ServerId) {
|
|
const response = await axios.get(`/servers/${serverId}/channels`);
|
|
|
|
return response.data as ServerChannel[];
|
|
}
|
|
|
|
export async function createChannel(serverId: ServerId, request: CreateServerChannelRequest) {
|
|
const response = await axios.post(`/servers/${serverId}/channels`, request);
|
|
|
|
return response.data as ServerChannel;
|
|
}
|
|
|
|
export async function getChannel(serverId: ServerId, channelId: ChannelId) {
|
|
const response = await axios.get(`/servers/${serverId}/channels/${channelId}`);
|
|
|
|
return response.data as ServerChannel;
|
|
}
|
|
|
|
export async function deleteChannel(serverId: ServerId, channelId: ChannelId) {
|
|
const response = await axios.delete(`/servers/${serverId}/channels/${channelId}`);
|
|
|
|
return response.data as ServerChannel;
|
|
}
|
|
|
|
export async function createInvite(serverId: ServerId) {
|
|
const response = await axios.post(`/servers/${serverId}/invites`);
|
|
|
|
return response.data as ServerInvite;
|
|
}
|
|
|
|
export async function getInvite(inviteCode: string) {
|
|
const response = await axios.get(`/invites/${inviteCode}`);
|
|
|
|
return response.data as Server;
|
|
}
|
|
|
|
export default {
|
|
create,
|
|
list,
|
|
listChannels,
|
|
get,
|
|
deleteServer,
|
|
createChannel,
|
|
getChannel,
|
|
deleteChannel,
|
|
createInvite,
|
|
getInvite,
|
|
};
|
|
|
|
// file: app/lib/api/client/user.ts
|
|
import axios from "../http-client";
|
|
import type { FullUser, PartialUser, RecipientChannel, UserId, Uuid } from "../types";
|
|
|
|
export async function me() {
|
|
const response = await axios.get("/users/@me");
|
|
|
|
return response.data as FullUser;
|
|
}
|
|
|
|
export async function getUser(userId: UserId) {
|
|
const response = await axios.get(`/users/${userId}`);
|
|
|
|
return response.data as PartialUser;
|
|
}
|
|
|
|
export async function channels() {
|
|
const response = await axios.get("/users/@me/channels");
|
|
|
|
return response.data as RecipientChannel[];
|
|
}
|
|
|
|
export async function createChannel(recipients: UserId[]) {
|
|
const response = await axios.post("/users/@me/channels", {
|
|
recipients,
|
|
});
|
|
|
|
return response.data as RecipientChannel;
|
|
}
|
|
|
|
interface PatchUserRequest {
|
|
displayName?: string | null;
|
|
avatarId?: Uuid | null;
|
|
}
|
|
|
|
export async function patchUser(request: PatchUserRequest) {
|
|
const response = await axios.patch(`/users/@me`, request);
|
|
|
|
return response.data as FullUser;
|
|
}
|
|
|
|
export default {
|
|
me,
|
|
channels,
|
|
createChannel,
|
|
getUser,
|
|
patchUser,
|
|
};
|
|
|
|
// file: app/lib/api/http-client.ts
|
|
import axios from "axios";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
import { API_URL } from "../consts";
|
|
|
|
axios.interceptors.request.use(
|
|
(config) => {
|
|
const token = useTokenStore.getState().token;
|
|
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
axios.defaults.baseURL = API_URL;
|
|
axios.defaults.headers.common["Content-Type"] = "application/json";
|
|
|
|
export default axios;
|
|
|
|
// file: app/lib/api/types.ts
|
|
import { z } from "zod";
|
|
|
|
export type TypeToZod<T> = {
|
|
[K in keyof T]: T[K] extends ReadonlyArray<infer E> | undefined // 1. Handle Arrays (including arrays of objects, optional or required)
|
|
? undefined extends T[K]
|
|
? E extends object
|
|
? z.ZodOptional<z.ZodArray<z.ZodObject<TypeToZod<E>>>>
|
|
: z.ZodOptional<z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>>
|
|
: E extends object
|
|
? z.ZodArray<z.ZodObject<TypeToZod<E>>>
|
|
: z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>
|
|
: // 2. Handle Primitives
|
|
T[K] extends string | number | boolean | Date | null | undefined
|
|
? undefined extends T[K]
|
|
? z.ZodOptional<z.ZodType<Exclude<T[K], undefined | null>>>
|
|
: z.ZodType<T[K]>
|
|
: // 3. Handle Objects (required or optional, but not arrays)
|
|
T[K] extends object | undefined
|
|
? undefined extends T[K]
|
|
? z.ZodOptional<z.ZodObject<TypeToZod<NonNullable<T[K]>>>>
|
|
: T[K] extends object
|
|
? z.ZodObject<TypeToZod<T[K]>>
|
|
: z.ZodUnknown // Fallback for unexpected required non-object/non-primitive types
|
|
: // 4. Fallback for any other types
|
|
z.ZodUnknown;
|
|
};
|
|
|
|
export const createZodObject = <T>(obj: TypeToZod<T>) => {
|
|
return z.object(obj);
|
|
};
|
|
|
|
export type Uuid = string;
|
|
|
|
export type UserId = Uuid;
|
|
export type ServerId = Uuid;
|
|
export type ChannelId = Uuid;
|
|
export type MessageId = Uuid;
|
|
|
|
export interface FullUser {
|
|
id: UserId;
|
|
avatarUrl?: string;
|
|
username: string;
|
|
displayName?: string;
|
|
email: string;
|
|
bot: boolean;
|
|
system: boolean;
|
|
settings: unknown;
|
|
}
|
|
|
|
export interface Server {
|
|
id: ServerId;
|
|
name: string;
|
|
iconUrl?: string;
|
|
ownerId: UserId;
|
|
}
|
|
|
|
export enum ChannelType {
|
|
SERVER_TEXT = "server_text",
|
|
SERVER_VOICE = "server_voice",
|
|
SERVER_CATEGORY = "server_category",
|
|
|
|
DIRECT_MESSAGE = "direct_message",
|
|
GROUP = "group",
|
|
}
|
|
|
|
export interface Message {
|
|
id: MessageId;
|
|
channelId: ChannelId;
|
|
authorId: UserId;
|
|
content: string;
|
|
createdAt: Date;
|
|
attachments: UploadedFile[];
|
|
}
|
|
|
|
export interface UploadedFile {
|
|
id: Uuid;
|
|
filename: string;
|
|
contentType: string;
|
|
size: number;
|
|
url: string;
|
|
}
|
|
|
|
export const uploadFileSchema = createZodObject<UploadedFile>({
|
|
id: z.string(),
|
|
filename: z.string(),
|
|
contentType: z.string(),
|
|
size: z.number(),
|
|
url: z.string(),
|
|
});
|
|
|
|
export const messageSchema = createZodObject<Message>({
|
|
id: z.string(),
|
|
channelId: z.string(),
|
|
authorId: z.string(),
|
|
content: z.string(),
|
|
createdAt: z.coerce.date(),
|
|
attachments: z.array(uploadFileSchema),
|
|
});
|
|
|
|
export interface Channel {
|
|
id: ChannelId;
|
|
name: string;
|
|
type: ChannelType;
|
|
lastMessageId?: MessageId;
|
|
}
|
|
|
|
export interface ServerChannel {
|
|
id: ChannelId;
|
|
name: string;
|
|
type: ChannelType;
|
|
lastMessageId?: MessageId;
|
|
serverId: ServerId;
|
|
parentId?: ChannelId;
|
|
}
|
|
|
|
export interface ServerInvite {
|
|
code: string;
|
|
serverId: ServerId;
|
|
inviterId?: UserId;
|
|
expiresAt?: string;
|
|
}
|
|
|
|
export interface RecipientChannel {
|
|
id: ChannelId;
|
|
name: string;
|
|
type: ChannelType;
|
|
lastMessageId?: MessageId;
|
|
recipients: UserId[];
|
|
}
|
|
|
|
export interface PartialUser {
|
|
id: ChannelId;
|
|
username: string;
|
|
displayName?: string;
|
|
avatarUrl?: string;
|
|
bot: boolean;
|
|
system: boolean;
|
|
}
|
|
|
|
// file: app/lib/consts.ts
|
|
export const API_URL = "http://localhost:12345/api/v1";
|
|
|
|
// file: app/lib/utils.ts
|
|
import { clsx, type ClassValue } from "clsx";
|
|
import { twMerge } from "tailwind-merge";
|
|
|
|
export function cn(...inputs: ClassValue[]) {
|
|
return twMerge(clsx(inputs));
|
|
}
|
|
|
|
export function getFirstLetters(str: string, n: number): string {
|
|
return str
|
|
.split(/\s+/)
|
|
.slice(0, n)
|
|
.map((word) => word[0] || "")
|
|
.join("");
|
|
}
|
|
|
|
export function formatFileSize(bytes: number, decimals = 2): string {
|
|
if (bytes === 0) return "0 Bytes";
|
|
const k = 1024;
|
|
const dm = decimals < 0 ? 0 : decimals;
|
|
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
|
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
|
|
}
|
|
|
|
export function createPrefixedLogger(prefix: string, styles?: string[]) {
|
|
const result: Record<string, (...args: unknown[]) => void> = {};
|
|
|
|
const methods = ["log", "trace", "debug", "info", "warn", "error"] as const;
|
|
|
|
for (const methodName of methods) {
|
|
const originalMethod = console[methodName].bind(console);
|
|
|
|
result[methodName] = (...args: unknown[]) => {
|
|
if (typeof args[0] === "string") {
|
|
originalMethod(`${prefix} ${args[0]}`, ...(styles || []), ...args.slice(1));
|
|
} else {
|
|
originalMethod(prefix, styles, ...args);
|
|
}
|
|
};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// file: app/lib/websocket/gateway/client.ts
|
|
import type { ChannelId, ServerId, UserId } from "~/lib/api/types";
|
|
import { createPrefixedLogger } from "~/lib/utils";
|
|
import {
|
|
type ClientMessage,
|
|
ClientMessageType,
|
|
ConnectionState,
|
|
ErrorCode,
|
|
type EventData,
|
|
EventType,
|
|
type ServerMessage,
|
|
ServerMessageType,
|
|
} from "./types";
|
|
|
|
export type GatewayEvents = {
|
|
[K in EventType]: (data: Extract<EventData, { type: K }>["data"]) => void;
|
|
};
|
|
|
|
export type ControlEvents = {
|
|
stateChange: (state: ConnectionState) => void;
|
|
error: (error: Error, code?: ErrorCode) => void;
|
|
authenticated: (userId: UserId, sessionKey: string) => void;
|
|
};
|
|
|
|
export interface GatewayClientOptions {
|
|
reconnect?: boolean;
|
|
reconnectDelay?: number;
|
|
maxReconnectAttempts?: number;
|
|
}
|
|
|
|
export class GatewayClient {
|
|
private socket: WebSocket | null = null;
|
|
private state: ConnectionState = ConnectionState.DISCONNECTED;
|
|
private url: string;
|
|
private token: string | null = null;
|
|
private sessionKey: string | null = null;
|
|
private userId: string | null = null;
|
|
private reconnectAttempts = 0;
|
|
private reconnectTimeout: NodeJS.Timeout | null = null;
|
|
private eventHandlers: Partial<ControlEvents> = {};
|
|
private serverEventHandlers: Partial<GatewayEvents> = {};
|
|
private options: Required<GatewayClientOptions>;
|
|
private closeInitiatedByClient = false;
|
|
|
|
private connectionLock = false;
|
|
|
|
constructor(url: string, options: GatewayClientOptions = {}) {
|
|
this.url = url;
|
|
this.options = {
|
|
reconnect: options.reconnect ?? true,
|
|
reconnectDelay: options.reconnectDelay ?? 5000,
|
|
maxReconnectAttempts: options.maxReconnectAttempts ?? 10,
|
|
};
|
|
}
|
|
|
|
// Public methods
|
|
public connect(token: string): void {
|
|
logger.log("Connecting to %s", this.url);
|
|
|
|
if (this.connectionLock) {
|
|
logger.warn("Connection already in progress");
|
|
return;
|
|
}
|
|
|
|
if (this.token === token) {
|
|
logger.warn("Token is the same as the current token");
|
|
return;
|
|
}
|
|
|
|
this.connectionLock = true;
|
|
|
|
if (this.state !== ConnectionState.DISCONNECTED) {
|
|
this.disconnect();
|
|
}
|
|
|
|
this.token = token;
|
|
this.closeInitiatedByClient = false;
|
|
this.reconnectAttempts = 0;
|
|
this.connectToWebSocket();
|
|
}
|
|
|
|
public disconnect(): void {
|
|
logger.log("Disconnecting");
|
|
|
|
this.closeInitiatedByClient = true;
|
|
this.cleanupSocket();
|
|
this.setState(ConnectionState.DISCONNECTED);
|
|
|
|
this.connectionLock = false;
|
|
}
|
|
|
|
public updateVoiceState(serverId: ServerId, channelId: ChannelId): void {
|
|
this.sendMessage({
|
|
type: ClientMessageType.VOICE_STATE_UPDATE,
|
|
data: { serverId, channelId },
|
|
});
|
|
}
|
|
|
|
public requestVoiceStates(serverId: ServerId): void {
|
|
this.sendMessage({
|
|
type: ClientMessageType.REQUEST_VOICE_STATES,
|
|
data: { serverId },
|
|
});
|
|
}
|
|
|
|
public onEvent<K extends keyof GatewayEvents>(event: K | string, handler: GatewayEvents[K]): void {
|
|
this.serverEventHandlers[event as K] = handler;
|
|
}
|
|
|
|
public offEvent<K extends keyof GatewayEvents>(event: K): void {
|
|
delete this.serverEventHandlers[event];
|
|
}
|
|
|
|
public onControl<K extends keyof ControlEvents>(event: K, handler: ControlEvents[K]): void {
|
|
this.eventHandlers[event] = handler;
|
|
}
|
|
|
|
public offControl<K extends keyof ControlEvents>(event: K): void {
|
|
delete this.eventHandlers[event];
|
|
}
|
|
|
|
public get connectionState(): ConnectionState {
|
|
return this.state;
|
|
}
|
|
|
|
public get currentUserId(): UserId | null {
|
|
return this.userId;
|
|
}
|
|
|
|
public get currentSessionKey(): string | null {
|
|
return this.sessionKey;
|
|
}
|
|
|
|
// Private methods
|
|
private connectToWebSocket(): void {
|
|
this.setState(ConnectionState.CONNECTING);
|
|
|
|
try {
|
|
this.socket = new WebSocket(this.url);
|
|
|
|
this.socket.onopen = this.onSocketOpen.bind(this);
|
|
this.socket.onmessage = this.onSocketMessage.bind(this);
|
|
this.socket.onerror = this.onSocketError.bind(this);
|
|
this.socket.onclose = this.onSocketClose.bind(this);
|
|
} catch (error) {
|
|
this.emitError(new Error("Failed to create WebSocket connection", { cause: error }));
|
|
this.setState(ConnectionState.ERROR);
|
|
}
|
|
}
|
|
|
|
private onSocketOpen(): void {
|
|
this.connectionLock = false;
|
|
|
|
logger.log("Socket opened");
|
|
this.setState(ConnectionState.AUTHENTICATING);
|
|
|
|
if (this.token) {
|
|
this.sendMessage({
|
|
type: ClientMessageType.AUTHENTICATE,
|
|
data: { token: this.token },
|
|
});
|
|
} else {
|
|
this.emitError(new Error("No authentication token provided"));
|
|
this.disconnect();
|
|
}
|
|
}
|
|
|
|
private onSocketMessage(event: MessageEvent): void {
|
|
try {
|
|
const message = JSON.parse(event.data) as ServerMessage;
|
|
this.handleServerMessage(message);
|
|
} catch (error) {
|
|
this.emitError(
|
|
new Error("Failed to parse WebSocket message", {
|
|
cause: error,
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
private onSocketError(event: Event): void {
|
|
this.connectionLock = false;
|
|
logger.log("Socket error: %s", event);
|
|
|
|
this.emitError(new Error("WebSocket error occurred"));
|
|
}
|
|
|
|
private onSocketClose(event: CloseEvent): void {
|
|
logger.log("Socket closed: %s", event);
|
|
|
|
this.connectionLock = false;
|
|
|
|
if (
|
|
this.options.reconnect &&
|
|
!this.closeInitiatedByClient &&
|
|
this.reconnectAttempts < this.options.maxReconnectAttempts
|
|
) {
|
|
logger.log(
|
|
"Reconnecting in %d seconds (%d/%d)",
|
|
this.options.reconnectDelay / 1000,
|
|
this.reconnectAttempts + 1,
|
|
this.options.maxReconnectAttempts,
|
|
);
|
|
this.reconnectAttempts++;
|
|
|
|
this.reconnectTimeout = setTimeout(() => {
|
|
if (this.token) {
|
|
this.connectToWebSocket();
|
|
}
|
|
}, this.options.reconnectDelay);
|
|
} else {
|
|
this.setState(ConnectionState.DISCONNECTED);
|
|
}
|
|
}
|
|
|
|
private handleServerMessage(message: ServerMessage): void {
|
|
logger.log("Received message: ", message);
|
|
|
|
switch (message.type) {
|
|
case ServerMessageType.AUTHENTICATE_ACCEPTED:
|
|
this.userId = message.data.userId;
|
|
this.sessionKey = message.data.sessionKey;
|
|
this.setState(ConnectionState.CONNECTED);
|
|
this.emitControl("authenticated", message.data.userId, message.data.sessionKey);
|
|
break;
|
|
|
|
case ServerMessageType.AUTHENTICATE_DENIED:
|
|
this.emitError(new Error("Authentication denied"));
|
|
this.disconnect();
|
|
break;
|
|
|
|
case ServerMessageType.ERROR:
|
|
this.emitError(new Error(`Server error: ${message.data.code}`), message.data.code);
|
|
break;
|
|
|
|
case ServerMessageType.EVENT:
|
|
this.handleEventMessage(message.data.event);
|
|
break;
|
|
|
|
default:
|
|
console.warn("Unhandled server message type:", message);
|
|
}
|
|
}
|
|
|
|
private handleEventMessage(event: EventData): void {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
this.emitEvent(event.type, event.data as any);
|
|
}
|
|
|
|
private sendMessage(message: ClientMessage): void {
|
|
logger.log("Sending message: %o", message);
|
|
|
|
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
|
|
this.socket.send(JSON.stringify(message));
|
|
} else {
|
|
this.emitError(new Error("Cannot send message: socket not connected"));
|
|
}
|
|
}
|
|
|
|
private setState(state: ConnectionState): void {
|
|
if (this.state !== state) {
|
|
logger.log("State changed to %s", state);
|
|
|
|
this.state = state;
|
|
this.emitControl("stateChange", state);
|
|
}
|
|
}
|
|
|
|
private emitError(error: Error, code?: ErrorCode): void {
|
|
logger.error("Error: %s", error, error.cause);
|
|
|
|
this.setState(ConnectionState.ERROR);
|
|
this.emitControl("error", error, code);
|
|
}
|
|
|
|
private emitControl<K extends keyof ControlEvents>(event: K, ...args: Parameters<ControlEvents[K]>): void {
|
|
const handler = this.eventHandlers[event];
|
|
if (handler) {
|
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
(handler as Function)(...args);
|
|
}
|
|
}
|
|
|
|
private emitEvent<K extends keyof GatewayEvents>(event: K, ...args: Parameters<GatewayEvents[K]>): void {
|
|
const handler = this.serverEventHandlers[event];
|
|
if (handler) {
|
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
(handler as Function)(...args);
|
|
}
|
|
}
|
|
|
|
private cleanupSocket(): void {
|
|
logger.log("Cleaning up socket");
|
|
|
|
if (this.reconnectTimeout) {
|
|
clearTimeout(this.reconnectTimeout);
|
|
this.reconnectTimeout = null;
|
|
}
|
|
|
|
if (this.socket) {
|
|
// Remove all event listeners
|
|
this.socket.onopen = null;
|
|
this.socket.onmessage = null;
|
|
this.socket.onerror = null;
|
|
this.socket.onclose = null;
|
|
|
|
// Close the connection if it's still open
|
|
if (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING) {
|
|
this.socket.close();
|
|
}
|
|
|
|
this.socket = null;
|
|
}
|
|
|
|
this.sessionKey = null;
|
|
this.userId = null;
|
|
}
|
|
}
|
|
|
|
const logger = createPrefixedLogger("%cGateway WS%c:", ["color: red; font-weight: bold;", ""]);
|
|
|
|
// file: app/lib/websocket/gateway/types.ts
|
|
import type {
|
|
Channel,
|
|
ChannelId,
|
|
Message,
|
|
MessageId,
|
|
PartialUser,
|
|
Server,
|
|
ServerChannel,
|
|
ServerId,
|
|
UserId,
|
|
} from "~/lib/api/types";
|
|
|
|
export enum ServerMessageType {
|
|
AUTHENTICATE_ACCEPTED = "AUTHENTICATE_ACCEPTED",
|
|
AUTHENTICATE_DENIED = "AUTHENTICATE_DENIED",
|
|
EVENT = "EVENT",
|
|
ERROR = "ERROR",
|
|
}
|
|
|
|
export enum ClientMessageType {
|
|
AUTHENTICATE = "AUTHENTICATE",
|
|
VOICE_STATE_UPDATE = "VOICE_STATE_UPDATE",
|
|
REQUEST_VOICE_STATES = "REQUEST_VOICE_STATES",
|
|
}
|
|
|
|
// Error codes from the server
|
|
export enum ErrorCode {
|
|
AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED",
|
|
TOKEN_GENERATION_FAILED = "TOKEN_GENERATION_FAILED",
|
|
}
|
|
|
|
// Event types from the server
|
|
export enum EventType {
|
|
ADD_SERVER = "ADD_SERVER",
|
|
REMOVE_SERVER = "REMOVE_SERVER",
|
|
|
|
ADD_DM_CHANNEL = "ADD_DM_CHANNEL",
|
|
REMOVE_DM_CHANNEL = "REMOVE_DM_CHANNEL",
|
|
|
|
ADD_SERVER_CHANNEL = "ADD_SERVER_CHANNEL",
|
|
REMOVE_SERVER_CHANNEL = "REMOVE_SERVER_CHANNEL",
|
|
|
|
ADD_USER = "ADD_USER",
|
|
REMOVE_USER = "REMOVE_USER",
|
|
|
|
ADD_SERVER_MEMBER = "ADD_SERVER_MEMBER",
|
|
REMOVE_SERVER_MEMBER = "REMOVE_SERVER_MEMBER",
|
|
|
|
ADD_MESSAGE = "ADD_MESSAGE",
|
|
REMOVE_MESSAGE = "REMOVE_MESSAGE",
|
|
|
|
VOICE_CHANNEL_CONNECTED = "VOICE_CHANNEL_CONNECTED",
|
|
VOICE_CHANNEL_DISCONNECTED = "VOICE_CHANNEL_DISCONNECTED",
|
|
|
|
VOICE_SERVER_UPDATE = "VOICE_SERVER_UPDATE",
|
|
}
|
|
|
|
// Client message types
|
|
export interface AuthenticateMessage {
|
|
type: ClientMessageType.AUTHENTICATE;
|
|
data: {
|
|
token: string;
|
|
};
|
|
}
|
|
|
|
export interface VoiceStateUpdateMessage {
|
|
type: ClientMessageType.VOICE_STATE_UPDATE;
|
|
data: {
|
|
serverId: ServerId;
|
|
channelId: ChannelId;
|
|
};
|
|
}
|
|
|
|
export interface RequestVoiceStatesMessage {
|
|
type: ClientMessageType.REQUEST_VOICE_STATES;
|
|
data: {
|
|
serverId: ServerId;
|
|
};
|
|
}
|
|
|
|
export type ClientMessage = AuthenticateMessage | VoiceStateUpdateMessage | RequestVoiceStatesMessage;
|
|
|
|
// Server message types
|
|
export interface AuthenticateAcceptedMessage {
|
|
type: ServerMessageType.AUTHENTICATE_ACCEPTED;
|
|
data: {
|
|
userId: UserId;
|
|
sessionKey: string;
|
|
};
|
|
}
|
|
|
|
export interface AuthenticateDeniedMessage {
|
|
type: ServerMessageType.AUTHENTICATE_DENIED;
|
|
}
|
|
|
|
export interface ErrorMessage {
|
|
type: ServerMessageType.ERROR;
|
|
data: {
|
|
code: ErrorCode;
|
|
};
|
|
}
|
|
|
|
// Event message types
|
|
export interface AddServerEvent {
|
|
type: EventType.ADD_SERVER;
|
|
data: {
|
|
server: Server;
|
|
};
|
|
}
|
|
|
|
export interface RemoveServerEvent {
|
|
type: EventType.REMOVE_SERVER;
|
|
data: {
|
|
serverId: ServerId;
|
|
};
|
|
}
|
|
|
|
export interface AddDmChannelEvent {
|
|
type: EventType.ADD_DM_CHANNEL;
|
|
data: {
|
|
channel: Channel;
|
|
recipients: UserId[];
|
|
};
|
|
}
|
|
|
|
export interface RemoveDmChannelEvent {
|
|
type: EventType.REMOVE_DM_CHANNEL;
|
|
data: {
|
|
channelId: ChannelId;
|
|
};
|
|
}
|
|
|
|
export interface AddServerChannelEvent {
|
|
type: EventType.ADD_SERVER_CHANNEL;
|
|
data: {
|
|
channel: ServerChannel;
|
|
};
|
|
}
|
|
|
|
export interface RemoveServerChannelEvent {
|
|
type: EventType.REMOVE_SERVER_CHANNEL;
|
|
data: {
|
|
serverId: ServerId;
|
|
channelId: ChannelId;
|
|
};
|
|
}
|
|
|
|
export interface AddUserEvent {
|
|
type: EventType.ADD_USER;
|
|
data: {
|
|
user: PartialUser;
|
|
};
|
|
}
|
|
|
|
export interface RemoveUserEvent {
|
|
type: EventType.REMOVE_USER;
|
|
data: {
|
|
userId: UserId;
|
|
};
|
|
}
|
|
|
|
export interface AddServerMemberEvent {
|
|
type: EventType.ADD_SERVER_MEMBER;
|
|
data: {
|
|
serverId: ServerId;
|
|
user: PartialUser;
|
|
};
|
|
}
|
|
|
|
export interface RemoveServerMemberEvent {
|
|
type: EventType.REMOVE_SERVER_MEMBER;
|
|
data: {
|
|
serverId: ServerId;
|
|
userId: UserId;
|
|
};
|
|
}
|
|
|
|
export interface AddMessageEvent {
|
|
type: EventType.ADD_MESSAGE;
|
|
data: {
|
|
channelId: ChannelId;
|
|
message: Message;
|
|
};
|
|
}
|
|
|
|
export interface RemoveMessageEvent {
|
|
type: EventType.REMOVE_MESSAGE;
|
|
data: {
|
|
channelId: ChannelId;
|
|
messageId: MessageId;
|
|
};
|
|
}
|
|
|
|
export interface VoiceChannelConnectedEvent {
|
|
type: EventType.VOICE_CHANNEL_CONNECTED;
|
|
data: {
|
|
serverId: ServerId;
|
|
channelId: ChannelId;
|
|
userId: UserId;
|
|
};
|
|
}
|
|
|
|
export interface VoiceChannelDisconnectedEvent {
|
|
type: EventType.VOICE_CHANNEL_DISCONNECTED;
|
|
data: {
|
|
serverId: ServerId;
|
|
channelId: ChannelId;
|
|
userId: UserId;
|
|
};
|
|
}
|
|
|
|
export interface VoiceServerUpdateEvent {
|
|
type: EventType.VOICE_SERVER_UPDATE;
|
|
data: {
|
|
serverId: ServerId;
|
|
channelId: ChannelId;
|
|
token: string;
|
|
};
|
|
}
|
|
|
|
export type EventData =
|
|
| AddServerEvent
|
|
| RemoveServerEvent
|
|
| AddDmChannelEvent
|
|
| RemoveDmChannelEvent
|
|
| AddServerChannelEvent
|
|
| RemoveServerChannelEvent
|
|
| AddUserEvent
|
|
| RemoveUserEvent
|
|
| AddServerMemberEvent
|
|
| RemoveServerMemberEvent
|
|
| AddMessageEvent
|
|
| RemoveMessageEvent
|
|
| VoiceChannelConnectedEvent
|
|
| VoiceChannelDisconnectedEvent
|
|
| VoiceServerUpdateEvent;
|
|
|
|
export interface EventMessage {
|
|
type: ServerMessageType.EVENT;
|
|
data: {
|
|
event: EventData;
|
|
};
|
|
}
|
|
|
|
export type ServerMessage = AuthenticateAcceptedMessage | AuthenticateDeniedMessage | EventMessage | ErrorMessage;
|
|
|
|
// Connection states
|
|
export enum ConnectionState {
|
|
DISCONNECTED = "DISCONNECTED",
|
|
CONNECTING = "CONNECTING",
|
|
AUTHENTICATING = "AUTHENTICATING",
|
|
CONNECTED = "CONNECTED",
|
|
ERROR = "ERROR",
|
|
}
|
|
|
|
// file: app/lib/websocket/voice/client.ts
|
|
import { createPrefixedLogger } from "~/lib/utils";
|
|
import { ClientMessageType, ConnectionState, ServerMessageType, type ClientMessage, type ServerMessage } from "./types";
|
|
|
|
export class WebRTCClient {
|
|
private socket: WebSocket | null = null;
|
|
private peerConnection: RTCPeerConnection | null = null;
|
|
|
|
private onStateChange: (state: ConnectionState) => void;
|
|
private onError: (error: Error) => void;
|
|
private onRemoteStream: (stream: MediaStream) => void;
|
|
|
|
private state: ConnectionState = ConnectionState.DISCONNECTED;
|
|
private url: string;
|
|
|
|
private connectionLock = false;
|
|
private disconnectPromise: Promise<void> | null = null;
|
|
private disconnectResolve: (() => void) | null = null;
|
|
|
|
constructor(
|
|
url: string,
|
|
onStateChange: (state: ConnectionState) => void,
|
|
onError: (error: Error) => void,
|
|
onRemoteStream: (stream: MediaStream) => void,
|
|
) {
|
|
this.url = url;
|
|
this.onStateChange = onStateChange;
|
|
this.onError = onError;
|
|
this.onRemoteStream = onRemoteStream;
|
|
}
|
|
|
|
public connect = async (token: string) => {
|
|
if (this.connectionLock) {
|
|
warn("WebRTC: Connection already in progress");
|
|
return;
|
|
}
|
|
|
|
this.connectionLock = true;
|
|
|
|
if (this.state !== ConnectionState.DISCONNECTED && this.state !== ConnectionState.ERROR) {
|
|
this.disconnect();
|
|
}
|
|
|
|
if (this.disconnectPromise) {
|
|
warn("WebRTC: Waiting for previous disconnect to complete");
|
|
try {
|
|
await this.disconnectPromise;
|
|
} catch (error) {
|
|
console.error("WebRTC: Previous disconnect failed:", error);
|
|
}
|
|
}
|
|
|
|
log("Connecting to %s", this.url);
|
|
|
|
try {
|
|
this.setState(ConnectionState.CONNECTING);
|
|
|
|
this.socket = new WebSocket(this.url);
|
|
|
|
this.socket.onopen = () => {
|
|
log("Socket opened");
|
|
|
|
this.connectionLock = false;
|
|
|
|
this.setState(ConnectionState.AUTHENTICATING);
|
|
this.sendMessage({
|
|
type: ClientMessageType.AUTHENTICATE,
|
|
data: { token },
|
|
});
|
|
};
|
|
|
|
this.socket.onmessage = this.handleServerMessage;
|
|
|
|
this.socket.onerror = (event) => {
|
|
this.handleError(new Error("WebSocket error occurred", { cause: event }));
|
|
};
|
|
|
|
this.socket.onclose = (e) => {
|
|
log("Socket closed", e);
|
|
this.cleanupResources();
|
|
if (this.state !== ConnectionState.ERROR) {
|
|
this.setState(ConnectionState.DISCONNECTED);
|
|
}
|
|
|
|
if (this.disconnectResolve) {
|
|
this.disconnectResolve();
|
|
this.disconnectResolve = null;
|
|
this.disconnectPromise = null;
|
|
}
|
|
};
|
|
} catch (error) {
|
|
this.handleError(error instanceof Error ? error : new Error("Unknown error"));
|
|
}
|
|
};
|
|
|
|
public disconnect = (): void => {
|
|
if (this.state === ConnectionState.DISCONNECTED) {
|
|
return;
|
|
}
|
|
|
|
this.setState(ConnectionState.DISCONNECTING);
|
|
this.connectionLock = false;
|
|
|
|
if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
|
|
// If we're already waiting for a disconnect, cancel it
|
|
if (this.disconnectPromise) {
|
|
this.disconnectResolve = null;
|
|
this.disconnectPromise = null;
|
|
}
|
|
|
|
this.disconnectPromise = new Promise((resolve) => {
|
|
this.disconnectResolve = resolve;
|
|
});
|
|
|
|
const onSocketClose = () => {
|
|
this.socket?.removeEventListener("close", onSocketClose);
|
|
this.disconnectResolve?.();
|
|
this.disconnectResolve = null;
|
|
this.disconnectPromise = null;
|
|
};
|
|
|
|
this.socket.addEventListener("close", onSocketClose);
|
|
|
|
if (this.socket.readyState !== WebSocket.CLOSING) {
|
|
this.socket.close(1000, "WebRTC: Cleaning up resources");
|
|
}
|
|
} else {
|
|
this.cleanupResources();
|
|
this.setState(ConnectionState.DISCONNECTED);
|
|
}
|
|
};
|
|
|
|
public createOffer = async (localStream?: MediaStream): Promise<void> => {
|
|
if (this.state !== ConnectionState.CONNECTED) {
|
|
this.handleError(new Error("Cannot create offer: not connected"));
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Create RTCPeerConnection with standard configuration
|
|
const configuration: RTCConfiguration = {
|
|
iceServers: [],
|
|
};
|
|
|
|
this.peerConnection = new RTCPeerConnection(configuration);
|
|
|
|
// Add local stream tracks if provided
|
|
if (localStream) {
|
|
localStream.getTracks().forEach((track) => {
|
|
this.peerConnection!.addTrack(track, localStream);
|
|
});
|
|
}
|
|
|
|
// Handle ICE candidates
|
|
this.peerConnection.onicecandidate = (event) => {
|
|
if (event.candidate === null) {
|
|
// ICE gathering completed
|
|
}
|
|
};
|
|
|
|
// Handle remote stream
|
|
this.peerConnection.ontrack = (event) => {
|
|
const [remoteStream] = event.streams;
|
|
if (remoteStream) {
|
|
this.onRemoteStream(remoteStream);
|
|
}
|
|
};
|
|
|
|
// Create offer and set local description
|
|
const offer = await this.peerConnection.createOffer();
|
|
await this.peerConnection.setLocalDescription(offer);
|
|
|
|
// Send offer to server
|
|
if (this.peerConnection.localDescription) {
|
|
this.sendMessage({
|
|
type: ClientMessageType.SDP_OFFER,
|
|
data: {
|
|
sdp: this.peerConnection.localDescription,
|
|
},
|
|
});
|
|
}
|
|
} catch (error) {
|
|
this.handleError(error instanceof Error ? error : new Error("Error creating WebRTC offer"));
|
|
}
|
|
};
|
|
|
|
private handleServerMessage = async (event: MessageEvent): Promise<void> => {
|
|
try {
|
|
const message: ServerMessage = JSON.parse(event.data);
|
|
|
|
log("Received message: %o", message);
|
|
|
|
switch (message.type) {
|
|
case ServerMessageType.AUTHENTICATE_ACCEPTED:
|
|
this.setState(ConnectionState.CONNECTED);
|
|
break;
|
|
|
|
case ServerMessageType.AUTHENTICATE_DENIED:
|
|
this.handleError(new Error("Authentication failed"));
|
|
break;
|
|
|
|
case ServerMessageType.SDP_ANSWER:
|
|
await this.handleSdpAnswer(message.data.sdp);
|
|
break;
|
|
|
|
default:
|
|
warn("Unhandled message type:", message);
|
|
}
|
|
} catch (error) {
|
|
this.handleError(error instanceof Error ? error : new Error("Failed to process message"));
|
|
}
|
|
};
|
|
|
|
private handleSdpAnswer = async (sdp: RTCSessionDescription): Promise<void> => {
|
|
log("Received SDP answer: %o", sdp);
|
|
|
|
if (!this.peerConnection) {
|
|
this.handleError(new Error("No peer connection established"));
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await this.peerConnection.setRemoteDescription(sdp);
|
|
} catch (error) {
|
|
this.handleError(error instanceof Error ? error : new Error("Error setting remote description"));
|
|
}
|
|
};
|
|
|
|
private sendMessage = (message: ClientMessage): void => {
|
|
log("Sending message: %o", message);
|
|
|
|
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
|
|
this.socket.send(JSON.stringify(message));
|
|
} else {
|
|
this.handleError(new Error("Cannot send message: socket not connected"));
|
|
}
|
|
};
|
|
|
|
private setState = (state: ConnectionState): void => {
|
|
log("State changed to %s", state);
|
|
|
|
this.state = state;
|
|
this.onStateChange(state);
|
|
};
|
|
|
|
private handleError = (error: Error): void => {
|
|
log("Error: %s", error.message);
|
|
|
|
this.setState(ConnectionState.ERROR);
|
|
this.onError(error);
|
|
};
|
|
|
|
private cleanupResources = (): void => {
|
|
log("Cleaning up resources");
|
|
|
|
if (this.peerConnection) {
|
|
this.peerConnection.close();
|
|
this.peerConnection = null;
|
|
}
|
|
|
|
if (this.socket) {
|
|
this.socket.close(1000, "WebRTC: Cleaning up resources");
|
|
this.socket = null;
|
|
}
|
|
};
|
|
}
|
|
|
|
const { log, warn } = createPrefixedLogger("%cWebRTC WS%c:", ["color: blue; font-weight: bold;", ""]);
|
|
|
|
// file: app/lib/websocket/voice/types.ts
|
|
export enum ConnectionState {
|
|
DISCONNECTED = "DISCONNECTED",
|
|
DISCONNECTING = "DISCONNECTING",
|
|
CONNECTING = "CONNECTING",
|
|
AUTHENTICATING = "AUTHENTICATING",
|
|
CONNECTED = "CONNECTED",
|
|
ERROR = "ERROR",
|
|
}
|
|
|
|
export enum ServerMessageType {
|
|
AUTHENTICATE_ACCEPTED = "AUTHENTICATE_ACCEPTED",
|
|
AUTHENTICATE_DENIED = "AUTHENTICATE_DENIED",
|
|
SDP_ANSWER = "SDP_ANSWER",
|
|
}
|
|
|
|
export type ServerMessage =
|
|
| { type: ServerMessageType.AUTHENTICATE_ACCEPTED }
|
|
| { type: ServerMessageType.AUTHENTICATE_DENIED }
|
|
| {
|
|
type: ServerMessageType.SDP_ANSWER;
|
|
data: {
|
|
sdp: RTCSessionDescription;
|
|
};
|
|
};
|
|
|
|
export enum ClientMessageType {
|
|
AUTHENTICATE = "AUTHENTICATE",
|
|
SDP_OFFER = "SDP_OFFER",
|
|
}
|
|
|
|
export type ClientMessage =
|
|
| { type: ClientMessageType.AUTHENTICATE; data: { token: string } }
|
|
| {
|
|
type: ClientMessageType.SDP_OFFER;
|
|
data: {
|
|
sdp: RTCSessionDescription;
|
|
};
|
|
};
|
|
|
|
// file: app/root.tsx
|
|
import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
|
|
|
|
import { ThemeProvider } from "~/components/theme/theme-provider";
|
|
import type { Route } from "./+types/root";
|
|
|
|
import "./app.css";
|
|
|
|
export const links: Route.LinksFunction = () => [
|
|
{ rel: "preconnect", href: "https://fonts.googleapis.com" },
|
|
{
|
|
rel: "preconnect",
|
|
href: "https://fonts.gstatic.com",
|
|
crossOrigin: "anonymous",
|
|
},
|
|
{
|
|
rel: "stylesheet",
|
|
href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap",
|
|
},
|
|
];
|
|
|
|
export default function App() {
|
|
return (
|
|
<ThemeProvider defaultTheme="system" storageKey="ui-theme">
|
|
<Outlet />
|
|
</ThemeProvider>
|
|
);
|
|
}
|
|
|
|
export function Layout({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<html lang="en">
|
|
<head>
|
|
<meta charSet="utf-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
<Meta />
|
|
<Links />
|
|
</head>
|
|
<body>
|
|
{children}
|
|
<ScrollRestoration />
|
|
<Scripts />
|
|
</body>
|
|
</html>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
|
|
let message = "Oops!";
|
|
let details = "An unexpected error occurred.";
|
|
let stack: string | undefined;
|
|
|
|
if (isRouteErrorResponse(error)) {
|
|
message = error.status === 404 ? "404" : "Error";
|
|
details = error.status === 404 ? "The requested page could not be found." : error.statusText || details;
|
|
} else if (import.meta.env.DEV && error && error instanceof Error) {
|
|
details = error.message;
|
|
stack = error.stack;
|
|
}
|
|
|
|
return (
|
|
<main className="pt-16 p-4 container mx-auto">
|
|
<h1>{message}</h1>
|
|
<p>{details}</p>
|
|
{stack && (
|
|
<pre className="w-full p-4 overflow-x-auto">
|
|
<code>{stack}</code>
|
|
</pre>
|
|
)}
|
|
</main>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/current-user-provider.tsx
|
|
import { useFetchCurrentUser } from "~/hooks/use-fetch-user";
|
|
|
|
interface WrapperProps {
|
|
children: React.ReactNode;
|
|
}
|
|
|
|
export default function CurrentUserProvider({ children }: WrapperProps) {
|
|
useFetchCurrentUser();
|
|
|
|
return <>{children}</>;
|
|
}
|
|
|
|
// file: app/routes/app/index.tsx
|
|
import { redirect } from "react-router";
|
|
|
|
export function clientLoader() {
|
|
return redirect("/app/@me");
|
|
}
|
|
|
|
export default function Index() {
|
|
return null;
|
|
}
|
|
|
|
// file: app/routes/app/invite.tsx
|
|
import { redirect } from "react-router";
|
|
import type { Route } from "./+types/invite";
|
|
|
|
export async function clientLoader({ params }: Route.ClientLoaderArgs) {
|
|
const inviteCode = params.inviteCode;
|
|
|
|
try {
|
|
const response = await import("~/lib/api/client/server").then((m) => m.default.getInvite(inviteCode));
|
|
|
|
return redirect(`/app/server/${response.id}`);
|
|
} catch {
|
|
return redirect("/app/@me");
|
|
}
|
|
}
|
|
|
|
export default function Index() {
|
|
return null;
|
|
}
|
|
|
|
// file: app/routes/app/layout.tsx
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { Outlet } from "react-router";
|
|
import AppLayout from "~/components/app-layout";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
|
|
async function fetchServers() {
|
|
const { addServers } = useServerListStore.getState();
|
|
|
|
const newServers = await import("~/lib/api/client/server").then((m) => m.default.list());
|
|
addServers(newServers);
|
|
|
|
return null;
|
|
}
|
|
|
|
export default function Layout() {
|
|
useQuery({
|
|
queryKey: ["servers"],
|
|
queryFn: fetchServers,
|
|
});
|
|
|
|
return (
|
|
<AppLayout>
|
|
<Outlet />
|
|
</AppLayout>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/me/channel.tsx
|
|
import type { Route } from ".react-router/types/app/routes/app/me/+types/channel";
|
|
import { Check } from "lucide-react";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import ChannelArea from "~/components/channel-area";
|
|
import { Badge } from "~/components/ui/badge";
|
|
import { useFetchUsers } from "~/hooks/use-fetch-user";
|
|
import { usePrivateChannelsStore } from "~/stores/private-channels-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
export default function Channel({ params }: Route.ComponentProps) {
|
|
const channelId = params.channelId;
|
|
const currentUserId = useUsersStore((state) => state.currentUserId);
|
|
|
|
const nativeChannel = usePrivateChannelsStore(useShallow((state) => state.channels[channelId]));
|
|
|
|
const recipients = nativeChannel?.recipients?.filter((recipient) => recipient !== currentUserId) || [];
|
|
|
|
useFetchUsers(recipients);
|
|
|
|
const recipientsUsers =
|
|
useUsersStore(useShallow((state) => recipients.map((recipient) => state.users[recipient]).filter(Boolean))) ||
|
|
[];
|
|
|
|
if (!nativeChannel) return null;
|
|
|
|
const renderSystemBadge = recipientsUsers.some((recipient) => recipient.system) && recipients.length === 1;
|
|
|
|
const channel = {
|
|
...nativeChannel,
|
|
name: (
|
|
<>
|
|
<div className="flex items-center gap-2">
|
|
<div>
|
|
{recipientsUsers.map((recipient) => recipient.displayName || recipient.username).join(", ")}
|
|
</div>
|
|
{renderSystemBadge && (
|
|
<Badge variant="default">
|
|
{" "}
|
|
<Check />
|
|
System
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
</>
|
|
),
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<ChannelArea channel={channel} />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/me/index.tsx
|
|
export default function Index() {
|
|
return (
|
|
<>
|
|
{/* <div className="h-full">
|
|
<div className="size-full relative">
|
|
<div className="absolute bottom-0 w-full max-h-1/2">
|
|
<div className="p-2">
|
|
<TextBox value={""}
|
|
onChange={(m) => { }}
|
|
placeholder="Type your message here..."
|
|
// Example of custom styling:
|
|
// wrapperClassName="bg-gray-700 border-gray-600 rounded-lg"
|
|
// inputClassName="text-lg"
|
|
aria-label="Message input" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div> */}
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/me/layout.tsx
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import React from "react";
|
|
import { Outlet } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import PrivateChannelListItem from "~/components/custom-ui/private-channel-list-item";
|
|
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
import { usePrivateChannelsStore } from "~/stores/private-channels-store";
|
|
|
|
async function fetchPrivateChannels() {
|
|
const { addChannels } = usePrivateChannelsStore.getState();
|
|
|
|
const channels = await import("~/lib/api/client/user").then((m) => m.default.channels());
|
|
addChannels(channels);
|
|
|
|
return null;
|
|
}
|
|
|
|
function ListComponent() {
|
|
const channels = Object.values(usePrivateChannelsStore(useShallow((state) => state.channels)));
|
|
const sortedChannels = React.useMemo(
|
|
() => channels.sort((a, b) => ((a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1)),
|
|
[channels],
|
|
);
|
|
|
|
useQuery({
|
|
queryKey: ["channels", "@me"],
|
|
queryFn: fetchPrivateChannels,
|
|
});
|
|
|
|
return (
|
|
<div className="h-full flex flex-col">
|
|
<div className="w-full min-h-12">
|
|
<div className="border-b-2 h-full flex items-center justify-center">Private Messages</div>
|
|
</div>
|
|
|
|
<ScrollArea className="overflow-auto" scrollbarSize="narrow">
|
|
<div className="p-2 flex flex-col gap-1 h-full">
|
|
{sortedChannels.map((channel) => (
|
|
<React.Fragment key={channel.id}>
|
|
<PrivateChannelListItem channel={channel} />
|
|
</React.Fragment>
|
|
))}
|
|
</div>
|
|
</ScrollArea>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export const handle = {
|
|
listComponent: <ListComponent />,
|
|
};
|
|
|
|
export default function Layout() {
|
|
return (
|
|
<>
|
|
<Outlet />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/providers.tsx
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { Outlet, redirect } from "react-router";
|
|
import { GatewayWebSocketConnectionManager } from "~/components/manager/gateway-websocket-connection-manager";
|
|
import { WebRTCConnectionManager } from "~/components/manager/webrtc-connection-manager";
|
|
import ModalProvider from "~/components/providers/modal-provider";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
import CurrentUserProvider from "./current-user-provider";
|
|
|
|
export async function clientLoader() {
|
|
const token = useTokenStore.getState().token;
|
|
|
|
if (!token) {
|
|
return redirect("/login");
|
|
}
|
|
}
|
|
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: {
|
|
queries: {
|
|
refetchOnWindowFocus: false,
|
|
staleTime: Infinity,
|
|
refetchInterval: Infinity,
|
|
refetchOnReconnect: false,
|
|
refetchOnMount: false,
|
|
},
|
|
},
|
|
});
|
|
|
|
export default function Layout() {
|
|
return (
|
|
<QueryClientProvider client={queryClient}>
|
|
<>
|
|
<CurrentUserProvider>
|
|
<ModalProvider />
|
|
<GatewayWebSocketConnectionManager />
|
|
<WebRTCConnectionManager />
|
|
<Outlet />
|
|
</CurrentUserProvider>
|
|
</>
|
|
</QueryClientProvider>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/server/channel.tsx
|
|
import { useNavigate } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import ChannelArea from "~/components/channel-area";
|
|
import { useServerChannelsStore } from "~/stores/server-channels-store";
|
|
import type { Route } from "./+types/channel";
|
|
|
|
export default function Channel({ params: { serverId, channelId } }: Route.ComponentProps) {
|
|
const navigate = useNavigate();
|
|
const channel = useServerChannelsStore(useShallow((state) => state.channels[serverId][channelId]));
|
|
|
|
if (!channel) {
|
|
setTimeout(() => navigate(`/app/server/${serverId}`), 0);
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<ChannelArea channel={channel} />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/server/index.tsx
|
|
export default function Index() {
|
|
return (
|
|
<>
|
|
{/* <div className="h-full">
|
|
<div className="size-full relative">
|
|
<div className="absolute bottom-0 w-full max-h-1/2">
|
|
<div className="p-2">
|
|
<TextBox value={""}
|
|
onChange={(m) => { }}
|
|
placeholder="Type your message here..."
|
|
// Example of custom styling:
|
|
// wrapperClassName="bg-gray-700 border-gray-600 rounded-lg"
|
|
// inputClassName="text-lg"
|
|
aria-label="Message input" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div> */}
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/server/layout.tsx
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import React from "react";
|
|
import { Outlet, useNavigate, useParams } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import ServerChannelListItem from "~/components/custom-ui/channel-list-item";
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuItem,
|
|
DropdownMenuSeparator,
|
|
DropdownMenuTrigger,
|
|
} from "~/components/ui/dropdown-menu";
|
|
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
import { listChannels } from "~/lib/api/client/server";
|
|
import type { ServerId } from "~/lib/api/types";
|
|
import { useGatewayStore } from "~/stores/gateway-store";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { useServerChannelsStore } from "~/stores/server-channels-store";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import type { Route } from "../server/+types/layout";
|
|
|
|
async function fetchServerChannels(serverId: ServerId) {
|
|
const { addChannels } = useServerChannelsStore.getState();
|
|
|
|
const channels = await listChannels(serverId);
|
|
addChannels(channels);
|
|
|
|
useGatewayStore.getState().requestVoiceStates(serverId as ServerId);
|
|
|
|
return null;
|
|
}
|
|
|
|
function ListComponent() {
|
|
const serverId = useParams<{ serverId: ServerId }>().serverId!;
|
|
|
|
useQuery({
|
|
queryKey: ["channels", serverId],
|
|
queryFn: async () => fetchServerChannels(serverId),
|
|
});
|
|
|
|
const currentUserId = useUsersStore((state) => state.currentUserId);
|
|
const onOpen = useModalStore((state) => state.onOpen);
|
|
|
|
const server = useServerListStore(useShallow((state) => state.servers[serverId] || null));
|
|
|
|
const channels = Array.from(
|
|
Object.values(useServerChannelsStore(useShallow((state) => state.channels[serverId] || {}))),
|
|
);
|
|
|
|
if (!server) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<div className="h-full flex flex-col">
|
|
<div className="w-full min-h-12">
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<div className="border-b-2 h-full flex items-center justify-center cursor-pointer">
|
|
{server?.name}
|
|
</div>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent>
|
|
<DropdownMenuItem
|
|
onClick={() =>
|
|
onOpen(ModalType.CREATE_SERVER_INVITE, {
|
|
serverId,
|
|
})
|
|
}
|
|
>
|
|
Create invite
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
onClick={() =>
|
|
onOpen(ModalType.CREATE_SERVER_CHANNEL, {
|
|
serverId,
|
|
})
|
|
}
|
|
>
|
|
Create channel
|
|
</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
{currentUserId === server.ownerId && (
|
|
<DropdownMenuItem
|
|
variant="destructive"
|
|
onClick={() =>
|
|
onOpen(ModalType.DELETE_SERVER_CONFIRM, {
|
|
serverId,
|
|
})
|
|
}
|
|
>
|
|
Delete
|
|
</DropdownMenuItem>
|
|
)}
|
|
{currentUserId !== server.ownerId && (
|
|
<DropdownMenuItem variant="destructive">Leave</DropdownMenuItem>
|
|
)}
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
</div>
|
|
|
|
<ScrollArea className="overflow-auto" scrollbarSize="narrow">
|
|
<div className="p-2 flex flex-col gap-1 h-full">
|
|
{channels
|
|
.sort((a, b) => ((a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1))
|
|
.map((channel) => (
|
|
<React.Fragment key={channel.id}>
|
|
<ServerChannelListItem channel={channel} />
|
|
</React.Fragment>
|
|
))}
|
|
</div>
|
|
</ScrollArea>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export const handle = {
|
|
listComponent: <ListComponent />,
|
|
};
|
|
|
|
export default function Layout({ params: { serverId } }: Route.ComponentProps) {
|
|
const server = useServerListStore(useShallow((state) => state.servers[serverId!] || null));
|
|
const navigate = useNavigate();
|
|
|
|
if (!server) {
|
|
setTimeout(() => navigate("/app/@me"), 0);
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Outlet />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/app/settings.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { LogOutIcon, UserIcon } from "lucide-react";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import { Button } from "~/components/ui/button";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
|
|
import { IconUploadField } from "~/components/ui/icon-upload-field";
|
|
import { Input } from "~/components/ui/input";
|
|
import file from "~/lib/api/client/file";
|
|
import { patchUser } from "~/lib/api/client/user";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
const schema = z.object({
|
|
displayName: z.string().min(1).max(32).optional().nullable(),
|
|
avatar: z.instanceof(File).optional().nullable(),
|
|
});
|
|
|
|
// Note: This is a mockup based on the provided store structure
|
|
export default function Settings() {
|
|
const setToken = useTokenStore((state) => state.setToken);
|
|
const user = useUsersStore((state) => state.getCurrentUser());
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
defaultValues: {
|
|
displayName: user?.displayName,
|
|
avatar: undefined,
|
|
},
|
|
});
|
|
|
|
const onSubmit = async (values: z.infer<typeof schema>) => {
|
|
if (!values) return;
|
|
|
|
let avatarId: string | null | undefined = values.avatar === null ? null : undefined;
|
|
if (values.avatar) {
|
|
avatarId = (await file.uploadFile(values.avatar))[0];
|
|
}
|
|
|
|
await patchUser({
|
|
displayName:
|
|
values.displayName === user?.displayName
|
|
? undefined
|
|
: values.displayName === ""
|
|
? null
|
|
: values.displayName,
|
|
avatarId,
|
|
});
|
|
|
|
form.control._defaultValues = {
|
|
displayName: user?.displayName,
|
|
avatar: undefined,
|
|
};
|
|
|
|
form.reset();
|
|
};
|
|
|
|
const onLogout = () => {
|
|
setToken(undefined);
|
|
window.location.reload();
|
|
};
|
|
|
|
return (
|
|
<div className="flex min-h-screen">
|
|
{/* Sidebar */}
|
|
<div className="w-64 border-r p-6 flex flex-col">
|
|
<h1 className="text-2xl font-bold mb-6">Settings</h1>
|
|
|
|
<Button variant="outline" className="justify-start mb-2 w-full">
|
|
<UserIcon className="mr-2 h-4 w-4" />
|
|
Profile
|
|
</Button>
|
|
|
|
<div className="mt-auto">
|
|
<Button variant="destructive" className="w-full" onClick={onLogout}>
|
|
<LogOutIcon className="mr-2 h-4 w-4" />
|
|
Logout
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Main content */}
|
|
<div className="flex-1 p-8">
|
|
<div className="max-w-2xl mx-auto">
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
|
<FormField
|
|
control={form.control}
|
|
name="avatar"
|
|
render={({ field, fieldState }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.avatar.isOptional()}>Avatar</FormLabel>
|
|
<FormControl>
|
|
<div className="flex flex-col items-center justify-center">
|
|
<IconUploadField
|
|
defaultPreview={user?.avatarUrl}
|
|
formDefaultValue={user?.avatarUrl}
|
|
field={field}
|
|
error={fieldState.error}
|
|
/>
|
|
</div>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="displayName"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.displayName.isOptional()}>
|
|
Display Name
|
|
</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
|
{form.formState.isSubmitting ? "Saving..." : "Save"}
|
|
</Button>
|
|
</form>
|
|
</Form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/auth/layout.tsx
|
|
import { Outlet } from "react-router";
|
|
|
|
export default function Layout() {
|
|
return (
|
|
<div className="min-h-screen min-w-screen grid place-items-center">
|
|
<div className="min-w-md">
|
|
<Outlet />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/auth/login.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { AxiosError } from "axios";
|
|
import { useForm } from "react-hook-form";
|
|
import { Link, redirect, useNavigate } from "react-router";
|
|
import { z } from "zod";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { PasswordInput } from "~/components/custom-ui/password-input";
|
|
import { ThemeToggle } from "~/components/theme/theme-toggle";
|
|
import { Button, buttonVariants } from "~/components/ui/button";
|
|
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
|
|
import { Input } from "~/components/ui/input";
|
|
import auth from "~/lib/api/client/auth";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
const schema = z.object({
|
|
username: z.string(),
|
|
password: z.string().min(8),
|
|
});
|
|
|
|
export async function clientLoader() {
|
|
const { token, setToken } = useTokenStore.getState();
|
|
|
|
if (token) {
|
|
try {
|
|
await import("~/lib/api/client/user").then((m) => m.default.me());
|
|
|
|
return redirect("/app/@me");
|
|
} catch (error) {
|
|
const axiosError = error as AxiosError;
|
|
|
|
if (axiosError.status === 401) {
|
|
setToken(undefined);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export default function Login() {
|
|
const navigate = useNavigate();
|
|
const setToken = useTokenStore((state) => state.setToken);
|
|
const { setCurrentUserId, addUser } = useUsersStore(
|
|
useShallow((state) => {
|
|
return {
|
|
setCurrentUserId: state.setCurrentUserId,
|
|
addUser: state.addUser,
|
|
};
|
|
}),
|
|
);
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
});
|
|
|
|
async function onSubmit(values: z.infer<typeof schema>) {
|
|
const response = await auth.login(values);
|
|
|
|
setToken(response.token);
|
|
setCurrentUserId(response.user.id);
|
|
addUser(response.user);
|
|
|
|
navigate("/app");
|
|
}
|
|
|
|
return (
|
|
<Card style={{ viewTransitionName: "auth-card-view" }}>
|
|
<CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative">
|
|
<CardTitle>Welcome back!</CardTitle>
|
|
<CardDescription>Please sign in to continue.</CardDescription>
|
|
<div
|
|
className="absolute top-0 right-0 px-6"
|
|
style={{
|
|
viewTransitionName: "auth-card-header-mode-toggle-view",
|
|
}}
|
|
>
|
|
<ThemeToggle />
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
|
|
<Form {...form}>
|
|
<form
|
|
onSubmit={form.handleSubmit(onSubmit)}
|
|
className="space-y-4"
|
|
style={{ viewTransitionName: "auth-form-view" }}
|
|
>
|
|
<FormField
|
|
control={form.control}
|
|
name="username"
|
|
render={({ field }) => (
|
|
<FormItem
|
|
style={{
|
|
viewTransitionName: "email-field-view",
|
|
}}
|
|
>
|
|
<FormLabel required>Username</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="password"
|
|
render={({ field }) => (
|
|
<FormItem
|
|
style={{
|
|
viewTransitionName: "password-field-view",
|
|
}}
|
|
>
|
|
<FormLabel required>Password</FormLabel>
|
|
<FormControl>
|
|
<PasswordInput {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>
|
|
Log In
|
|
</Button>
|
|
</form>
|
|
</Form>
|
|
</CardContent>
|
|
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
|
|
<div className="flex items-center">
|
|
<span className="text-muted-foreground text-sm">Don't have an account?</span>
|
|
<Link
|
|
className={buttonVariants({
|
|
variant: "link",
|
|
size: "sm",
|
|
})}
|
|
to="/register"
|
|
viewTransition
|
|
>
|
|
Register
|
|
</Link>
|
|
</div>
|
|
</CardFooter>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/auth/register.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { Link, useNavigate } from "react-router";
|
|
import { z } from "zod";
|
|
import { PasswordInput } from "~/components/custom-ui/password-input";
|
|
import { ThemeToggle } from "~/components/theme/theme-toggle";
|
|
import { Button, buttonVariants } from "~/components/ui/button";
|
|
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
|
|
import { Input } from "~/components/ui/input";
|
|
import auth from "~/lib/api/client/auth";
|
|
|
|
const schema = z.object({
|
|
email: z.string().email(),
|
|
displayName: z.string().min(1).optional(),
|
|
username: z
|
|
.string()
|
|
.min(3)
|
|
.regex(/^[a-zA-Z0-9_.]+$/),
|
|
password: z.string().min(8),
|
|
});
|
|
|
|
export default function Register() {
|
|
const navigate = useNavigate();
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
});
|
|
|
|
async function onSubmit(values: z.infer<typeof schema>) {
|
|
await auth.register(values);
|
|
|
|
navigate("/login");
|
|
}
|
|
|
|
return (
|
|
<Card style={{ viewTransitionName: "auth-card-view" }}>
|
|
<CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative">
|
|
<CardTitle>Create an account</CardTitle>
|
|
<CardDescription>Please fill out the form below to create an account.</CardDescription>
|
|
<div
|
|
className="absolute top-0 right-0 px-6"
|
|
style={{
|
|
viewTransitionName: "auth-card-header-mode-toggle-view",
|
|
}}
|
|
>
|
|
<ThemeToggle />
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
|
|
<Form {...form}>
|
|
<form
|
|
onSubmit={form.handleSubmit(onSubmit)}
|
|
className="space-y-4"
|
|
style={{ viewTransitionName: "auth-form-view" }}
|
|
>
|
|
<FormField
|
|
control={form.control}
|
|
name="email"
|
|
render={({ field }) => (
|
|
<FormItem
|
|
style={{
|
|
viewTransitionName: "email-field-view",
|
|
}}
|
|
>
|
|
<FormLabel required>Email</FormLabel>
|
|
<FormControl>
|
|
<Input type="email" placeholder="email@example.com" {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="username"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required>Username</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="displayName"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel>Display Name</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="password"
|
|
render={({ field }) => (
|
|
<FormItem
|
|
style={{
|
|
viewTransitionName: "password-field-view",
|
|
}}
|
|
>
|
|
<FormLabel required>Password</FormLabel>
|
|
<FormControl>
|
|
<PasswordInput {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>
|
|
Register
|
|
</Button>
|
|
</form>
|
|
</Form>
|
|
</CardContent>
|
|
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
|
|
<div className="flex items-center">
|
|
<span className="text-muted-foreground text-sm">Already have an account?</span>
|
|
<Link
|
|
className={buttonVariants({
|
|
variant: "link",
|
|
size: "sm",
|
|
})}
|
|
to="/login"
|
|
viewTransition
|
|
>
|
|
Log In
|
|
</Link>
|
|
</div>
|
|
</CardFooter>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
// file: app/routes/index.tsx
|
|
import { redirect } from "react-router";
|
|
|
|
export function meta() {
|
|
return [{ title: "New React Router App" }];
|
|
}
|
|
|
|
export function clientLoader() {
|
|
return redirect("/login");
|
|
}
|
|
|
|
export default function Index() {
|
|
return <></>;
|
|
}
|
|
|
|
// file: app/routes.ts
|
|
import { type RouteConfig, index, layout, prefix, route } from "@react-router/dev/routes";
|
|
|
|
export default [
|
|
index("routes/index.tsx"),
|
|
layout("routes/auth/layout.tsx", [
|
|
route("/login", "routes/auth/login.tsx"),
|
|
route("/register", "routes/auth/register.tsx"),
|
|
]),
|
|
...prefix("/app", [
|
|
layout("routes/app/providers.tsx", [
|
|
route("/settings", "routes/app/settings.tsx"),
|
|
layout("routes/app/layout.tsx", [
|
|
index("routes/app/index.tsx"),
|
|
route("/invite/:inviteCode", "routes/app/invite.tsx"),
|
|
...prefix("/@me", [
|
|
layout("routes/app/me/layout.tsx", [
|
|
index("routes/app/me/index.tsx"),
|
|
route("/channels/:channelId", "routes/app/me/channel.tsx"),
|
|
]),
|
|
]),
|
|
...prefix("/server/:serverId", [
|
|
layout("routes/app/server/layout.tsx", [
|
|
index("routes/app/server/index.tsx"),
|
|
route("/:channelId", "routes/app/server/channel.tsx"),
|
|
]),
|
|
]),
|
|
]),
|
|
]),
|
|
]),
|
|
] satisfies RouteConfig;
|
|
|
|
// file: app/stores/channels-voice-state.tsx
|
|
import { create } from "zustand";
|
|
import { immer } from "zustand/middleware/immer";
|
|
import type { ChannelId, UserId } from "~/lib/api/types";
|
|
|
|
interface UserVoiceState {
|
|
deaf: boolean;
|
|
muted: boolean;
|
|
}
|
|
|
|
interface ChannelVoiceState {
|
|
users: Record<UserId, UserVoiceState>;
|
|
}
|
|
|
|
interface ChannelsVoiceState {
|
|
channels: Record<ChannelId, ChannelVoiceState>;
|
|
addUser: (channelId: ChannelId, userId: UserId, userVoiceState: UserVoiceState) => void;
|
|
removeUser: (channelId: ChannelId, userId: UserId) => void;
|
|
removeChannel: (channelId: ChannelId) => void;
|
|
}
|
|
|
|
export const useChannelsVoiceStateStore = create<ChannelsVoiceState>()(
|
|
immer((set) => ({
|
|
channels: {},
|
|
addUser: (channelId, userId, userVoiceState) =>
|
|
set((state) => {
|
|
if (!state.channels[channelId]) {
|
|
state.channels[channelId] = {
|
|
users: {},
|
|
};
|
|
}
|
|
|
|
state.channels[channelId].users[userId] = userVoiceState;
|
|
}),
|
|
removeUser: (channelId, userId) =>
|
|
set((state) => {
|
|
if (state.channels[channelId]) {
|
|
delete state.channels[channelId].users[userId];
|
|
}
|
|
}),
|
|
removeChannel: (channelId) =>
|
|
set((state) => {
|
|
delete state.channels[channelId];
|
|
}),
|
|
})),
|
|
);
|
|
|
|
// file: app/stores/gateway-store.ts
|
|
import type { QueryClient } from "@tanstack/react-query";
|
|
import { create } from "zustand";
|
|
import { messageSchema, type ChannelId, type Message, type MessageId, type ServerId } from "~/lib/api/types";
|
|
import { GatewayClient } from "~/lib/websocket/gateway/client";
|
|
import { ConnectionState, EventType, type EventData, type VoiceServerUpdateEvent } from "~/lib/websocket/gateway/types";
|
|
import { useChannelsVoiceStateStore } from "./channels-voice-state";
|
|
import { usePrivateChannelsStore } from "./private-channels-store";
|
|
import { useServerChannelsStore } from "./server-channels-store";
|
|
import { useServerListStore } from "./server-list-store";
|
|
import { useUsersStore } from "./users-store";
|
|
|
|
const GATEWAY_URL = "ws://localhost:12345/gateway/ws";
|
|
|
|
const HANDLERS = {
|
|
[EventType.ADD_SERVER]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_SERVER }>["data"]) => {
|
|
useServerListStore.getState().addServer(data.server);
|
|
},
|
|
|
|
[EventType.REMOVE_SERVER]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.REMOVE_SERVER }>["data"],
|
|
) => {
|
|
useServerListStore.getState().removeServer(data.serverId);
|
|
useServerChannelsStore.getState().removeServer(data.serverId);
|
|
useChannelsVoiceStateStore.getState().removeChannel(data.serverId);
|
|
},
|
|
|
|
[EventType.ADD_DM_CHANNEL]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.ADD_DM_CHANNEL }>["data"],
|
|
) => {
|
|
usePrivateChannelsStore.getState().addChannel({
|
|
...data.channel,
|
|
recipients: data.recipients,
|
|
});
|
|
},
|
|
|
|
[EventType.REMOVE_DM_CHANNEL]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.REMOVE_DM_CHANNEL }>["data"],
|
|
) => {
|
|
usePrivateChannelsStore.getState().removeChannel(data.channelId);
|
|
useChannelsVoiceStateStore.getState().removeChannel(data.channelId);
|
|
},
|
|
|
|
[EventType.ADD_SERVER_CHANNEL]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.ADD_SERVER_CHANNEL }>["data"],
|
|
) => {
|
|
useServerChannelsStore.getState().addChannel(data.channel);
|
|
},
|
|
|
|
[EventType.REMOVE_SERVER_CHANNEL]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.REMOVE_SERVER_CHANNEL }>["data"],
|
|
) => {
|
|
useServerChannelsStore.getState().removeChannel(data.serverId, data.channelId);
|
|
useChannelsVoiceStateStore.getState().removeChannel(data.serverId);
|
|
},
|
|
|
|
[EventType.ADD_USER]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_USER }>["data"]) => {
|
|
useUsersStore.getState().addUser(data.user);
|
|
},
|
|
|
|
[EventType.REMOVE_USER]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.REMOVE_USER }>["data"],
|
|
) => {
|
|
useUsersStore.getState().removeUser(data.userId);
|
|
},
|
|
|
|
[EventType.ADD_SERVER_MEMBER]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.ADD_SERVER_MEMBER }>["data"],
|
|
) => {
|
|
useUsersStore.getState().addUser(data.user);
|
|
},
|
|
|
|
[EventType.REMOVE_SERVER_MEMBER]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.REMOVE_SERVER_MEMBER }>["data"],
|
|
) => {
|
|
useUsersStore.getState().removeUser(data.userId);
|
|
},
|
|
|
|
[EventType.ADD_MESSAGE]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.ADD_MESSAGE }>["data"],
|
|
) => {
|
|
const message = messageSchema.parse(data.message);
|
|
|
|
if (self.queryClient) {
|
|
self.queryClient.setQueryData(
|
|
["messages", message.channelId],
|
|
(oldData: { pages: Message[][]; pageParams: MessageId[] }) => {
|
|
return {
|
|
pages: oldData?.pages
|
|
? [[message, ...oldData.pages[0]], ...oldData.pages.slice(1)]
|
|
: [[message]],
|
|
pageParams: oldData?.pageParams ?? [undefined, message.id],
|
|
};
|
|
},
|
|
);
|
|
}
|
|
},
|
|
|
|
[EventType.REMOVE_MESSAGE]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.REMOVE_MESSAGE }>["data"],
|
|
) => {
|
|
if (self.queryClient) {
|
|
self.queryClient.setQueryData(["messages", data.channelId], (oldData: Message[]) => {
|
|
if (!oldData) return [];
|
|
return oldData.filter((message: Message) => message.id !== data.messageId);
|
|
});
|
|
}
|
|
},
|
|
|
|
[EventType.VOICE_CHANNEL_CONNECTED]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.VOICE_CHANNEL_CONNECTED }>["data"],
|
|
) => {
|
|
useChannelsVoiceStateStore.getState().addUser(data.channelId, data.userId, {
|
|
deaf: false,
|
|
muted: false,
|
|
});
|
|
},
|
|
|
|
[EventType.VOICE_CHANNEL_DISCONNECTED]: (
|
|
self: GatewayState,
|
|
data: Extract<EventData, { type: EventType.VOICE_CHANNEL_DISCONNECTED }>["data"],
|
|
) => {
|
|
useChannelsVoiceStateStore.getState().removeUser(data.channelId, data.userId);
|
|
},
|
|
};
|
|
|
|
interface GatewayState {
|
|
client: GatewayClient | null;
|
|
queryClient: QueryClient | null;
|
|
status: ConnectionState;
|
|
|
|
connect: (token: string) => void;
|
|
disconnect: () => void;
|
|
|
|
setQueryClient: (client: QueryClient) => void;
|
|
|
|
updateVoiceState: (serverId: ServerId, channelId: ChannelId) => void;
|
|
requestVoiceStates: (serverId: ServerId) => void;
|
|
onVoiceServerUpdate: (handler: (event: VoiceServerUpdateEvent["data"]) => void | Promise<void>) => () => void;
|
|
}
|
|
|
|
export const useGatewayStore = create<GatewayState>()((set, get) => {
|
|
const client = new GatewayClient(GATEWAY_URL);
|
|
|
|
const voiceHandlers = new Set<(event: VoiceServerUpdateEvent["data"]) => void>();
|
|
|
|
client.onEvent(EventType.VOICE_SERVER_UPDATE, (event) => {
|
|
voiceHandlers.forEach((handler) => handler(event));
|
|
});
|
|
|
|
for (const [type, handler] of Object.entries(HANDLERS)) {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
client.onEvent(type, (data: any) => {
|
|
handler(get(), data);
|
|
});
|
|
}
|
|
|
|
return {
|
|
client,
|
|
queryClient: null,
|
|
status: ConnectionState.DISCONNECTED,
|
|
|
|
connect: (token) => {
|
|
client.connect(token);
|
|
set({ status: client.connectionState });
|
|
|
|
client.onControl("stateChange", (state) => {
|
|
set({ status: state });
|
|
});
|
|
},
|
|
|
|
disconnect: () => {
|
|
client.disconnect();
|
|
set({ status: ConnectionState.DISCONNECTED });
|
|
},
|
|
|
|
setQueryClient: (queryClient) => {
|
|
set({ queryClient });
|
|
},
|
|
|
|
updateVoiceState: (serverId, channelId) => {
|
|
client.updateVoiceState(serverId, channelId);
|
|
},
|
|
|
|
requestVoiceStates: (serverId) => {
|
|
client.requestVoiceStates(serverId);
|
|
},
|
|
|
|
onVoiceServerUpdate: (handler) => {
|
|
voiceHandlers.add(handler);
|
|
|
|
return () => {
|
|
voiceHandlers.delete(handler);
|
|
};
|
|
},
|
|
};
|
|
});
|
|
|
|
// file: app/stores/modal-store.ts
|
|
import { create } from "zustand";
|
|
import type { ServerId } from "~/lib/api/types";
|
|
|
|
export enum ModalType {
|
|
CREATE_SERVER = "CREATE_SERVER",
|
|
CREATE_SERVER_CHANNEL = "CREATE_CHANNEL",
|
|
CREATE_SERVER_INVITE = "CREATE_SERVER_INVITE",
|
|
DELETE_SERVER_CONFIRM = "DELETE_SERVER_CONFIRM",
|
|
UPDATE_PROFILE = "UPDATE_PROFILE",
|
|
}
|
|
|
|
export type CreateServerInviteModalData = {
|
|
type: ModalType.CREATE_SERVER_INVITE;
|
|
data: {
|
|
serverId: ServerId;
|
|
};
|
|
};
|
|
|
|
export type DeleteServerConfirmModalData = {
|
|
type: ModalType.CREATE_SERVER_CHANNEL;
|
|
data: {
|
|
serverId: ServerId;
|
|
};
|
|
};
|
|
|
|
export type CreateServerChannelModalData = {
|
|
type: ModalType.CREATE_SERVER_CHANNEL;
|
|
data: {
|
|
serverId: ServerId;
|
|
};
|
|
};
|
|
|
|
export type ModalData = CreateServerChannelModalData | CreateServerInviteModalData | DeleteServerConfirmModalData;
|
|
|
|
interface ModalState {
|
|
type: ModalType | null;
|
|
data?: ModalData["data"];
|
|
isOpen: boolean;
|
|
onOpen: (type: ModalType, data?: ModalData["data"]) => void;
|
|
onClose: () => void;
|
|
}
|
|
|
|
export const useModalStore = create<ModalState>()((set) => ({
|
|
type: null,
|
|
data: undefined,
|
|
isOpen: false,
|
|
onOpen: (type, data) => set({ type, data, isOpen: true }),
|
|
onClose: () => set({ type: null, isOpen: false }),
|
|
}));
|
|
|
|
// file: app/stores/private-channels-store.ts
|
|
import { create } from "zustand";
|
|
import { immer } from "zustand/middleware/immer";
|
|
import type { ChannelId, RecipientChannel } from "~/lib/api/types";
|
|
|
|
type PrivateChannelsStore = {
|
|
channels: Record<ChannelId, RecipientChannel>;
|
|
addChannels: (channels: RecipientChannel[]) => void;
|
|
addChannel: (channel: RecipientChannel) => void;
|
|
removeChannel: (channelId: ChannelId) => void;
|
|
};
|
|
|
|
export const usePrivateChannelsStore = create<PrivateChannelsStore>()(
|
|
immer((set) => ({
|
|
channels: {},
|
|
addChannels: (channels: RecipientChannel[]) =>
|
|
set((state) => {
|
|
for (const channel of channels) {
|
|
state.channels[channel.id] = channel;
|
|
}
|
|
}),
|
|
addChannel: (channel: RecipientChannel) =>
|
|
set((state) => {
|
|
state.channels[channel.id] = {
|
|
...channel,
|
|
};
|
|
}),
|
|
removeChannel: (channelId: ChannelId) =>
|
|
set((state) => {
|
|
delete state.channels[channelId];
|
|
}),
|
|
})),
|
|
);
|
|
|
|
// file: app/stores/server-channels-store.ts
|
|
import { create } from "zustand";
|
|
import { immer } from "zustand/middleware/immer";
|
|
import type { ChannelId, ServerChannel, ServerId } from "~/lib/api/types";
|
|
|
|
type ServerChannelsStore = {
|
|
channels: Record<ServerId, Record<ChannelId, ServerChannel>>;
|
|
addServer: (serverId: ServerId) => void;
|
|
addChannel: (channel: ServerChannel) => void;
|
|
addChannels: (channels: ServerChannel[]) => void;
|
|
removeChannel: (serverId: ServerId, channelId: ChannelId) => void;
|
|
removeServer: (serverId: ServerId) => void;
|
|
};
|
|
|
|
export const useServerChannelsStore = create<ServerChannelsStore>()(
|
|
immer((set) => ({
|
|
channels: {},
|
|
addServer: (serverId) =>
|
|
set((state) => {
|
|
state.channels[serverId] = {};
|
|
}),
|
|
addChannel: (channel) =>
|
|
set((state) => {
|
|
if (state.channels[channel.serverId] === undefined) {
|
|
state.channels[channel.serverId] = {};
|
|
}
|
|
|
|
state.channels[channel.serverId][channel.id] = channel;
|
|
}),
|
|
addChannels: (channels) =>
|
|
set((state) => {
|
|
for (const channel of channels) {
|
|
if (state.channels[channel.serverId] === undefined) {
|
|
state.channels[channel.serverId] = {};
|
|
}
|
|
|
|
state.channels[channel.serverId][channel.id] = channel;
|
|
}
|
|
}),
|
|
removeChannel: (serverId, channelId) =>
|
|
set((state) => {
|
|
delete state.channels[serverId][channelId];
|
|
}),
|
|
removeServer: (serverId) =>
|
|
set((state) => {
|
|
delete state.channels[serverId];
|
|
}),
|
|
})),
|
|
);
|
|
|
|
// file: app/stores/server-list-store.ts
|
|
import { create } from "zustand";
|
|
import { immer } from "zustand/middleware/immer";
|
|
import type { Server, ServerId, Uuid } from "~/lib/api/types";
|
|
|
|
type ServerListStore = {
|
|
servers: Record<ServerId, Server>;
|
|
addServers: (newServers: Server[]) => void;
|
|
addServer: (server: Server) => void;
|
|
removeServer: (serverId: Uuid) => void;
|
|
};
|
|
|
|
export const useServerListStore = create<ServerListStore>()(
|
|
immer((set) => ({
|
|
servers: {},
|
|
addServers: (servers: Server[]) =>
|
|
set((state) => {
|
|
for (const server of servers) {
|
|
state.servers[server.id] = server;
|
|
}
|
|
}),
|
|
addServer: (server: Server) =>
|
|
set((state) => {
|
|
state.servers[server.id] = server;
|
|
}),
|
|
removeServer: (serverId: Uuid) =>
|
|
set((state) => {
|
|
delete state.servers[serverId];
|
|
}),
|
|
})),
|
|
);
|
|
|
|
// file: app/stores/token-store.ts
|
|
import { create } from "zustand";
|
|
import { persist } from "zustand/middleware";
|
|
|
|
type TokenStore = {
|
|
token?: string;
|
|
setToken: (token?: string) => void;
|
|
removeToken: () => void;
|
|
};
|
|
|
|
export const useTokenStore = create<TokenStore>()(
|
|
persist(
|
|
(set) => ({
|
|
token: undefined,
|
|
setToken: (token?: string) => set({ token }),
|
|
removeToken: () => set({ token: undefined }),
|
|
}),
|
|
{
|
|
name: "token",
|
|
},
|
|
),
|
|
);
|
|
|
|
// file: app/stores/users-store.tsx
|
|
import { create } from "zustand";
|
|
import { immer } from "zustand/middleware/immer";
|
|
import type { FullUser, PartialUser, UserId } from "~/lib/api/types";
|
|
|
|
type UsersStore = {
|
|
users: Record<UserId, PartialUser>;
|
|
currentUserId: UserId | undefined;
|
|
addUser: (user: PartialUser) => void;
|
|
removeUser: (userId: UserId) => void;
|
|
setCurrentUserId: (userId: UserId) => void;
|
|
getCurrentUser: () => FullUser | undefined;
|
|
};
|
|
|
|
export const useUsersStore = create<UsersStore>()(
|
|
immer((set, get) => ({
|
|
users: {},
|
|
currentUserId: undefined,
|
|
addUser: (user) =>
|
|
set((state) => {
|
|
if (user.id !== get().currentUserId) state.users[user.id] = user;
|
|
else {
|
|
const currentUser = get().users[user.id];
|
|
if (currentUser) state.users[user.id] = { ...currentUser, ...user };
|
|
else state.users[user.id] = user;
|
|
}
|
|
}),
|
|
removeUser: (userId) =>
|
|
set((state) => {
|
|
delete state.users[userId];
|
|
}),
|
|
|
|
setCurrentUserId: (userId) =>
|
|
set((state) => {
|
|
state.currentUserId = userId;
|
|
}),
|
|
|
|
getCurrentUser: () => {
|
|
const currentUserId = get().currentUserId;
|
|
return currentUserId ? (get().users[currentUserId] as FullUser) : undefined;
|
|
},
|
|
})),
|
|
);
|
|
|
|
// file: app/stores/voice-state-store.ts
|
|
import { create } from "zustand";
|
|
import { useWebRTCStore } from "./webrtc-store";
|
|
|
|
interface VoiceState {
|
|
activeChannel: { serverId: string; channelId: string } | null;
|
|
error: string | null;
|
|
|
|
// Actions
|
|
joinVoiceChannel: (serverId: string, channelId: string) => void;
|
|
leaveVoiceChannel: () => void;
|
|
setError: (error: string) => void;
|
|
resetError: () => void;
|
|
}
|
|
|
|
export const useVoiceStateStore = create<VoiceState>()((set, get) => {
|
|
return {
|
|
activeChannel: null,
|
|
error: null,
|
|
|
|
joinVoiceChannel: (serverId, channelId) => {
|
|
set({
|
|
activeChannel: { serverId, channelId },
|
|
error: null,
|
|
});
|
|
},
|
|
|
|
leaveVoiceChannel: () => {
|
|
const currentState = get();
|
|
if (currentState.activeChannel) {
|
|
useWebRTCStore.getState().disconnect();
|
|
|
|
set({
|
|
activeChannel: null,
|
|
});
|
|
}
|
|
},
|
|
|
|
setError: (error) => {
|
|
set({ error });
|
|
},
|
|
|
|
resetError: () => {
|
|
set({ error: null });
|
|
},
|
|
};
|
|
});
|
|
|
|
// file: app/stores/webrtc-store.ts
|
|
import { create } from "zustand";
|
|
import { WebRTCClient } from "~/lib/websocket/voice/client";
|
|
import { ConnectionState } from "~/lib/websocket/voice/types";
|
|
import { useVoiceStateStore } from "./voice-state-store";
|
|
|
|
const VOICE_GATEWAY_URL = "ws://localhost:12345/voice/ws";
|
|
|
|
interface WebRTCState {
|
|
client: WebRTCClient | null;
|
|
status: ConnectionState;
|
|
remoteStream: MediaStream | null;
|
|
error: string | null;
|
|
connect: (token: string) => Promise<void>;
|
|
disconnect: () => void;
|
|
createOffer: (localStream: MediaStream) => Promise<void>;
|
|
}
|
|
|
|
export const useWebRTCStore = create<WebRTCState>()((set) => {
|
|
const client = new WebRTCClient(
|
|
VOICE_GATEWAY_URL,
|
|
(state) => set({ status: state }),
|
|
(error) => {
|
|
set({
|
|
status: ConnectionState.ERROR,
|
|
error: error.message,
|
|
});
|
|
useVoiceStateStore.getState().setError(error.message);
|
|
},
|
|
(stream) => set({ remoteStream: stream }),
|
|
);
|
|
|
|
return {
|
|
client,
|
|
status: ConnectionState.DISCONNECTED,
|
|
remoteStream: null,
|
|
error: null,
|
|
|
|
connect: async (token) => {
|
|
await client.connect(token);
|
|
},
|
|
|
|
disconnect: () => {
|
|
client.disconnect();
|
|
set({
|
|
status: ConnectionState.DISCONNECTED,
|
|
remoteStream: null,
|
|
});
|
|
},
|
|
|
|
createOffer: async (localStream) => {
|
|
await client.createOffer(localStream);
|
|
},
|
|
};
|
|
});
|
|
|
|
// file: react-router.config.ts
|
|
import type { Config } from "@react-router/dev/config";
|
|
|
|
export default {
|
|
// Config options...
|
|
// Server-side render by default, to enable SPA mode set this to `false`
|
|
ssr: false,
|
|
} satisfies Config;
|
|
|
|
// file: vite.config.ts
|
|
import { reactRouter } from "@react-router/dev/vite";
|
|
import tailwindcss from "@tailwindcss/vite";
|
|
import { defineConfig } from "vite";
|
|
import babel from "vite-plugin-babel";
|
|
import tsconfigPaths from "vite-tsconfig-paths";
|
|
|
|
const ReactCompilerConfig = {
|
|
target: "19", // '17' | '18' | '19'
|
|
};
|
|
|
|
export default defineConfig({
|
|
plugins: [
|
|
tailwindcss(),
|
|
reactRouter(),
|
|
tsconfigPaths(),
|
|
babel({
|
|
filter: /\.[jt]sx?$/,
|
|
babelConfig: {
|
|
presets: ["@babel/preset-typescript"],
|
|
plugins: [["babel-plugin-react-compiler", ReactCompilerConfig]],
|
|
},
|
|
}),
|
|
],
|
|
});
|