.
This commit is contained in:
@@ -1,72 +1,41 @@
|
||||
import { Headphones, Mic, Settings } from "lucide-react";
|
||||
import React from "react";
|
||||
import { NavLink } from "react-router";
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { cn, getFirstLetters } from "~/lib/utils";
|
||||
import { useServerListStore } from "~/store/server-list";
|
||||
import { useUserStore } from "~/store/user";
|
||||
import { CreateServerButton } from "./create-server";
|
||||
import Discord from "./icons/Discord";
|
||||
import { OnlineStatus } from "./online-status";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar";
|
||||
import { Button } from "./ui/button";
|
||||
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";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
interface AppLayoutProps {
|
||||
list: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function AppLayout({ list, children }: AppLayoutProps) {
|
||||
let user = useUserStore(state => state.user!)
|
||||
let servers = useServerListStore(useShallow((state) => Array.from(state.servers.values())))
|
||||
export default function AppLayout({ children }: AppLayoutProps) {
|
||||
let servers = useServerListStore(useShallow((state) => Object.values(state.servers)))
|
||||
|
||||
const matches = useMatches();
|
||||
|
||||
let 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-accent/60 min-w-80" style={{ gridTemplateColumns: "auto 1fr", gridTemplateRows: "1fr auto" }}>
|
||||
<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-4 p-2 h-full">
|
||||
<NavLink to={`/app/@me`} className={({ isActive }) =>
|
||||
cn(
|
||||
"rounded-xl",
|
||||
isActive ? "bg-primary" : "bg-accent",
|
||||
)
|
||||
}>
|
||||
<Discord className="size-8 m-2" />
|
||||
</NavLink>
|
||||
<HomeButton />
|
||||
<Separator />
|
||||
{
|
||||
servers.map((server, _) =>
|
||||
<React.Fragment key={server.id}>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<NavLink to={`/app/server/${server.id}`} className={({ isActive }) =>
|
||||
cn(
|
||||
"rounded-xl overflow-hidden",
|
||||
isActive ? "bg-primary" : "bg-accent",
|
||||
)
|
||||
}>
|
||||
{({ isActive }) => (
|
||||
<TooltipTrigger asChild>
|
||||
<Avatar className="size-12 rounded-none">
|
||||
<AvatarImage src={server.icon_url} className="rounded-none" />
|
||||
<AvatarFallback className={cn(isActive ? "bg-primary text-accent" : "", "rounded-none")}>
|
||||
<div>
|
||||
{getFirstLetters(server.name, 4)}
|
||||
</div>
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</TooltipTrigger>
|
||||
)}
|
||||
</NavLink>
|
||||
<TooltipContent>
|
||||
{server.name}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<ServerButton server={server} />
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
@@ -80,37 +49,7 @@ export default function AppLayout({ list, children }: AppLayoutProps) {
|
||||
</div>
|
||||
|
||||
<div className="col-start-1 row-start-2 col-span-2 row-span-1 mb-2 mx-2 min-w-fit z-1">
|
||||
<div className="outline-1 p-2 h-full rounded-xl">
|
||||
<div className="flex justify-between items-center gap-2">
|
||||
<div className="grow flex flex-row gap-2">
|
||||
<OnlineStatus status="online">
|
||||
<Avatar className="size-10">
|
||||
<AvatarImage src="https://api.dicebear.com/9.x/bottts/jpg?seed=lionarius" />
|
||||
</Avatar>
|
||||
</OnlineStatus>
|
||||
|
||||
<div className="flex flex-col text-sm justify-center">
|
||||
<div className="truncate max-w-30">
|
||||
{user.displayName || user.username}
|
||||
</div>
|
||||
<span className="text-muted-foreground text-xs">@{user.username}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex flex-row-reverse gap-2 items-center">
|
||||
<Button variant="secondary" size="none">
|
||||
<Settings className="size-5 m-1.5" />
|
||||
</Button>
|
||||
<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>
|
||||
<UserStatus />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
84
app/components/channel-area.tsx
Normal file
84
app/components/channel-area.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
import { useInfiniteQuery, type QueryFunctionContext } from "@tanstack/react-query"
|
||||
import type { Channel, MessageId } from "~/lib/api/types"
|
||||
import ChatMessage from "./chat-message"
|
||||
import MessageBox from "./message-box"
|
||||
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,
|
||||
error,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetching,
|
||||
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">
|
||||
{
|
||||
status === "success" && data.pages.map((page, i) => (
|
||||
page.map((message) => (
|
||||
<div key={message.id} className="w-full">
|
||||
<ChatMessage message={message} />
|
||||
</div>
|
||||
))
|
||||
)
|
||||
)
|
||||
}
|
||||
<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 max-w-full max-h-1/2">
|
||||
<MessageBox channelId={channelId} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import { ChevronDown, Hash, Volume2 } from "lucide-react"
|
||||
import { Button } from "./ui/button"
|
||||
|
||||
interface Channel {
|
||||
id: string
|
||||
name: string
|
||||
type: "text" | "voice" | "category"
|
||||
}
|
||||
|
||||
interface ChannelListItemProps {
|
||||
channel: Channel
|
||||
}
|
||||
|
||||
export default function ChannelListItem({ channel }: ChannelListItemProps) {
|
||||
if (channel.type === "category") {
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="secondary" size="sm" className="justify-start">
|
||||
<div className="flex items-center gap-2 max-w-72">
|
||||
<div>
|
||||
{channel.type === "text" && <Hash />}
|
||||
{channel.type === "voice" && <Volume2 />}
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{channel.name}
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
136
app/components/chat-message-attachment.tsx
Normal file
136
app/components/chat-message-attachment.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
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,
|
||||
TooltipProvider,
|
||||
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 (
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<div className="flex items-center gap-3 rounded-lg border bg-card p-3 shadow-sm w-full max-w-xs sm:max-w-sm">
|
||||
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md bg-muted">
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageAttachment({ file }: ChatMessageAttachmentProps) {
|
||||
return (
|
||||
<Dialog>
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<div className="group relative w-48 cursor-pointer sm:w-64">
|
||||
<DialogTrigger asChild>
|
||||
<AspectRatio ratio={16 / 9} className="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>
|
||||
</TooltipProvider>
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
86
app/components/chat-message.tsx
Normal file
86
app/components/chat-message.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { Clock } from "lucide-react"
|
||||
import React from "react"
|
||||
import { useShallow } from "zustand/react/shallow"
|
||||
import type { Message } from "~/lib/api/types"
|
||||
import { useUsersStore } from "~/stores/users-store"
|
||||
import ChatMessageAttachment from "./chat-message-attachment"
|
||||
import UserAvatar from "./user-avatar"
|
||||
|
||||
interface ChatMessageProps {
|
||||
message: Message
|
||||
}
|
||||
|
||||
export default function ChatMessage(
|
||||
{ message }: ChatMessageProps
|
||||
) {
|
||||
const { user, fetchUsersIfNotPresent } = useUsersStore(useShallow(state => ({
|
||||
user: state.users[message.authorId],
|
||||
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent
|
||||
})))
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchUsersIfNotPresent([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">
|
||||
<UserAvatar user={user} />
|
||||
</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">
|
||||
{user?.displayName || user?.username}
|
||||
</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="flex flex-col gap-2">
|
||||
{
|
||||
message.attachments.map((file, i) => (<div key={file.id}>
|
||||
<ChatMessageAttachment file={file} />
|
||||
</div>))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
114
app/components/custom-ui/channel-list-item.tsx
Normal file
114
app/components/custom-ui/channel-list-item.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { ChevronDown, Hash, Volume2 } from "lucide-react"
|
||||
import React from "react"
|
||||
import { NavLink } from "react-router"
|
||||
import { useShallow } from "zustand/react/shallow"
|
||||
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 { Button } from "../ui/button"
|
||||
import UserAvatar from "../user-avatar"
|
||||
|
||||
interface ChannelListItemProps {
|
||||
channel: ServerChannel
|
||||
}
|
||||
|
||||
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 channelVoiceState = useChannelsVoiceStateStore(state => state.channels[channel.id]) || {}
|
||||
const userIds = Object.keys(channelVoiceState.users ?? {})
|
||||
|
||||
const { users, fetchUsersIfNotPresent } = useUsersStore(useShallow(state => ({
|
||||
users: state.users,
|
||||
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent
|
||||
})))
|
||||
|
||||
const channelUsers = React.useMemo(() => userIds.map(userId => users[userId]).filter(Boolean), [userIds, users])
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchUsersIfNotPresent(userIds)
|
||||
}, [userIds])
|
||||
|
||||
const onClick = () => {
|
||||
updateVoiceState(channel.serverId, channel.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="secondary" size="sm" className="justify-start" onClick={onClick}>
|
||||
<div className="flex items-center gap-2 max-w-72">
|
||||
<div>
|
||||
<Volume2 />
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{channel.name}
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
{channelUsers.length > 0 &&
|
||||
<div className="ml-2 border-l-2 flex flex-col gap-1">
|
||||
{
|
||||
channelUsers
|
||||
.map(user => (
|
||||
<div key={user.id} className="flex items-center gap-2 max-w-72 pl-4">
|
||||
<UserAvatar user={user} className="size-6" />
|
||||
{user.displayName || user.username}
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ServerText({ channel }: ChannelListItemProps) {
|
||||
return (
|
||||
<NavLink to={`/app/server/${channel.serverId}/${channel.id}`} discover="none" >
|
||||
{({ isActive }) => (
|
||||
<Button variant="secondary" size="sm" className={
|
||||
cn(
|
||||
"justify-start w-full",
|
||||
isActive ? "bg-accent hover:bg-accent" : "bg-secondary"
|
||||
)
|
||||
}>
|
||||
<div className="flex items-center gap-2 max-w-72">
|
||||
<div>
|
||||
<Hash />
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{channel.name}
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
15
app/components/custom-ui/create-server-button.tsx
Normal file
15
app/components/custom-ui/create-server-button.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
21
app/components/custom-ui/home-button.tsx
Normal file
21
app/components/custom-ui/home-button.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
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" asChild className={
|
||||
isActive ? "bg-accent size-12" : "size-12"
|
||||
}>
|
||||
<div>
|
||||
<Discord className="size-full p-2" />
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export function OnlineStatus({
|
||||
return (
|
||||
<div className="relative">
|
||||
<div {...props}></div>
|
||||
<div className="absolute bottom-0 right-0 bg-accent rounded-full p-0.5 size-1/2">
|
||||
<div className="absolute bottom-0 right-0 bg-background rounded-full p-0.5 size-1/2">
|
||||
{status === "online" && <Circle className="size-full stroke-emerald-400 fill-emerald-400" />}
|
||||
{status === "dnd" && <CircleMinus className="size-full stroke-red-400 stroke-3" />}
|
||||
{status === "idle" && <Moon className="size-full stroke-amber-400 fill-amber-400" />}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EyeIcon, EyeOffIcon } from "lucide-react"
|
||||
import React from "react"
|
||||
import { Button } from "./ui/button"
|
||||
import { Input } from "./ui/input"
|
||||
import { Button } from "../ui/button"
|
||||
import { Input } from "../ui/input"
|
||||
|
||||
export function PasswordInput(props: React.ComponentProps<"input">) {
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
48
app/components/custom-ui/private-channel-list-item.tsx
Normal file
48
app/components/custom-ui/private-channel-list-item.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Check } from "lucide-react"
|
||||
import { NavLink } from "react-router"
|
||||
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.id !== currentUserId);
|
||||
const renderSystemBadge = recipients.some(recipient => recipient.system) && recipients.length === 1
|
||||
|
||||
return (
|
||||
<>
|
||||
<NavLink to={`/app/@me/channels/${channel.id}`}>
|
||||
{
|
||||
({ isActive }) => (
|
||||
<Button variant="secondary" size="none" asChild className={
|
||||
cn(
|
||||
isActive ? "bg-accent hover:bg-accent" : "",
|
||||
"w-full flex flex-row justify-start"
|
||||
)
|
||||
}>
|
||||
<div className="flex items-center gap-2 max-w-72 p-2">
|
||||
<div>
|
||||
<OnlineStatus status="online">
|
||||
<UserAvatar user={channel.recipients.find(recipient => recipient.id !== currentUserId)} />
|
||||
</OnlineStatus>
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{recipients.map(recipient => recipient.displayName || recipient.username).join(", ")}
|
||||
</div>
|
||||
{renderSystemBadge && <Badge variant="default"> <Check /> System</Badge>}
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
</NavLink>
|
||||
</>
|
||||
)
|
||||
}
|
||||
36
app/components/custom-ui/server-button.tsx
Normal file
36
app/components/custom-ui/server-button.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@radix-ui/react-avatar"
|
||||
import { NavLink } from "react-router"
|
||||
import type { Server } from "~/lib/api/types"
|
||||
import { getFirstLetters } from "~/lib/utils"
|
||||
import { Button } from "../ui/button"
|
||||
|
||||
export interface ServerButtonProps {
|
||||
server: Server
|
||||
}
|
||||
|
||||
export function ServerButton(
|
||||
{ server }: ServerButtonProps
|
||||
) {
|
||||
return (
|
||||
<NavLink to={`/app/server/${server.id}`}>
|
||||
{
|
||||
({ isActive }) => (
|
||||
<Button variant="outline" size="none" asChild className={
|
||||
isActive ? "bg-accent" : ""
|
||||
}>
|
||||
<div>
|
||||
<Avatar className="size-12 rounded-none flex items-center justify-center">
|
||||
<AvatarImage src={server.iconUrl} className="rounded-none" />
|
||||
<AvatarFallback>
|
||||
<div>
|
||||
{getFirstLetters(server.name, 4)}
|
||||
</div>
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
38
app/components/custom-ui/settings-button.tsx
Normal file
38
app/components/custom-ui/settings-button.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Settings } from "lucide-react";
|
||||
import { ModalType, useModalStore } from "~/stores/modal-store";
|
||||
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 onOpen = useModalStore(state => state.onOpen)
|
||||
|
||||
const onUpdateProfile = () => {
|
||||
onOpen(ModalType.UPDATE_PROFILE)
|
||||
}
|
||||
|
||||
const onLogout = () => {
|
||||
setToken(undefined)
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Settings className="size-5 m-1.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={onUpdateProfile}>
|
||||
Update profile
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={onLogout}>
|
||||
Logout
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -86,8 +86,7 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"max-h-96 w-full overflow-y-auto min-h-6 outline-none p-4 rounded-xl no-scrollbar bg-background border border-input",
|
||||
"focus-within:ring-2 focus-within:ring-ring focus-within:border-ring",
|
||||
"max-h-96 w-full overflow-y-auto min-h-6",
|
||||
wrapperClassName
|
||||
)}
|
||||
onClick={() => localRef.current?.focus()}
|
||||
80
app/components/custom-ui/user-status.tsx
Normal file
80
app/components/custom-ui/user-status.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import { PhoneMissed, Signal } from "lucide-react";
|
||||
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 webrtcState = useWebRTCStore(state => state.status)
|
||||
|
||||
const leaveVoiceChannel = () => {
|
||||
useVoiceStateStore.getState().leaveVoiceChannel()
|
||||
}
|
||||
|
||||
const channel = useServerChannelsStore(state => state.channels[voiceState.serverId]?.[voiceState.channelId])
|
||||
const server = useServerListStore(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="secondary" size="none" onClick={leaveVoiceChannel}>
|
||||
<PhoneMissed className="size-5 m-1.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">
|
||||
{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>
|
||||
)
|
||||
}
|
||||
62
app/components/file-icon.tsx
Normal file
62
app/components/file-icon.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
FileArchive,
|
||||
FileAudio,
|
||||
FileQuestion,
|
||||
FileText,
|
||||
FileVideo,
|
||||
ImageIcon,
|
||||
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 <ImageIcon {...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 <FileText {...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
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
// ~/components/global-audio-player.tsx
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useWebRTCStore } from '~/store/webrtc';
|
||||
|
||||
export function GlobalWebRTCAudioPlayer() {
|
||||
const audioRef = useRef<HTMLAudioElement>(null);
|
||||
const remoteStream = useWebRTCStore(state => state.remoteStream);
|
||||
const webRTCStatus = useWebRTCStore(state => state.status);
|
||||
|
||||
useEffect(() => {
|
||||
const audioElement = audioRef.current;
|
||||
if (audioElement) {
|
||||
if (remoteStream && webRTCStatus === 'CONNECTED') {
|
||||
console.log('GlobalAudioPlayer: Setting remote stream to audio element.');
|
||||
if (audioElement.srcObject !== remoteStream) { // Avoid unnecessary re-assignments
|
||||
audioElement.srcObject = remoteStream;
|
||||
audioElement.play().catch(error => {
|
||||
// Autoplay policy might prevent play without user interaction.
|
||||
// You might need a UI element for the user to click to start playback.
|
||||
console.warn('GlobalAudioPlayer: Error trying to play audio automatically:', error);
|
||||
// A common pattern is to mute the element initially and then allow unmuting by user action
|
||||
// audioElement.muted = true; // Then provide an unmute button
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// If stream is null or not connected, clear the srcObject
|
||||
// This also handles the case when leaving a channel.
|
||||
if (audioElement.srcObject) {
|
||||
console.log('GlobalAudioPlayer: Clearing remote stream from audio element.');
|
||||
audioElement.srcObject = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [remoteStream, webRTCStatus]); // Re-run when remoteStream or connection status changes
|
||||
|
||||
// This component renders the audio element.
|
||||
// It's generally good practice for <audio> and <video> to have controls if user interaction is expected.
|
||||
// For background audio, you might hide it, but be mindful of autoplay policies.
|
||||
// `playsInline` is more relevant for video but doesn't hurt.
|
||||
// `autoPlay` is desired but subject to browser restrictions.
|
||||
return (
|
||||
<audio
|
||||
ref={audioRef}
|
||||
autoPlay
|
||||
playsInline
|
||||
// controls // Optional: for debugging or if you want user to control volume/mute from here
|
||||
// muted={true} // Start muted if autoplay is problematic, then provide an unmute button
|
||||
style={{ display: 'none' }} // Hide it if it's just for background audio
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
const Discord = (props: SVGProps<SVGSVGElement>) => <svg viewBox="0 0 256 199" width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid" {...props}><path d="M216.856 16.597A208.502 208.502 0 0 0 164.042 0c-2.275 4.113-4.933 9.645-6.766 14.046-19.692-2.961-39.203-2.961-58.533 0-1.832-4.4-4.55-9.933-6.846-14.046a207.809 207.809 0 0 0-52.855 16.638C5.618 67.147-3.443 116.4 1.087 164.956c22.169 16.555 43.653 26.612 64.775 33.193A161.094 161.094 0 0 0 79.735 175.3a136.413 136.413 0 0 1-21.846-10.632 108.636 108.636 0 0 0 5.356-4.237c42.122 19.702 87.89 19.702 129.51 0a131.66 131.66 0 0 0 5.355 4.237 136.07 136.07 0 0 1-21.886 10.653c4.006 8.02 8.638 15.67 13.873 22.848 21.142-6.58 42.646-16.637 64.815-33.213 5.316-56.288-9.08-105.09-38.056-148.36ZM85.474 135.095c-12.645 0-23.015-11.805-23.015-26.18s10.149-26.2 23.015-26.2c12.867 0 23.236 11.804 23.015 26.2.02 14.375-10.148 26.18-23.015 26.18Zm85.051 0c-12.645 0-23.014-11.805-23.014-26.18s10.148-26.2 23.014-26.2c12.867 0 23.236 11.804 23.015 26.2 0 14.375-10.148 26.18-23.015 26.18Z" fill="#5865F2" /></svg>;
|
||||
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;
|
||||
export default Discord;
|
||||
|
||||
@@ -1,47 +1,42 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect } from 'react';
|
||||
import { useGatewayWebSocketStore } from '~/store/gateway-websocket';
|
||||
import { useTokenStore } from '~/store/token';
|
||||
import { ConnectionState } from '~/lib/websocket/gateway/types';
|
||||
import { useGatewayStore } from '~/stores/gateway-store';
|
||||
import { useTokenStore } from '~/stores/token-store';
|
||||
|
||||
export function GatewayWebSocketConnectionManager() {
|
||||
const connectWebSocket = useGatewayWebSocketStore((state) => state.connect);
|
||||
const disconnectWebSocket = useGatewayWebSocketStore((state) => state.disconnect);
|
||||
const wsStatus = useGatewayWebSocketStore((state) => state.status);
|
||||
|
||||
const token = useTokenStore((state) =>
|
||||
state.token,
|
||||
);
|
||||
|
||||
const { setQueryClient } = useGatewayStore();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
useEffect(() => {
|
||||
console.debug(`WS Manager: Status (${wsStatus})`);
|
||||
setQueryClient(queryClient);
|
||||
}, [queryClient])
|
||||
|
||||
useEffect(() => {
|
||||
const { status, connect, disconnect } = useGatewayStore.getState();
|
||||
|
||||
if (!!token) {
|
||||
// Connect if we should be connected and are currently idle, disconnected, or errored out
|
||||
if (wsStatus === 'IDLE' || wsStatus === 'DISCONNECTED' || wsStatus === 'ERROR') {
|
||||
console.log("WS Manager: Conditions met. Calling connect...");
|
||||
// Pass the stable token getter function reference
|
||||
connectWebSocket(() => token);
|
||||
}
|
||||
connect(token);
|
||||
} else {
|
||||
// Disconnect if we shouldn't be connected and are currently in any connected/connecting state
|
||||
if (wsStatus !== 'IDLE' && wsStatus !== 'DISCONNECTED') {
|
||||
console.log("WS Manager: Conditions no longer met. Calling disconnect...");
|
||||
disconnectWebSocket(true); // Intentional disconnect
|
||||
if (status === ConnectionState.CONNECTED) {
|
||||
disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
// The disconnect logic for component unmount (e.g., user logs out entirely)
|
||||
return () => {
|
||||
// Check status on unmount to avoid disconnecting if already idle/disconnected
|
||||
const currentStatus = useGatewayWebSocketStore.getState().status;
|
||||
if (currentStatus !== 'IDLE' && currentStatus !== 'DISCONNECTED') {
|
||||
console.log("WS Manager: Unmounting. Calling disconnect...");
|
||||
// Ensure Zustand has the latest state before calling disconnect
|
||||
useGatewayWebSocketStore.getState().disconnect(true); // Intentional disconnect on unmount
|
||||
if (status === ConnectionState.CONNECTED) {
|
||||
disconnect();
|
||||
}
|
||||
};
|
||||
// Dependencies: connect/disconnect actions, auth status, route location
|
||||
}, [connectWebSocket, disconnectWebSocket]);
|
||||
}, [token]);
|
||||
|
||||
// This component doesn't render anything itself
|
||||
return null;
|
||||
return (
|
||||
<>
|
||||
{null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,185 +1,52 @@
|
||||
// ~/components/webrtc-connection-manager.tsx
|
||||
import { useEffect, useRef } from 'react'; // Removed useState
|
||||
import { useActiveVoiceChannelStore } from '~/store/active-voice-channel';
|
||||
import { useGatewayWebSocketStore } from '~/store/gateway-websocket';
|
||||
import { useWebRTCStore } from '~/store/webrtc'; // Ensure WebRTCStatus is exported
|
||||
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() {
|
||||
console.log('WebRTC Manager: Mounting component.');
|
||||
const gateway = useGatewayStore();
|
||||
const voiceState = useVoiceStateStore();
|
||||
const webrtc = useWebRTCStore();
|
||||
|
||||
const {
|
||||
serverId: activeServerId,
|
||||
channelId: activeChannelId,
|
||||
isVoiceActive,
|
||||
} = useActiveVoiceChannelStore(state => ({
|
||||
serverId: state.serverId,
|
||||
channelId: state.channelId,
|
||||
isVoiceActive: state.isVoiceActive,
|
||||
}));
|
||||
const remoteStream = useWebRTCStore(state => state.remoteStream);
|
||||
const audioRef = useRef<HTMLAudioElement>(null)
|
||||
|
||||
const gatewayStatus = useGatewayWebSocketStore((state) => state.status);
|
||||
|
||||
const {
|
||||
joinVoiceChannel,
|
||||
leaveVoiceChannel,
|
||||
status: webRTCStatus,
|
||||
currentChannelId: rtcCurrentChannelId,
|
||||
} = useWebRTCStore((state) => ({
|
||||
joinVoiceChannel: state.joinVoiceChannel,
|
||||
leaveVoiceChannel: state.leaveVoiceChannel,
|
||||
status: state.status,
|
||||
currentChannelId: state.currentChannelId,
|
||||
}));
|
||||
|
||||
// Use useRef for the stream to avoid re-triggering effect on set
|
||||
const mediaStreamRef = useRef<MediaStream | null>(null);
|
||||
// Use useRef for an operation lock to prevent re-entrancy
|
||||
const operationLockRef = useRef<boolean>(false);
|
||||
if (audioRef.current) {
|
||||
audioRef.current.srcObject = remoteStream
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
console.log('WebRTC Manager: Effect triggered', {
|
||||
activeServerId,
|
||||
activeChannelId,
|
||||
isVoiceActive,
|
||||
gatewayStatus,
|
||||
webRTCStatus,
|
||||
rtcCurrentChannelId,
|
||||
operationLock: operationLockRef.current,
|
||||
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);
|
||||
});
|
||||
|
||||
const manageWebRTCConnection = async () => {
|
||||
if (operationLockRef.current) {
|
||||
console.debug('WebRTC Manager: Operation in progress, skipping.');
|
||||
return;
|
||||
}
|
||||
|
||||
const isConnectedToSomeChannel =
|
||||
webRTCStatus !== "IDLE" &&
|
||||
webRTCStatus !== "DISCONNECTED" &&
|
||||
webRTCStatus !== "FAILED";
|
||||
|
||||
// --- Condition to JOIN/SWITCH voice ---
|
||||
if (isVoiceActive && activeServerId && activeChannelId && gatewayStatus === 'CONNECTED') {
|
||||
// Condition 1: Not connected at all, and want to join.
|
||||
// Condition 2: Connected to a DIFFERENT channel, and want to switch.
|
||||
const needsToJoinOrSwitch =
|
||||
!isConnectedToSomeChannel || (rtcCurrentChannelId !== activeChannelId);
|
||||
|
||||
if (needsToJoinOrSwitch) {
|
||||
operationLockRef.current = true;
|
||||
console.log(`WebRTC Manager: Attempting to join/switch to ${activeServerId}/${activeChannelId}. Current RTC status: ${webRTCStatus}, current RTC channel: ${rtcCurrentChannelId}`);
|
||||
|
||||
// If currently connected to a different channel, leave it first.
|
||||
if (isConnectedToSomeChannel && rtcCurrentChannelId && rtcCurrentChannelId !== activeChannelId) {
|
||||
console.log(`WebRTC Manager: Leaving current channel ${rtcCurrentChannelId} before switching.`);
|
||||
leaveVoiceChannel();
|
||||
// leaveVoiceChannel will change webRTCStatus, triggering this effect again.
|
||||
// The operationLock will be released when status becomes IDLE/DISCONNECTED.
|
||||
// No 'return' here needed, let the status change from leave drive the next step.
|
||||
// The lock is set, so next iteration won't try to join immediately.
|
||||
// It will fall through to the lock release logic when state becomes IDLE.
|
||||
} else { // Not connected or switching from a null/same channel (should be IDLE then)
|
||||
let streamToUse = mediaStreamRef.current;
|
||||
|
||||
// Acquire media if we don't have a usable stream
|
||||
if (!streamToUse || streamToUse.getTracks().every(t => t.readyState === 'ended')) {
|
||||
if (streamToUse) { // Clean up old ended stream
|
||||
streamToUse.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
try {
|
||||
console.log('WebRTC Manager: Acquiring new local media stream...');
|
||||
streamToUse = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
|
||||
mediaStreamRef.current = streamToUse;
|
||||
} catch (err) {
|
||||
console.error('WebRTC Manager: Failed to get user media:', err);
|
||||
useWebRTCStore.setState({ status: "FAILED", lastError: 'Failed to get user media.' });
|
||||
operationLockRef.current = false; // Release lock on failure
|
||||
return; // Stop further processing for this run
|
||||
}
|
||||
}
|
||||
|
||||
if (streamToUse) {
|
||||
console.log(`WebRTC Manager: Calling joinVoiceChannel for ${activeServerId}/${activeChannelId}`);
|
||||
await joinVoiceChannel(activeServerId, activeChannelId, streamToUse);
|
||||
// Don't release lock here immediately; let status changes from joinVoiceChannel
|
||||
// (e.g., to CONNECTED or FAILED) handle releasing the lock.
|
||||
} else {
|
||||
console.error('WebRTC Manager: No media stream available to join channel.');
|
||||
useWebRTCStore.setState({ status: "FAILED", lastError: 'Media stream unavailable.' });
|
||||
operationLockRef.current = false; // Release lock
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// --- Condition to LEAVE voice ---
|
||||
else { // Not (isVoiceActive && activeServerId && activeChannelId && gatewayStatus === 'CONNECTED')
|
||||
if (isConnectedToSomeChannel) {
|
||||
operationLockRef.current = true;
|
||||
console.log('WebRTC Manager: Conditions met to leave active voice channel. Leaving...', { isVoiceActive, activeServerId, gatewayStatus, webRTCStatus });
|
||||
leaveVoiceChannel();
|
||||
// Lock will be released when status becomes IDLE/DISCONNECTED.
|
||||
}
|
||||
}
|
||||
|
||||
// --- Manage operation lock based on final WebRTC state for this "cycle" ---
|
||||
// This part is crucial: if an operation was started, the lock is only released
|
||||
// when the WebRTC state settles into a terminal (IDLE, DISCONNECTED, FAILED) or successful (CONNECTED) state.
|
||||
if (operationLockRef.current) { // Only if a lock was acquired in this effect run or previous
|
||||
if (
|
||||
webRTCStatus === "IDLE" ||
|
||||
webRTCStatus === "DISCONNECTED" ||
|
||||
webRTCStatus === "FAILED" ||
|
||||
(webRTCStatus === "CONNECTED" && rtcCurrentChannelId === activeChannelId && isVoiceActive) // Successfully connected to desired channel
|
||||
) {
|
||||
// console.debug(`WebRTC Manager: Releasing operation lock. Status: ${webRTCStatus}`);
|
||||
operationLockRef.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Release media stream if no longer needed ---
|
||||
// This should happen if WebRTC is inactive AND user doesn't want voice.
|
||||
if (
|
||||
mediaStreamRef.current &&
|
||||
(webRTCStatus === "IDLE" || webRTCStatus === "DISCONNECTED" || webRTCStatus === "FAILED") &&
|
||||
!isVoiceActive // Only if voice is explicitly deactivated
|
||||
) {
|
||||
console.log('WebRTC Manager: Releasing local media stream as WebRTC is inactive and voice is not desired.');
|
||||
mediaStreamRef.current.getTracks().forEach(track => track.stop());
|
||||
mediaStreamRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
manageWebRTCConnection();
|
||||
|
||||
}, [
|
||||
activeServerId,
|
||||
activeChannelId,
|
||||
isVoiceActive,
|
||||
gatewayStatus,
|
||||
webRTCStatus,
|
||||
rtcCurrentChannelId,
|
||||
joinVoiceChannel, // Stable from Zustand
|
||||
leaveVoiceChannel, // Stable from Zustand
|
||||
]);
|
||||
|
||||
// Cleanup on component unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
console.log('WebRTC Manager: Unmounting component.');
|
||||
// Ensure we attempt to leave if connection is active
|
||||
const { status: currentRtcStatus, leaveVoiceChannel: finalLeave } = useWebRTCStore.getState();
|
||||
if (currentRtcStatus !== "IDLE" && currentRtcStatus !== "DISCONNECTED") {
|
||||
console.log('WebRTC Manager: Unmounting. Leaving active voice channel.');
|
||||
finalLeave();
|
||||
}
|
||||
// Stop any tracks held by the ref
|
||||
if (mediaStreamRef.current) {
|
||||
console.log('WebRTC Manager: Unmounting. Stopping tracks from mediaStreamRef.');
|
||||
mediaStreamRef.current.getTracks().forEach(track => track.stop());
|
||||
mediaStreamRef.current = null;
|
||||
}
|
||||
voiceState.leaveVoiceChannel();
|
||||
unsubscribe();
|
||||
};
|
||||
}, []); // Empty dependency array for unmount cleanup only
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
useEffect(() => {
|
||||
if (webrtc.status === ConnectionState.DISCONNECTED) {
|
||||
voiceState.leaveVoiceChannel();
|
||||
}
|
||||
|
||||
}, [webrtc.status]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<audio autoPlay ref={audioRef} className="hidden" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
103
app/components/message-box.tsx
Normal file
103
app/components/message-box.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Plus, Send, Trash } from "lucide-react"
|
||||
import React from "react"
|
||||
import { sendMessage } from "~/lib/api/client/channel"
|
||||
import { uploadFiles } from "~/lib/api/client/file"
|
||||
import TextBox from "./custom-ui/text-box"
|
||||
import { Button } from "./ui/button"
|
||||
|
||||
export interface MessageBoxProps {
|
||||
channelId: string
|
||||
}
|
||||
|
||||
export default function MessageBox(
|
||||
{ channelId }: MessageBoxProps
|
||||
) {
|
||||
const [text, setText] = React.useState("")
|
||||
const [attachments, setAttachments] = React.useState<File[]>([])
|
||||
|
||||
const fileInputRef = React.useRef<HTMLInputElement>(null)
|
||||
|
||||
const onSendMessage = async () => {
|
||||
const content = text.trim()
|
||||
if (!content && !attachments.length)
|
||||
return
|
||||
|
||||
const uploadedAttachments = await uploadFiles(attachments)
|
||||
|
||||
await sendMessage(channelId, text, uploadedAttachments)
|
||||
setText("")
|
||||
setAttachments([])
|
||||
}
|
||||
|
||||
const addAttachment = async () => {
|
||||
if (!fileInputRef.current)
|
||||
return
|
||||
|
||||
fileInputRef.current.click()
|
||||
}
|
||||
|
||||
const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || [])
|
||||
const newAttachments = [...attachments, ...files]
|
||||
setAttachments(newAttachments.slice(0, 10))
|
||||
|
||||
if (!fileInputRef.current)
|
||||
return
|
||||
|
||||
fileInputRef.current.value = ""
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
setText("")
|
||||
setAttachments([])
|
||||
}, [channelId])
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
<div className="max-h-1/2 w-full max-w-full grid items-center gap-x-2 outline-none py-4 px-2 rounded-xl no-scrollbar bg-background border border-input focus-within:ring-2 focus-within:ring-ring focus-within:border-ring"
|
||||
style={{ gridTemplateColumns: "auto 1fr auto", gridTemplateRows: "1fr auto" }}>
|
||||
<div className="row-start-1 col-start-1 row-span-2 col-span-1 h-full">
|
||||
<Button size="icon" variant="ghost" onClick={addAttachment} disabled={attachments.length >= 10}>
|
||||
<Plus />
|
||||
</Button>
|
||||
<input type="file" multiple className="hidden" ref={fileInputRef} onChange={onFileChange} />
|
||||
</div>
|
||||
|
||||
<div className="flex-1 row-start-1 col-start-2 row-span-1 col-span-1">
|
||||
<TextBox value={text}
|
||||
wrapperClassName="contain-inline-size"
|
||||
onChange={setText}
|
||||
placeholder="Type your message here..."
|
||||
aria-label="Message input">
|
||||
|
||||
</TextBox>
|
||||
</div>
|
||||
<div className="flex-1 row-start-2 col-start-2 row-span-1 col-span-1 overflow-y-auto max-h-40">
|
||||
<div className={`${attachments.length > 0 ? "pt-2" : "hidden"}`}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{
|
||||
attachments.map((file, i) => (
|
||||
<div key={i} className="flex items-center gap-2 wrap-anywhere rounded-xl border border-input bg-background p-2">
|
||||
<div className="flex-1">
|
||||
{file.name}
|
||||
</div>
|
||||
<div>
|
||||
<Button size="icon" variant="destructive" onClick={() => setAttachments(attachments.filter((_, j) => i !== j))}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-start-1 col-start-3 row-span-2 col-span-1 h-full">
|
||||
<Button size="icon" onClick={onSendMessage}>
|
||||
<Send />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
109
app/components/modals/create-server-channel-modal.tsx
Normal file
109
app/components/modals/create-server-channel-modal.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
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
|
||||
|
||||
let 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>) => {
|
||||
const response = 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>
|
||||
)
|
||||
}
|
||||
66
app/components/modals/create-server-invite-modal.tsx
Normal file
66
app/components/modals/create-server-invite-modal.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
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 = (openState: boolean) => {
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -1,59 +1,54 @@
|
||||
import { CirclePlus } from "lucide-react";
|
||||
import React from "react";
|
||||
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "~/components/ui/dialog";
|
||||
import file from "~/lib/api/client/file";
|
||||
import server from "~/lib/api/client/server";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "./ui/form";
|
||||
import { IconUploadField } from "./ui/icon-upload-field";
|
||||
import { Input } from "./ui/input";
|
||||
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 function CreateServerButton() {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
export default function CreateServerModal() {
|
||||
const { type, isOpen, onClose } = useModalStore();
|
||||
|
||||
const isModalOpen = type === ModalType.CREATE_SERVER && isOpen
|
||||
|
||||
let form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
})
|
||||
});
|
||||
|
||||
function onOpenChange(openState: boolean) {
|
||||
setOpen(openState)
|
||||
const onOpenChange = (openState: boolean) => {
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
if (!openState) {
|
||||
form.reset()
|
||||
const onSubmit = async (values: z.infer<typeof schema>) => {
|
||||
let iconId = undefined
|
||||
if (values.icon) {
|
||||
iconId = (await file.uploadFile(values.icon))[0]
|
||||
}
|
||||
|
||||
const response = await server.create({
|
||||
name: values.name,
|
||||
iconId
|
||||
})
|
||||
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
async function onSubmit(values: z.infer<typeof schema>) {
|
||||
const response = await server.create(values)
|
||||
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="secondary" size="none">
|
||||
<CirclePlus className="size-8 m-2" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create server</DialogTitle>
|
||||
40
app/components/modals/delete-server-confirm-modal.tsx
Normal file
40
app/components/modals/delete-server-confirm-modal.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
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.delet((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>
|
||||
)
|
||||
}
|
||||
112
app/components/modals/update-profile-modal.tsx
Normal file
112
app/components/modals/update-profile-modal.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
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
|
||||
|
||||
let form = useForm<z.infer<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
const onOpenChange = () => {
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof schema>) => {
|
||||
if (!values)
|
||||
return
|
||||
|
||||
let avatarId = undefined
|
||||
if (values.avatar) {
|
||||
avatarId = (await file.uploadFile(values.avatar))[0]
|
||||
}
|
||||
|
||||
const response = 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
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Check } from "lucide-react"
|
||||
import { NavLink } from "react-router"
|
||||
import type { RecipientChannel } from "~/lib/api/types"
|
||||
import { cn } from "~/lib/utils"
|
||||
import { useUserStore } from "~/store/user"
|
||||
import { OnlineStatus } from "./online-status"
|
||||
import { Avatar, AvatarImage } from "./ui/avatar"
|
||||
import { Badge } from "./ui/badge"
|
||||
|
||||
interface PrivateChannelListItemProps {
|
||||
channel: RecipientChannel
|
||||
}
|
||||
|
||||
export default function PrivateChannelListItem({ channel }: PrivateChannelListItemProps) {
|
||||
const userId = useUserStore(state => state.user?.id)
|
||||
const recipients = channel.recipients.filter(recipient => recipient.id !== userId);
|
||||
const renderSystemBadge = recipients.some(recipient => recipient.system) && recipients.length === 1
|
||||
|
||||
return (
|
||||
<>
|
||||
<NavLink to={`/app/@me/channels/${channel.id}`} className={({ isActive }) =>
|
||||
cn(
|
||||
"rounded-xl justify-start",
|
||||
isActive ? "bg-primary/20" : "bg-accent",
|
||||
)
|
||||
}>
|
||||
<div className="flex items-center gap-2 max-w-72 p-2">
|
||||
<div>
|
||||
<OnlineStatus status="online">
|
||||
<Avatar>
|
||||
<AvatarImage src={`https://api.dicebear.com/9.x/bottts/jpg?seed=${channel.name}`} />
|
||||
</Avatar>
|
||||
</OnlineStatus>
|
||||
</div>
|
||||
<div className="truncate">
|
||||
{recipients.map(recipient => recipient.displayName || recipient.username).join(", ")}
|
||||
</div>
|
||||
{renderSystemBadge && <Badge variant="default"> <Check /> System</Badge>}
|
||||
</div>
|
||||
</NavLink>
|
||||
</>
|
||||
)
|
||||
}
|
||||
28
app/components/providers/modal-provider.tsx
Normal file
28
app/components/providers/modal-provider.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
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 />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react"
|
||||
|
||||
type Theme = "dark" | "light" | "system"
|
||||
export type Theme = "dark" | "light" | "system"
|
||||
|
||||
type ThemeProviderProps = {
|
||||
children: React.ReactNode
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
|
||||
import { useTheme } from "~/components/theme/theme-provider"
|
||||
|
||||
import { useTheme, type Theme } from "~/components/theme/theme-provider"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger
|
||||
} from "~/components/ui/dropdown-menu"
|
||||
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { setTheme } = useTheme()
|
||||
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
@@ -21,16 +22,18 @@ export function ThemeToggle() {
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setTheme("light")}>
|
||||
Light
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme("dark")}>
|
||||
Dark
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme("system")}>
|
||||
System
|
||||
</DropdownMenuItem>
|
||||
<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>
|
||||
)
|
||||
|
||||
9
app/components/ui/aspect-ratio.tsx
Normal file
9
app/components/ui/aspect-ratio.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
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 }
|
||||
@@ -7,9 +7,11 @@ function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
scrollbarSize,
|
||||
viewportRef,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
|
||||
scrollbarSize?: "default" | "narrow" | "none"
|
||||
scrollbarSize?: "default" | "narrow" | "none",
|
||||
viewportRef?: React.Ref<HTMLDivElement>
|
||||
}) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
@@ -18,6 +20,7 @@ function ScrollArea({
|
||||
{...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"
|
||||
>
|
||||
|
||||
183
app/components/ui/select.tsx
Normal file
183
app/components/ui/select.tsx
Normal file
@@ -0,0 +1,183 @@
|
||||
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,
|
||||
}
|
||||
19
app/components/user-avatar.tsx
Normal file
19
app/components/user-avatar.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
102
app/components/visible-trigger.tsx
Normal file
102
app/components/visible-trigger.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
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>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user