This commit is contained in:
2025-05-21 08:52:33 +03:00
parent e992d388fb
commit 4e5fca2402
68 changed files with 358 additions and 1398 deletions

View File

@@ -1,3 +1,9 @@
{ {
"tabWidth": 4 "tabWidth": 4,
"useTabs": false,
"endOfLine": "lf",
"trailingComma": "all",
"bracketSameLine": false,
"printWidth": 120,
"bracketSpacing": true
} }

View File

@@ -5,8 +5,8 @@
@theme { @theme {
--font-sans: --font-sans:
"Inter", ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Inter", ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol",
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; "Noto Color Emoji";
} }
:root { :root {
@@ -48,16 +48,11 @@
--radius: 0.375rem; --radius: 0.375rem;
--shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
--shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
--shadow-sm: --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); --shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
--shadow: --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1);
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1);
--shadow-md: --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1);
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1);
--shadow-lg:
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1);
--shadow-xl:
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1);
--shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25); --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25);
} }
@@ -100,16 +95,11 @@
--radius: 0.375rem; --radius: 0.375rem;
--shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
--shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
--shadow-sm: --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); --shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1);
--shadow: --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1);
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1);
--shadow-md: --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1);
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1);
--shadow-lg:
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1);
--shadow-xl:
0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1);
--shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25); --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25);
} }

View File

@@ -14,9 +14,7 @@ interface AppLayoutProps {
} }
export default function AppLayout({ children }: AppLayoutProps) { export default function AppLayout({ children }: AppLayoutProps) {
let servers = Object.values( let servers = Object.values(useServerListStore(useShallow((state) => state.servers)));
useServerListStore(useShallow((state) => state.servers)),
);
const matches = useMatches(); const matches = useMatches();
@@ -58,9 +56,7 @@ export default function AppLayout({ children }: AppLayoutProps) {
</aside> </aside>
</ScrollArea> </ScrollArea>
</div> </div>
<div className="col-start-2 row-start-1 col-span-1 row-span-1 overflow-hidden"> <div className="col-start-2 row-start-1 col-span-1 row-span-1 overflow-hidden">{list}</div>
{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"> <div className="col-start-1 row-start-2 col-span-2 row-span-1 mb-2 mx-2 min-w-fit z-1">
<UserStatus /> <UserStatus />

View File

@@ -1,7 +1,4 @@
import { import { useInfiniteQuery, type QueryFunctionContext } from "@tanstack/react-query";
useInfiniteQuery,
type QueryFunctionContext,
} from "@tanstack/react-query";
import type { Channel, Message, MessageId } from "~/lib/api/types"; import type { Channel, Message, MessageId } from "~/lib/api/types";
import ChatMessage from "./chat-message"; import ChatMessage from "./chat-message";
import MessageBox from "./message-box"; import MessageBox from "./message-box";
@@ -17,33 +14,18 @@ export default function ChannelArea({ channel }: ChannelAreaProps) {
const fetchMessages = async ({ pageParam }: QueryFunctionContext) => { const fetchMessages = async ({ pageParam }: QueryFunctionContext) => {
return await import("~/lib/api/client/channel").then((m) => return await import("~/lib/api/client/channel").then((m) =>
m.default.paginatedMessages( m.default.paginatedMessages(channelId, 50, pageParam as MessageId | undefined),
channelId,
50,
pageParam as MessageId | undefined,
),
); );
}; };
const { const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, isPending, status } =
data, useInfiniteQuery({
error, queryKey: ["messages", channelId],
fetchNextPage, initialPageParam: undefined,
hasNextPage, queryFn: fetchMessages,
isFetching, getNextPageParam: (lastPage) => (lastPage.length < 50 ? undefined : lastPage[lastPage.length - 1]?.id),
isFetchingNextPage, staleTime: Infinity,
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 = () => { const fetchNextPageVisible = () => {
if (!isFetchingNextPage && hasNextPage) fetchNextPage(); if (!isFetchingNextPage && hasNextPage) fetchNextPage();
@@ -63,10 +45,7 @@ export default function ChannelArea({ channel }: ChannelAreaProps) {
<div className="flex-1" /> <div className="flex-1" />
<div className="flex flex-col-reverse overflow-auto gap-2 pb-2 pr-2"> <div className="flex flex-col-reverse overflow-auto gap-2 pb-2 pr-2">
{status === "success" && renderMessages(data.pages)} {status === "success" && renderMessages(data.pages)}
<VisibleTrigger <VisibleTrigger triggerOnce={false} onVisible={fetchNextPageVisible} />
triggerOnce={false}
onVisible={fetchNextPageVisible}
/>
</div> </div>
</> </>
); );
@@ -75,12 +54,8 @@ export default function ChannelArea({ channel }: ChannelAreaProps) {
return ( return (
<> <>
<div className="flex flex-col size-full"> <div className="flex flex-col size-full">
<div className="w-full min-h-12 border-b-2 flex items-center justify-center"> <div className="w-full min-h-12 border-b-2 flex items-center justify-center">{channel?.name}</div>
{channel?.name} <div className="flex-1 overflow-y-auto flex flex-col pl-2 pr-0.5">{messageArea}</div>
</div>
<div className="flex-1 overflow-y-auto flex flex-col pl-2 pr-0.5">
{messageArea}
</div>
<div className="w-full"> <div className="w-full">
<MessageBox channelId={channelId} /> <MessageBox channelId={channelId} />
</div> </div>
@@ -95,22 +70,13 @@ function renderMessages(pages: Message[][]) {
const formatMessageDate = (date: Date) => { const formatMessageDate = (date: Date) => {
const now = new Date(); const now = new Date();
const today = new Date( const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
now.getFullYear(),
now.getMonth(),
now.getDate(),
);
const yesterday = new Date(today); const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1); yesterday.setDate(yesterday.getDate() - 1);
const messageDate = new Date( const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
date.getFullYear(),
date.getMonth(),
date.getDate(),
);
const capitalize = (str: string) => const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
str.charAt(0).toUpperCase() + str.slice(1);
if (messageDate.getTime() === today.getTime()) { if (messageDate.getTime() === today.getTime()) {
const rtf = new Intl.RelativeTimeFormat(undefined, { const rtf = new Intl.RelativeTimeFormat(undefined, {

View File

@@ -10,12 +10,7 @@ import {
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
} from "~/components/ui/dialog"; // Shadcn UI Dialog } from "~/components/ui/dialog"; // Shadcn UI Dialog
import { import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "~/components/ui/tooltip"; // Shadcn UI Tooltip
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "~/components/ui/tooltip"; // Shadcn UI Tooltip
import type { UploadedFile } from "~/lib/api/types"; // Adjust path as needed import type { UploadedFile } from "~/lib/api/types"; // Adjust path as needed
import { formatFileSize } from "~/lib/utils"; // Adjust path import { formatFileSize } from "~/lib/utils"; // Adjust path
import { FileIcon } from "./file-icon"; import { FileIcon } from "./file-icon";
@@ -24,9 +19,7 @@ interface ChatMessageAttachmentProps {
file: UploadedFile; file: UploadedFile;
} }
export default function ChatMessageAttachment({ export default function ChatMessageAttachment({ file }: ChatMessageAttachmentProps) {
file,
}: ChatMessageAttachmentProps) {
if (file.contentType.startsWith("image/")) { if (file.contentType.startsWith("image/")) {
return <ImageAttachment file={file} />; return <ImageAttachment file={file} />;
} }
@@ -38,29 +31,17 @@ function GenericFileAttachment({ file }: ChatMessageAttachmentProps) {
<TooltipProvider delayDuration={100}> <TooltipProvider delayDuration={100}>
<div className="flex items-center gap-3 rounded-lg border bg-card p-3 shadow-sm "> <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"> <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md">
<FileIcon <FileIcon className="h-8 w-8 text-muted-foreground" contentType={file.contentType} />
className="h-8 w-8 text-muted-foreground"
contentType={file.contentType}
/>
</div> </div>
<div className="flex-1 overflow-hidden"> <div className="flex-1 overflow-hidden">
<p className="truncate text-sm font-medium text-card-foreground"> <p className="truncate text-sm font-medium text-card-foreground">{file.filename}</p>
{file.filename} <p className="text-xs text-muted-foreground">{formatFileSize(file.size)}</p>
</p>
<p className="text-xs text-muted-foreground">
{formatFileSize(file.size)}
</p>
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant="ghost" size="icon" asChild> <Button variant="ghost" size="icon" asChild>
<a <a href={file.url} target="_blank" rel="noreferrer" download={file.filename}>
href={file.url}
target="_blank"
rel="noreferrer"
download={file.filename}
>
<Download className="h-4 w-4" /> <Download className="h-4 w-4" />
<span className="sr-only">Download</span> <span className="sr-only">Download</span>
</a> </a>
@@ -71,15 +52,9 @@ function GenericFileAttachment({ file }: ChatMessageAttachmentProps) {
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant="ghost" size="icon" asChild> <Button variant="ghost" size="icon" asChild>
<a <a href={file.url} target="_blank" rel="noreferrer">
href={file.url}
target="_blank"
rel="noreferrer"
>
<ExternalLink className="h-4 w-4" /> <ExternalLink className="h-4 w-4" />
<span className="sr-only"> <span className="sr-only">Open in new tab</span>
Open in new tab
</span>
</a> </a>
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -97,10 +72,7 @@ function ImageAttachment({ file }: ChatMessageAttachmentProps) {
<TooltipProvider delayDuration={100}> <TooltipProvider delayDuration={100}>
<div className="group relative w-48 cursor-pointer sm:w-64"> <div className="group relative w-48 cursor-pointer sm:w-64">
<DialogTrigger asChild> <DialogTrigger asChild>
<AspectRatio <AspectRatio ratio={16 / 9} className="overflow-hidden rounded-lg border bg-muted">
ratio={16 / 9}
className="overflow-hidden rounded-lg border bg-muted"
>
<img <img
src={file.url} src={file.url}
alt={file.filename} alt={file.filename}
@@ -121,9 +93,7 @@ function ImageAttachment({ file }: ChatMessageAttachmentProps) {
<DialogContent className="max-w-3xl p-0"> <DialogContent className="max-w-3xl p-0">
<DialogHeader className="p-4 pb-0"> <DialogHeader className="p-4 pb-0">
<DialogTitle className="truncate"> <DialogTitle className="truncate">{file.filename}</DialogTitle>
{file.filename}
</DialogTitle>
</DialogHeader> </DialogHeader>
<div className="p-4 pt-0 max-h-[70vh] overflow-y-auto"> <div className="p-4 pt-0 max-h-[70vh] overflow-y-auto">
<img <img
@@ -135,8 +105,7 @@ function ImageAttachment({ file }: ChatMessageAttachmentProps) {
<DialogFooter className="flex-col items-stretch gap-2 border-t p-4 sm:flex-row sm:justify-end sm:space-x-2"> <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> <Button variant="outline" asChild>
<a href={file.url} target="_blank" rel="noreferrer"> <a href={file.url} target="_blank" rel="noreferrer">
<ExternalLink className="mr-2 h-4 w-4" /> Open <ExternalLink className="mr-2 h-4 w-4" /> Open original
original
</a> </a>
</Button> </Button>
<Button asChild> <Button asChild>

View File

@@ -25,19 +25,11 @@ export default function ChatMessage({ message }: ChatMessageProps) {
const formatMessageDate = (date: Date) => { const formatMessageDate = (date: Date) => {
const now = new Date(); const now = new Date();
const today = new Date( const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
now.getFullYear(),
now.getMonth(),
now.getDate(),
);
const yesterday = new Date(today); const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1); yesterday.setDate(yesterday.getDate() - 1);
const messageDate = new Date( const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
date.getFullYear(),
date.getMonth(),
date.getDate(),
);
// Get localized time string // Get localized time string
const timeString = date.toLocaleTimeString(undefined, { const timeString = date.toLocaleTimeString(undefined, {
@@ -45,8 +37,7 @@ export default function ChatMessage({ message }: ChatMessageProps) {
minute: "2-digit", minute: "2-digit",
hour12: false, hour12: false,
}); });
const capitalize = (str: string) => const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
str.charAt(0).toUpperCase() + str.slice(1);
if (messageDate.getTime() === today.getTime()) { if (messageDate.getTime() === today.getTime()) {
// Use Intl.RelativeTimeFormat for localized "Today" // Use Intl.RelativeTimeFormat for localized "Today"
@@ -96,9 +87,7 @@ export default function ChatMessage({ message }: ChatMessageProps) {
</div> </div>
</div> </div>
<div className="row-start-2 col-start-2 row-span-1 col-span-1"> <div className="row-start-2 col-start-2 row-span-1 col-span-1">
<div className="wrap-break-word contain-inline-size"> <div className="wrap-break-word contain-inline-size">{message.content}</div>
{message.content}
</div>
<div className="grid gap-2 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 justify-start"> <div className="grid gap-2 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 justify-start">
{message.attachments.map((file, i) => ( {message.attachments.map((file, i) => (
<div key={file.id}> <div key={file.id}>

View File

@@ -10,12 +10,7 @@ import { useGatewayStore } from "~/stores/gateway-store";
import { useUsersStore } from "~/stores/users-store"; import { useUsersStore } from "~/stores/users-store";
import { useVoiceStateStore } from "~/stores/voice-state-store"; import { useVoiceStateStore } from "~/stores/voice-state-store";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import { import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "../ui/context-menu";
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
} from "../ui/context-menu";
import UserAvatar from "../user-avatar"; import UserAvatar from "../user-avatar";
interface ChannelListItemProps { interface ChannelListItemProps {
@@ -41,11 +36,8 @@ function ServerCategory({ channel }: ChannelListItemProps) {
function ServerVoice({ channel }: ChannelListItemProps) { function ServerVoice({ channel }: ChannelListItemProps) {
const updateVoiceState = useGatewayStore((state) => state.updateVoiceState); const updateVoiceState = useGatewayStore((state) => state.updateVoiceState);
const voiceStateChannel = useVoiceStateStore( const voiceStateChannel = useVoiceStateStore((state) => state.activeChannel);
(state) => state.activeChannel, const channelVoiceState = useChannelsVoiceStateStore((state) => state.channels[channel.id]) || {};
);
const channelVoiceState =
useChannelsVoiceStateStore((state) => state.channels[channel.id]) || {};
const userIds = Object.keys(channelVoiceState.users ?? {}); const userIds = Object.keys(channelVoiceState.users ?? {});
const { users, fetchUsersIfNotPresent } = useUsersStore( const { users, fetchUsersIfNotPresent } = useUsersStore(
@@ -55,21 +47,14 @@ function ServerVoice({ channel }: ChannelListItemProps) {
})), })),
); );
const channelUsers = React.useMemo( const channelUsers = React.useMemo(() => userIds.map((userId) => users[userId]).filter(Boolean), [userIds, users]);
() => userIds.map((userId) => users[userId]).filter(Boolean),
[userIds, users],
);
React.useEffect(() => { React.useEffect(() => {
fetchUsersIfNotPresent(userIds); fetchUsersIfNotPresent(userIds);
}, [userIds]); }, [userIds]);
const onClick = () => { const onClick = () => {
if ( if (voiceStateChannel?.serverId === channel.serverId && voiceStateChannel.channelId === channel.id) return;
voiceStateChannel?.serverId === channel.serverId &&
voiceStateChannel.channelId === channel.id
)
return;
updateVoiceState(channel.serverId, channel.id); updateVoiceState(channel.serverId, channel.id);
}; };
@@ -78,12 +63,7 @@ function ServerVoice({ channel }: ChannelListItemProps) {
<> <>
<ContextMenu> <ContextMenu>
<ContextMenuTrigger asChild> <ContextMenuTrigger asChild>
<Button <Button variant="secondary" size="sm" className="justify-start" onClick={onClick}>
variant="secondary"
size="sm"
className="justify-start"
onClick={onClick}
>
<div className="flex items-center gap-2 max-w-72"> <div className="flex items-center gap-2 max-w-72">
<div> <div>
<Volume2 /> <Volume2 />
@@ -93,10 +73,7 @@ function ServerVoice({ channel }: ChannelListItemProps) {
</Button> </Button>
</ContextMenuTrigger> </ContextMenuTrigger>
<ContextMenuContent> <ContextMenuContent>
<ContextMenuItem <ContextMenuItem variant="destructive" onClick={() => onDeleteChannel(channel)}>
variant="destructive"
onClick={() => onDeleteChannel(channel)}
>
Delete Delete
</ContextMenuItem> </ContextMenuItem>
</ContextMenuContent> </ContextMenuContent>
@@ -104,10 +81,7 @@ function ServerVoice({ channel }: ChannelListItemProps) {
{channelUsers.length > 0 && ( {channelUsers.length > 0 && (
<div className="ml-2 border-l-2 flex flex-col gap-1"> <div className="ml-2 border-l-2 flex flex-col gap-1">
{channelUsers.map((user) => ( {channelUsers.map((user) => (
<div <div key={user.id} className="flex items-center gap-2 max-w-72 pl-4">
key={user.id}
className="flex items-center gap-2 max-w-72 pl-4"
>
<UserAvatar user={user} className="size-6" /> <UserAvatar user={user} className="size-6" />
{user.displayName || user.username} {user.displayName || user.username}
</div> </div>
@@ -120,10 +94,7 @@ function ServerVoice({ channel }: ChannelListItemProps) {
function ServerText({ channel }: ChannelListItemProps) { function ServerText({ channel }: ChannelListItemProps) {
return ( return (
<NavLink <NavLink to={`/app/server/${channel.serverId}/${channel.id}`} discover="none">
to={`/app/server/${channel.serverId}/${channel.id}`}
discover="none"
>
{({ isActive }) => ( {({ isActive }) => (
<ContextMenu> <ContextMenu>
<ContextMenuTrigger asChild> <ContextMenuTrigger asChild>
@@ -132,9 +103,7 @@ function ServerText({ channel }: ChannelListItemProps) {
size="sm" size="sm"
className={cn( className={cn(
"justify-start w-full", "justify-start w-full",
isActive isActive ? "bg-accent hover:bg-accent" : "bg-secondary",
? "bg-accent hover:bg-accent"
: "bg-secondary",
)} )}
> >
<div className="flex items-center gap-2 max-w-72"> <div className="flex items-center gap-2 max-w-72">
@@ -146,10 +115,7 @@ function ServerText({ channel }: ChannelListItemProps) {
</Button> </Button>
</ContextMenuTrigger> </ContextMenuTrigger>
<ContextMenuContent> <ContextMenuContent>
<ContextMenuItem <ContextMenuItem variant="destructive" onClick={() => onDeleteChannel(channel)}>
variant="destructive"
onClick={() => onDeleteChannel(channel)}
>
Delete Delete
</ContextMenuItem> </ContextMenuItem>
</ContextMenuContent> </ContextMenuContent>
@@ -159,9 +125,7 @@ function ServerText({ channel }: ChannelListItemProps) {
); );
} }
export default function ServerChannelListItem({ export default function ServerChannelListItem({ channel }: ChannelListItemProps) {
channel,
}: ChannelListItemProps) {
switch (channel.type) { switch (channel.type) {
case ChannelType.SERVER_CATEGORY: case ChannelType.SERVER_CATEGORY:
return <ServerCategory channel={channel} />; return <ServerCategory channel={channel} />;

View File

@@ -7,11 +7,7 @@ export function CreateServerButton() {
const onOpen = useModalStore((state) => state.onOpen); const onOpen = useModalStore((state) => state.onOpen);
return ( return (
<Button <Button variant="outline" size="none" onClick={() => onOpen(ModalType.CREATE_SERVER)}>
variant="outline"
size="none"
onClick={() => onOpen(ModalType.CREATE_SERVER)}
>
<CirclePlus className="size-8 m-2" /> <CirclePlus className="size-8 m-2" />
</Button> </Button>
); );

View File

@@ -6,12 +6,7 @@ export function HomeButton() {
return ( return (
<NavLink to={`/app/@me`}> <NavLink to={`/app/@me`}>
{({ isActive }) => ( {({ isActive }) => (
<Button <Button variant="outline" size="none" asChild className={isActive ? "bg-accent size-12" : "size-12"}>
variant="outline"
size="none"
asChild
className={isActive ? "bg-accent size-12" : "size-12"}
>
<div> <div>
<Discord className="size-full p-2" /> <Discord className="size-full p-2" />
</div> </div>

View File

@@ -10,18 +10,10 @@ export function OnlineStatus({
<div className="relative"> <div className="relative">
<div {...props}></div> <div {...props}></div>
<div className="absolute bottom-0 right-0 bg-background 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" && ( {status === "online" && <Circle className="size-full stroke-emerald-400 fill-emerald-400" />}
<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" />}
{status === "dnd" && ( {status === "offline" && <Circle className="size-full stroke-gray-400 stroke-3" />}
<CircleMinus className="size-full stroke-red-400 stroke-3" />
)}
{status === "idle" && (
<Moon className="size-full stroke-amber-400 fill-amber-400" />
)}
{status === "offline" && (
<Circle className="size-full stroke-gray-400 stroke-3" />
)}
</div> </div>
</div> </div>
); );

View File

@@ -5,8 +5,7 @@ import { Input } from "../ui/input";
export function PasswordInput(props: React.ComponentProps<"input">) { export function PasswordInput(props: React.ComponentProps<"input">) {
const [showPassword, setShowPassword] = React.useState(false); const [showPassword, setShowPassword] = React.useState(false);
const disabled = const disabled = props.value === "" || props.value === undefined || props.disabled;
props.value === "" || props.value === undefined || props.disabled;
return ( return (
<div className="relative"> <div className="relative">
@@ -24,9 +23,7 @@ export function PasswordInput(props: React.ComponentProps<"input">) {
) : ( ) : (
<EyeOffIcon className="h-4 w-4" aria-hidden="true" /> <EyeOffIcon className="h-4 w-4" aria-hidden="true" />
)} )}
<span className="sr-only"> <span className="sr-only">{showPassword ? "Hide password" : "Show password"}</span>
{showPassword ? "Hide password" : "Show password"}
</span>
</Button> </Button>
<style> <style>
{` {`

View File

@@ -12,16 +12,10 @@ interface PrivateChannelListItemProps {
channel: RecipientChannel; channel: RecipientChannel;
} }
export default function PrivateChannelListItem({ export default function PrivateChannelListItem({ channel }: PrivateChannelListItemProps) {
channel,
}: PrivateChannelListItemProps) {
const currentUserId = useUsersStore((state) => state.currentUserId); const currentUserId = useUsersStore((state) => state.currentUserId);
const recipients = channel.recipients.filter( const recipients = channel.recipients.filter((recipient) => recipient.id !== currentUserId);
(recipient) => recipient.id !== currentUserId, const renderSystemBadge = recipients.some((recipient) => recipient.system) && recipients.length === 1;
);
const renderSystemBadge =
recipients.some((recipient) => recipient.system) &&
recipients.length === 1;
return ( return (
<> <>
@@ -40,21 +34,12 @@ export default function PrivateChannelListItem({
<div> <div>
<OnlineStatus status="online"> <OnlineStatus status="online">
<UserAvatar <UserAvatar
user={channel.recipients.find( user={channel.recipients.find((recipient) => recipient.id !== currentUserId)}
(recipient) =>
recipient.id !== currentUserId,
)}
/> />
</OnlineStatus> </OnlineStatus>
</div> </div>
<div className="truncate"> <div className="truncate">
{recipients {recipients.map((recipient) => recipient.displayName || recipient.username).join(", ")}
.map(
(recipient) =>
recipient.displayName ||
recipient.username,
)
.join(", ")}
</div> </div>
{renderSystemBadge && ( {renderSystemBadge && (
<Badge variant="default"> <Badge variant="default">

View File

@@ -12,18 +12,10 @@ export function ServerButton({ server }: ServerButtonProps) {
return ( return (
<NavLink to={`/app/server/${server.id}`}> <NavLink to={`/app/server/${server.id}`}>
{({ isActive }) => ( {({ isActive }) => (
<Button <Button variant="outline" size="none" asChild className={isActive ? "bg-accent" : ""}>
variant="outline"
size="none"
asChild
className={isActive ? "bg-accent" : ""}
>
<div> <div>
<Avatar className="size-12 rounded-none flex items-center justify-center"> <Avatar className="size-12 rounded-none flex items-center justify-center">
<AvatarImage <AvatarImage src={server.iconUrl} className="rounded-none" />
src={server.iconUrl}
className="rounded-none"
/>
<AvatarFallback> <AvatarFallback>
<div>{getFirstLetters(server.name, 4)}</div> <div>{getFirstLetters(server.name, 4)}</div>
</AvatarFallback> </AvatarFallback>

View File

@@ -37,9 +37,7 @@ export function SettingsButton() {
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent> <DropdownMenuContent>
<DropdownMenuItem onClick={onOpenSettings}> <DropdownMenuItem onClick={onOpenSettings}>Settings</DropdownMenuItem>
Settings
</DropdownMenuItem>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={onLogout}> <DropdownMenuItem variant="destructive" onClick={onLogout}>
Logout Logout

View File

@@ -1,13 +1,7 @@
import React, { import React, { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
forwardRef,
useEffect,
useImperativeHandle,
useRef,
} from "react";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
export interface TextBoxProps export interface TextBoxProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange" | "value"> {
extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange" | "value"> {
value: string; value: string;
onChange: (value: string) => void; onChange: (value: string) => void;
placeholder?: string; placeholder?: string;
@@ -47,10 +41,7 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
localRef.current.textContent = newValue; localRef.current.textContent = newValue;
// Clear any <br> elements if the content is empty // Clear any <br> elements if the content is empty
if ( if (!newValue && localRef.current.innerHTML.includes("<br>")) {
!newValue &&
localRef.current.innerHTML.includes("<br>")
) {
localRef.current.innerHTML = ""; localRef.current.innerHTML = "";
} }
} }
@@ -94,10 +85,7 @@ export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
return ( return (
<div <div
className={cn( className={cn("overflow-y-auto overflow-x-hidden w-full min-h-6", wrapperClassName)}
"overflow-y-auto overflow-x-hidden w-full min-h-6",
wrapperClassName,
)}
onClick={() => localRef.current?.focus()} onClick={() => localRef.current?.focus()}
> >
<div <div

View File

@@ -10,23 +10,15 @@ import UserAvatar from "../user-avatar";
import { OnlineStatus } from "./online-status"; import { OnlineStatus } from "./online-status";
import { SettingsButton } from "./settings-button"; import { SettingsButton } from "./settings-button";
function VoiceStatus({ function VoiceStatus({ voiceState }: { voiceState: { serverId: string; channelId: string } }) {
voiceState,
}: {
voiceState: { serverId: string; channelId: string };
}) {
// const webrtcState = useWebRTCStore(state => state.status) // const webrtcState = useWebRTCStore(state => state.status)
const leaveVoiceChannel = () => { const leaveVoiceChannel = () => {
useVoiceStateStore.getState().leaveVoiceChannel(); useVoiceStateStore.getState().leaveVoiceChannel();
}; };
const channel = useServerChannelsStore( const channel = useServerChannelsStore((state) => state.channels[voiceState.serverId]?.[voiceState.channelId]);
(state) => state.channels[voiceState.serverId]?.[voiceState.channelId], const server = useServerListStore((state) => state.servers[voiceState.serverId]);
);
const server = useServerListStore(
(state) => state.servers[voiceState.serverId],
);
return ( return (
<div className="gap-1 flex justify-between items-center "> <div className="gap-1 flex justify-between items-center ">
@@ -63,14 +55,8 @@ export default function UserStatus() {
</OnlineStatus> </OnlineStatus>
<div className="flex flex-col text-sm justify-center"> <div className="flex flex-col text-sm justify-center">
<div className="truncate max-w-30"> <div className="truncate max-w-30">{user?.displayName || user?.username || "Unknown user"}</div>
{user?.displayName || <span className="text-muted-foreground text-xs">@{user?.username}</span>
user?.username ||
"Unknown user"}
</div>
<span className="text-muted-foreground text-xs">
@{user?.username}
</span>
</div> </div>
</div> </div>
<div> <div>

View File

@@ -31,25 +31,19 @@ export function FileIcon({ contentType, className, ...props }: FileIconProps) {
} }
if ( if (
contentType.startsWith("application/vnd.ms-excel") || contentType.startsWith("application/vnd.ms-excel") ||
contentType.startsWith( contentType.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml")
"application/vnd.openxmlformats-officedocument.spreadsheetml",
)
) { ) {
return <FileSpreadsheet {...commonProps} />; // Could use a specific Excel icon if available/desired return <FileSpreadsheet {...commonProps} />; // Could use a specific Excel icon if available/desired
} }
if ( if (
contentType.startsWith("application/msword") || contentType.startsWith("application/msword") ||
contentType.startsWith( contentType.startsWith("application/vnd.openxmlformats-officedocument.wordprocessingml")
"application/vnd.openxmlformats-officedocument.wordprocessingml",
)
) { ) {
return <FileText {...commonProps} />; return <FileText {...commonProps} />;
} }
if ( if (
contentType.startsWith("application/vnd.ms-powerpoint") || contentType.startsWith("application/vnd.ms-powerpoint") ||
contentType.startsWith( contentType.startsWith("application/vnd.openxmlformats-officedocument.presentationml")
"application/vnd.openxmlformats-officedocument.presentationml",
)
) { ) {
return <FileText {...commonProps} />; return <FileText {...commonProps} />;
} }

View File

@@ -7,12 +7,7 @@ import type { Uuid } from "~/lib/api/types"; // Adjust path
import { cn, formatFileSize } from "~/lib/utils"; // 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 TextBox from "./custom-ui/text-box"; // Adjust path, assuming TextBox is in ./custom-ui/
import { Button } from "./ui/button"; // Adjust path import { Button } from "./ui/button"; // Adjust path
import { import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; // Adjust path
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "./ui/tooltip"; // Adjust path
export interface MessageBoxProps { export interface MessageBoxProps {
channelId: string; channelId: string;
@@ -87,8 +82,7 @@ export default function MessageBox({ channelId }: MessageBoxProps) {
setTimeout(() => textBoxRef.current?.focus(), 0); setTimeout(() => textBoxRef.current?.focus(), 0);
}, [channelId]); }, [channelId]);
const canSend = const canSend = (text.trim().length > 0 || attachments.length > 0) && !isLoading;
(text.trim().length > 0 || attachments.length > 0) && !isLoading;
const attachmentsRemaining = 10 - attachments.length; const attachmentsRemaining = 10 - attachments.length;
return ( return (
@@ -100,17 +94,10 @@ export default function MessageBox({ channelId }: MessageBoxProps) {
key={`${file.name}-${file.lastModified}-${i}`} key={`${file.name}-${file.lastModified}-${i}`}
className="flex items-center gap-2.5 rounded-md border bg-card p-2 text-sm shadow-sm" className="flex items-center gap-2.5 rounded-md border bg-card p-2 text-sm shadow-sm"
> >
<FileIcon <FileIcon contentType={file.type} className="h-7 w-7 flex-shrink-0 text-muted-foreground" />
contentType={file.type}
className="h-7 w-7 flex-shrink-0 text-muted-foreground"
/>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate font-medium text-card-foreground"> <p className="truncate font-medium text-card-foreground">{file.name}</p>
{file.name} <p className="text-xs text-muted-foreground">{formatFileSize(file.size)}</p>
</p>
<p className="text-xs text-muted-foreground">
{formatFileSize(file.size)}
</p>
</div> </div>
<TooltipProvider delayDuration={100}> <TooltipProvider delayDuration={100}>
<Tooltip> <Tooltip>
@@ -164,9 +151,7 @@ export default function MessageBox({ channelId }: MessageBoxProps) {
size="icon" size="icon"
variant="ghost" variant="ghost"
onClick={addAttachment} onClick={addAttachment}
disabled={ disabled={attachments.length >= 10 || isLoading}
attachments.length >= 10 || isLoading
}
aria-label="Add attachment" aria-label="Add attachment"
> >
<Paperclip className="h-5 w-5" /> <Paperclip className="h-5 w-5" />
@@ -177,10 +162,7 @@ export default function MessageBox({ channelId }: MessageBoxProps) {
{attachments.length >= 10 ? ( {attachments.length >= 10 ? (
<p>Maximum 10 attachments</p> <p>Maximum 10 attachments</p>
) : ( ) : (
<p> <p>Add attachment ({attachmentsRemaining} remaining)</p>
Add attachment ({attachmentsRemaining}{" "}
remaining)
</p>
)} )}
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
@@ -207,11 +189,7 @@ export default function MessageBox({ channelId }: MessageBoxProps) {
disabled={!canSend} disabled={!canSend}
aria-label="Send message" aria-label="Send message"
> >
{isLoading ? ( {isLoading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Send className="h-5 w-5" />}
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Send className="h-5 w-5" />
)}
</Button> </Button>
</div> </div>
</div> </div>

View File

@@ -2,11 +2,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
import { ChannelType } from "~/lib/api/types"; import { ChannelType } from "~/lib/api/types";
import { import { ModalType, useModalStore, type CreateServerChannelModalData } from "~/stores/modal-store";
ModalType,
useModalStore,
type CreateServerChannelModalData,
} from "~/stores/modal-store";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import { import {
Dialog, Dialog,
@@ -17,22 +13,9 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "../ui/dialog"; } from "../ui/dialog";
import { import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
import { Input } from "../ui/input"; import { Input } from "../ui/input";
import { import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "../ui/select";
const schema = z.object({ const schema = z.object({
name: z.string().min(1).max(32), name: z.string().min(1).max(32),
@@ -58,10 +41,7 @@ export default function CreateServerChannelModal() {
const onSubmit = async (values: z.infer<typeof schema>) => { const onSubmit = async (values: z.infer<typeof schema>) => {
const response = await import("~/lib/api/client/server").then((m) => const response = await import("~/lib/api/client/server").then((m) =>
m.default.createChannel( m.default.createChannel((data as CreateServerChannelModalData["data"]).serverId, values),
(data as CreateServerChannelModalData["data"]).serverId,
values,
),
); );
form.reset(); form.reset();
@@ -73,28 +53,17 @@ export default function CreateServerChannelModal() {
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle>Create channel</DialogTitle> <DialogTitle>Create channel</DialogTitle>
<DialogDescription> <DialogDescription>Give your channel a name and choose a channel type.</DialogDescription>
Give your channel a name and choose a channel type.
</DialogDescription>
</DialogHeader> </DialogHeader>
<Form {...form}> <Form {...form}>
<form <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField <FormField
control={form.control} control={form.control}
name="name" name="name"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
required={
!schema.shape.name.isOptional()
}
>
Name
</FormLabel>
<FormControl> <FormControl>
<Input {...field} /> <Input {...field} />
</FormControl> </FormControl>
@@ -107,17 +76,8 @@ export default function CreateServerChannelModal() {
name="type" name="type"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.type.isOptional()}>Type</FormLabel>
required={ <Select defaultValue={field.value} onValueChange={field.onChange}>
!schema.shape.type.isOptional()
}
>
Type
</FormLabel>
<Select
defaultValue={field.value}
onValueChange={field.onChange}
>
<FormControl> <FormControl>
<SelectTrigger className="w-full"> <SelectTrigger className="w-full">
<SelectValue placeholder="Select a channel type" /> <SelectValue placeholder="Select a channel type" />
@@ -125,15 +85,10 @@ export default function CreateServerChannelModal() {
</FormControl> </FormControl>
<SelectContent> <SelectContent>
{Object.entries({ {Object.entries({
[ChannelType.SERVER_TEXT]: [ChannelType.SERVER_TEXT]: "Text",
"Text", [ChannelType.SERVER_VOICE]: "Voice",
[ChannelType.SERVER_VOICE]:
"Voice",
}).map(([type, label]) => ( }).map(([type, label]) => (
<SelectItem <SelectItem key={type} value={type}>
key={type}
value={type}
>
{label} {label}
</SelectItem> </SelectItem>
))} ))}
@@ -149,13 +104,8 @@ export default function CreateServerChannelModal() {
Close Close
</Button> </Button>
</DialogClose> </DialogClose>
<Button <Button type="submit" disabled={form.formState.isSubmitting}>
type="submit" {form.formState.isSubmitting ? "Creating..." : "Create"}
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting
? "Creating..."
: "Create"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>

View File

@@ -3,21 +3,13 @@ import React from "react";
import { useOrigin } from "~/hooks/use-origin"; import { useOrigin } from "~/hooks/use-origin";
import { ModalType, useModalStore } from "~/stores/modal-store"; import { ModalType, useModalStore } from "~/stores/modal-store";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import { import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input"; import { Input } from "../ui/input";
import { Label } from "../ui/label"; import { Label } from "../ui/label";
export default function CreateServerInviteModal() { export default function CreateServerInviteModal() {
const { type, data, isOpen, onClose } = useModalStore(); const { type, data, isOpen, onClose } = useModalStore();
const [inviteCode, setInviteCode] = React.useState<string | undefined>( const [inviteCode, setInviteCode] = React.useState<string | undefined>(undefined);
undefined,
);
const origin = useOrigin(); const origin = useOrigin();
const [isCopied, setCopied] = React.useState(false); const [isCopied, setCopied] = React.useState(false);
@@ -30,9 +22,7 @@ export default function CreateServerInviteModal() {
const regenerateInviteCode = () => { const regenerateInviteCode = () => {
import("~/lib/api/client/server") import("~/lib/api/client/server")
.then((m) => .then((m) => m.default.createInvite((data as { serverId: string }).serverId))
m.default.createInvite((data as { serverId: string }).serverId),
)
.then((invite) => { .then((invite) => {
setInviteCode(invite.code); setInviteCode(invite.code);
}); });
@@ -48,11 +38,7 @@ export default function CreateServerInviteModal() {
React.useEffect(() => { React.useEffect(() => {
if (isModalOpen) { if (isModalOpen) {
import("~/lib/api/client/server") import("~/lib/api/client/server")
.then((m) => .then((m) => m.default.createInvite((data as { serverId: string }).serverId))
m.default.createInvite(
(data as { serverId: string }).serverId,
),
)
.then((invite) => { .then((invite) => {
setInviteCode(invite.code); setInviteCode(invite.code);
}); });
@@ -72,20 +58,11 @@ export default function CreateServerInviteModal() {
<div className="flex items-center gap-x-2"> <div className="flex items-center gap-x-2">
<Input value={inviteLink} readOnly /> <Input value={inviteLink} readOnly />
<Button variant="ghost" size="icon" onClick={onCopy}> <Button variant="ghost" size="icon" onClick={onCopy}>
{isCopied ? ( {isCopied ? <Check className="size-4" /> : <Copy className="size-4" />}
<Check className="size-4" />
) : (
<Copy className="size-4" />
)}
</Button> </Button>
</div> </div>
<DialogFooter> <DialogFooter>
<Button <Button variant="link" size="none" className="h-9 py-2" onClick={regenerateInviteCode}>
variant="link"
size="none"
className="h-9 py-2"
onClick={regenerateInviteCode}
>
Generate a new invite Generate a new invite
<RefreshCw /> <RefreshCw />
</Button> </Button>

View File

@@ -14,14 +14,7 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "../ui/dialog"; } from "../ui/dialog";
import { import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
import { IconUploadField } from "../ui/icon-upload-field"; import { IconUploadField } from "../ui/icon-upload-field";
import { Input } from "../ui/input"; import { Input } from "../ui/input";
@@ -64,34 +57,20 @@ export default function CreateServerModal() {
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle>Create server</DialogTitle> <DialogTitle>Create server</DialogTitle>
<DialogDescription> <DialogDescription>Give your server a name and choose a server icon.</DialogDescription>
Give your server a name and choose a server icon.
</DialogDescription>
</DialogHeader> </DialogHeader>
<Form {...form}> <Form {...form}>
<form <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField <FormField
control={form.control} control={form.control}
name="icon" name="icon"
render={({ field, fieldState }) => ( render={({ field, fieldState }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.icon.isOptional()}>Icon</FormLabel>
required={
!schema.shape.icon.isOptional()
}
>
Icon
</FormLabel>
<FormControl> <FormControl>
<div className="flex flex-col items-center justify-center"> <div className="flex flex-col items-center justify-center">
<IconUploadField <IconUploadField field={field} error={fieldState.error} />
field={field}
error={fieldState.error}
/>
</div> </div>
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
@@ -103,13 +82,7 @@ export default function CreateServerModal() {
name="name" name="name"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
required={
!schema.shape.name.isOptional()
}
>
Name
</FormLabel>
<FormControl> <FormControl>
<Input {...field} /> <Input {...field} />
</FormControl> </FormControl>
@@ -123,13 +96,8 @@ export default function CreateServerModal() {
Close Close
</Button> </Button>
</DialogClose> </DialogClose>
<Button <Button type="submit" disabled={form.formState.isSubmitting}>
type="submit" {form.formState.isSubmitting ? "Creating..." : "Create"}
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting
? "Creating..."
: "Create"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>

View File

@@ -1,13 +1,6 @@
import { ModalType, useModalStore } from "~/stores/modal-store"; import { ModalType, useModalStore } from "~/stores/modal-store";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import { import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../ui/dialog";
export default function DeleteServerConfirmModal() { export default function DeleteServerConfirmModal() {
const { type, data, isOpen, onClose } = useModalStore(); const { type, data, isOpen, onClose } = useModalStore();
@@ -19,9 +12,7 @@ export default function DeleteServerConfirmModal() {
}; };
const onConfirm = async () => { const onConfirm = async () => {
await import("~/lib/api/client/server").then((m) => await import("~/lib/api/client/server").then((m) => m.default.delet((data as { serverId: string }).serverId));
m.default.delet((data as { serverId: string }).serverId),
);
onClose(); onClose();
}; };
@@ -30,9 +21,7 @@ export default function DeleteServerConfirmModal() {
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle>Are you sure?</DialogTitle> <DialogTitle>Are you sure?</DialogTitle>
<DialogDescription> <DialogDescription>This action cannot be undone.</DialogDescription>
This action cannot be undone.
</DialogDescription>
</DialogHeader> </DialogHeader>
<DialogFooter className="justify-between"> <DialogFooter className="justify-between">

View File

@@ -16,14 +16,7 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "../ui/dialog"; } from "../ui/dialog";
import { import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
import { IconUploadField } from "../ui/icon-upload-field"; import { IconUploadField } from "../ui/icon-upload-field";
import { Input } from "../ui/input"; import { Input } from "../ui/input";
@@ -52,8 +45,7 @@ export default function UpdateProfileModal() {
if (!values) return; if (!values) return;
let avatarId: string | null | undefined = let avatarId: string | null | undefined = values.avatar === null ? null : undefined;
values.avatar === null ? null : undefined;
if (values.avatar) { if (values.avatar) {
avatarId = (await file.uploadFile(values.avatar))[0]; avatarId = (await file.uploadFile(values.avatar))[0];
} }
@@ -76,29 +68,18 @@ export default function UpdateProfileModal() {
</DialogHeader> </DialogHeader>
<Form {...form}> <Form {...form}>
<form <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField <FormField
control={form.control} control={form.control}
name="avatar" name="avatar"
render={({ field, fieldState }) => ( render={({ field, fieldState }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.avatar.isOptional()}>Avatar</FormLabel>
required={
!schema.shape.avatar.isOptional()
}
>
Avatar
</FormLabel>
<FormControl> <FormControl>
<div className="flex flex-col items-center justify-center"> <div className="flex flex-col items-center justify-center">
<IconUploadField <IconUploadField
defaultPreview={user?.avatarUrl} defaultPreview={user?.avatarUrl}
formDefaultValue={ formDefaultValue={user?.avatarUrl}
user?.avatarUrl
}
field={field} field={field}
error={fieldState.error} error={fieldState.error}
/> />
@@ -113,18 +94,11 @@ export default function UpdateProfileModal() {
name="displayName" name="displayName"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.displayName.isOptional()}>
required={
!schema.shape.displayName.isOptional()
}
>
Display Name Display Name
</FormLabel> </FormLabel>
<FormControl> <FormControl>
<Input <Input {...field} placeholder={user?.displayName} />
{...field}
placeholder={user?.displayName}
/>
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -136,13 +110,8 @@ export default function UpdateProfileModal() {
Close Close
</Button> </Button>
</DialogClose> </DialogClose>
<Button <Button type="submit" disabled={form.formState.isSubmitting}>
type="submit" {form.formState.isSubmitting ? "Updating..." : "Update"}
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting
? "Updating..."
: "Update"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>

View File

@@ -26,9 +26,7 @@ export function ThemeProvider({
storageKey = "ui-theme", storageKey = "ui-theme",
...props ...props
}: ThemeProviderProps) { }: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>( const [theme, setTheme] = useState<Theme>(() => (localStorage.getItem(storageKey) as Theme) || defaultTheme);
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
);
useEffect(() => { useEffect(() => {
const root = window.document.documentElement; const root = window.document.documentElement;
@@ -36,11 +34,7 @@ export function ThemeProvider({
root.classList.remove("light", "dark"); root.classList.remove("light", "dark");
if (theme === "system") { if (theme === "system") {
const systemTheme = window.matchMedia( const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
"(prefers-color-scheme: dark)",
).matches
? "dark"
: "light";
root.classList.add(systemTheme); root.classList.add(systemTheme);
return; return;
@@ -67,8 +61,7 @@ export function ThemeProvider({
export const useTheme = () => { export const useTheme = () => {
const context = useContext(ThemeProviderContext); const context = useContext(ThemeProviderContext);
if (context === undefined) if (context === undefined) throw new Error("useTheme must be used within a ThemeProvider");
throw new Error("useTheme must be used within a ThemeProvider");
return context; return context;
}; };

View File

@@ -23,19 +23,10 @@ export function ThemeToggle() {
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent> <DropdownMenuContent>
<DropdownMenuRadioGroup <DropdownMenuRadioGroup value={theme} onValueChange={(value) => setTheme(value as Theme)}>
value={theme} <DropdownMenuRadioItem value="light">Light</DropdownMenuRadioItem>
onValueChange={(value) => setTheme(value as Theme)} <DropdownMenuRadioItem value="dark">Dark</DropdownMenuRadioItem>
> <DropdownMenuRadioItem value="system">System</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="light">
Light
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="dark">
Dark
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="system">
System
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup> </DropdownMenuRadioGroup>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>

View File

@@ -1,8 +1,6 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"; import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
function AspectRatio({ function AspectRatio({ ...props }: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
...props
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />; return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />;
} }

View File

@@ -3,26 +3,17 @@ import * as React from "react";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function Avatar({ function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return ( return (
<AvatarPrimitive.Root <AvatarPrimitive.Root
data-slot="avatar" data-slot="avatar"
className={cn( className={cn("relative flex size-8 shrink-0 overflow-hidden rounded-full", className)}
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className,
)}
{...props} {...props}
/> />
); );
} }
function AvatarImage({ function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return ( return (
<AvatarPrimitive.Image <AvatarPrimitive.Image
data-slot="avatar-image" data-slot="avatar-image"
@@ -32,17 +23,11 @@ function AvatarImage({
); );
} }
function AvatarFallback({ function AvatarFallback({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return ( return (
<AvatarPrimitive.Fallback <AvatarPrimitive.Fallback
data-slot="avatar-fallback" data-slot="avatar-fallback"
className={cn( className={cn("bg-muted flex size-full items-center justify-center rounded-full", className)}
"bg-muted flex size-full items-center justify-center rounded-full",
className,
)}
{...props} {...props}
/> />
); );

View File

@@ -9,14 +9,11 @@ const badgeVariants = cva(
{ {
variants: { variants: {
variant: { variant: {
default: default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
"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",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive: 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", "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: outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
}, },
}, },
defaultVariants: { defaultVariants: {
@@ -30,17 +27,10 @@ function Badge({
variant, variant,
asChild = false, asChild = false,
...props ...props
}: React.ComponentProps<"span"> & }: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"; const Comp = asChild ? Slot : "span";
return ( return <Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props} />;
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
} }
export { Badge, badgeVariants }; export { Badge, badgeVariants };

View File

@@ -9,14 +9,12 @@ const buttonVariants = cva(
{ {
variants: { variants: {
variant: { variant: {
default: default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive: 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", "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: 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", "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: secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline", link: "text-primary underline-offset-4 hover:underline",
}, },
@@ -47,13 +45,7 @@ function Button({
}) { }) {
const Comp = asChild ? Slot : "button"; const Comp = asChild ? Slot : "button";
return ( return <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} />;
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
} }
export { Button, buttonVariants }; export { Button, buttonVariants };

View File

@@ -29,64 +29,31 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
} }
function CardTitle({ className, ...props }: React.ComponentProps<"div">) { function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return ( return <div data-slot="card-title" className={cn("leading-none font-semibold", className)} {...props} />;
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
);
} }
function CardDescription({ className, ...props }: React.ComponentProps<"div">) { function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return ( return <div data-slot="card-description" className={cn("text-muted-foreground text-sm", className)} {...props} />;
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
} }
function CardAction({ className, ...props }: React.ComponentProps<"div">) { function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
<div <div
data-slot="card-action" data-slot="card-action"
className={cn( className={cn("col-start-2 row-span-2 row-start-1 self-start justify-self-end", className)}
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className,
)}
{...props} {...props}
/> />
); );
} }
function CardContent({ className, ...props }: React.ComponentProps<"div">) { function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return ( return <div data-slot="card-content" className={cn("px-6", className)} {...props} />;
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
);
} }
function CardFooter({ className, ...props }: React.ComponentProps<"div">) { function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
<div <div data-slot="card-footer" className={cn("flex items-center px-6 [.border-t]:pt-6", className)} {...props} />
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
); );
} }
export { export { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle };
Card,
CardAction,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
};

View File

@@ -4,57 +4,28 @@ import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function ContextMenu({ function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />; return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />;
} }
function ContextMenuTrigger({ function ContextMenuTrigger({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
...props return <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />;
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (
<ContextMenuPrimitive.Trigger
data-slot="context-menu-trigger"
{...props}
/>
);
} }
function ContextMenuGroup({ function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
...props return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />;
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return (
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
);
} }
function ContextMenuPortal({ function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
...props return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />;
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return (
<ContextMenuPrimitive.Portal
data-slot="context-menu-portal"
{...props}
/>
);
} }
function ContextMenuSub({ function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />; return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />;
} }
function ContextMenuRadioGroup({ function ContextMenuRadioGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
...props return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />;
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return (
<ContextMenuPrimitive.RadioGroup
data-slot="context-menu-radio-group"
{...props}
/>
);
} }
function ContextMenuSubTrigger({ function ContextMenuSubTrigger({
@@ -81,10 +52,7 @@ function ContextMenuSubTrigger({
); );
} }
function ContextMenuSubContent({ function ContextMenuSubContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return ( return (
<ContextMenuPrimitive.SubContent <ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content" data-slot="context-menu-sub-content"
@@ -97,10 +65,7 @@ function ContextMenuSubContent({
); );
} }
function ContextMenuContent({ function ContextMenuContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
return ( return (
<ContextMenuPrimitive.Portal> <ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content <ContextMenuPrimitive.Content
@@ -199,19 +164,13 @@ function ContextMenuLabel({
<ContextMenuPrimitive.Label <ContextMenuPrimitive.Label
data-slot="context-menu-label" data-slot="context-menu-label"
data-inset={inset} data-inset={inset}
className={cn( className={cn("text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", className)}
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props} {...props}
/> />
); );
} }
function ContextMenuSeparator({ function ContextMenuSeparator({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return ( return (
<ContextMenuPrimitive.Separator <ContextMenuPrimitive.Separator
data-slot="context-menu-separator" data-slot="context-menu-separator"
@@ -221,17 +180,11 @@ function ContextMenuSeparator({
); );
} }
function ContextMenuShortcut({ function ContextMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
className,
...props
}: React.ComponentProps<"span">) {
return ( return (
<span <span
data-slot="context-menu-shortcut" data-slot="context-menu-shortcut"
className={cn( className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)}
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props} {...props}
/> />
); );

View File

@@ -4,34 +4,23 @@ import * as React from "react";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function Dialog({ function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />; return <DialogPrimitive.Root data-slot="dialog" {...props} />;
} }
function DialogTrigger({ function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />; return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
} }
function DialogPortal({ function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />; return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
} }
function DialogClose({ function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />; return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
} }
function DialogOverlay({ function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return ( return (
<DialogPrimitive.Overlay <DialogPrimitive.Overlay
data-slot="dialog-overlay" data-slot="dialog-overlay"
@@ -44,11 +33,7 @@ function DialogOverlay({
); );
} }
function DialogContent({ function DialogContent({ className, children, ...props }: React.ComponentProps<typeof DialogPrimitive.Content>) {
className,
children,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
return ( return (
<DialogPortal data-slot="dialog-portal"> <DialogPortal data-slot="dialog-portal">
<DialogOverlay /> <DialogOverlay />
@@ -74,10 +59,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
<div <div
data-slot="dialog-header" data-slot="dialog-header"
className={cn( className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
"flex flex-col gap-2 text-center sm:text-left",
className,
)}
{...props} {...props}
/> />
); );
@@ -93,10 +75,7 @@ function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
); );
} }
function DialogTitle({ function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return ( return (
<DialogPrimitive.Title <DialogPrimitive.Title
data-slot="dialog-title" data-slot="dialog-title"
@@ -106,10 +85,7 @@ function DialogTitle({
); );
} }
function DialogDescription({ function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return ( return (
<DialogPrimitive.Description <DialogPrimitive.Description
data-slot="dialog-description" data-slot="dialog-description"

View File

@@ -4,32 +4,16 @@ import * as React from "react";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function DropdownMenu({ function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />; return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
} }
function DropdownMenuPortal({ function DropdownMenuPortal({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
...props return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal
data-slot="dropdown-menu-portal"
{...props}
/>
);
} }
function DropdownMenuTrigger({ function DropdownMenuTrigger({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
...props return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
);
} }
function DropdownMenuContent({ function DropdownMenuContent({
@@ -52,15 +36,8 @@ function DropdownMenuContent({
); );
} }
function DropdownMenuGroup({ function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
...props return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group
data-slot="dropdown-menu-group"
{...props}
/>
);
} }
function DropdownMenuItem({ function DropdownMenuItem({
@@ -112,15 +89,8 @@ function DropdownMenuCheckboxItem({
); );
} }
function DropdownMenuRadioGroup({ function DropdownMenuRadioGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
...props return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
);
} }
function DropdownMenuRadioItem({ function DropdownMenuRadioItem({
@@ -158,19 +128,13 @@ function DropdownMenuLabel({
<DropdownMenuPrimitive.Label <DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label" data-slot="dropdown-menu-label"
data-inset={inset} data-inset={inset}
className={cn( className={cn("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", className)}
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props} {...props}
/> />
); );
} }
function DropdownMenuSeparator({ function DropdownMenuSeparator({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return ( return (
<DropdownMenuPrimitive.Separator <DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator" data-slot="dropdown-menu-separator"
@@ -180,28 +144,18 @@ function DropdownMenuSeparator({
); );
} }
function DropdownMenuShortcut({ function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
className,
...props
}: React.ComponentProps<"span">) {
return ( return (
<span <span
data-slot="dropdown-menu-shortcut" data-slot="dropdown-menu-shortcut"
className={cn( className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)}
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props} {...props}
/> />
); );
} }
function DropdownMenuSub({ function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
...props return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return (
<DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
);
} }
function DropdownMenuSubTrigger({ function DropdownMenuSubTrigger({

View File

@@ -23,9 +23,7 @@ type FormFieldContextValue<
name: TName; name: TName;
}; };
const FormFieldContext = React.createContext<FormFieldContextValue>( const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue);
{} as FormFieldContextValue,
);
const FormField = < const FormField = <
TFieldValues extends FieldValues = FieldValues, TFieldValues extends FieldValues = FieldValues,
@@ -67,20 +65,14 @@ type FormItemContextValue = {
id: string; id: string;
}; };
const FormItemContext = React.createContext<FormItemContextValue>( const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);
{} as FormItemContextValue,
);
function FormItem({ className, ...props }: React.ComponentProps<"div">) { function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId(); const id = React.useId();
return ( return (
<FormItemContext.Provider value={{ id }}> <FormItemContext.Provider value={{ id }}>
<div <div data-slot="form-item" className={cn("grid gap-2", className)} {...props} />
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider> </FormItemContext.Provider>
); );
} }
@@ -107,18 +99,13 @@ function FormLabel({
} }
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) { function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } = const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
useFormField();
return ( return (
<Slot <Slot
data-slot="form-control" data-slot="form-control"
id={formItemId} id={formItemId}
aria-describedby={ aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error} aria-invalid={!!error}
{...props} {...props}
/> />
@@ -147,24 +134,10 @@ function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
} }
return ( return (
<p <p data-slot="form-message" id={formMessageId} className={cn("text-destructive text-sm", className)} {...props}>
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body} {body}
</p> </p>
); );
} }
export { export { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useFormField };
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
useFormField,
};

View File

@@ -87,8 +87,7 @@ export function IconUploadField({
// Visibility for the "Remove" button: show if there's a File or a URL string in field.value // Visibility for the "Remove" button: show if there's a File or a URL string in field.value
const showRemoveButton = const showRemoveButton =
(!!field.value && (!!field.value && (field.value instanceof File || typeof field.value === "string")) ||
(field.value instanceof File || typeof field.value === "string")) ||
(formDefaultValue && field.value === undefined); (formDefaultValue && field.value === undefined);
// Visibility for the "Reset to Default" button // Visibility for the "Reset to Default" button
@@ -96,8 +95,7 @@ export function IconUploadField({
// Is current value different from the formDefaultValue? // Is current value different from the formDefaultValue?
// (A File object is always different from a URL string/null/undefined default) // (A File object is always different from a URL string/null/undefined default)
const isDifferentFromDefault = const isDifferentFromDefault =
(field.value instanceof File || (field.value instanceof File || (field.value !== formDefaultValue && field.value !== undefined)) &&
(field.value !== formDefaultValue && field.value !== undefined)) &&
formDefaultValue; formDefaultValue;
const showResetButton = canReset && isDifferentFromDefault; const showResetButton = canReset && isDifferentFromDefault;
@@ -106,9 +104,7 @@ export function IconUploadField({
<div <div
ref={field.ref} ref={field.ref}
className={`relative ${previewContainerClassName} border-2 ${ className={`relative ${previewContainerClassName} border-2 ${
error error ? "border-destructive" : "border-dashed border-muted-foreground"
? "border-destructive"
: "border-dashed border-muted-foreground"
} flex items-center justify-center cursor-pointer hover:border-primary transition-colors overflow-hidden`} } flex items-center justify-center cursor-pointer hover:border-primary transition-colors overflow-hidden`}
onClick={triggerFileInput} onClick={triggerFileInput}
onKeyDown={(e) => { onKeyDown={(e) => {
@@ -124,15 +120,9 @@ export function IconUploadField({
aria-describedby={error ? `${field.name}-error` : undefined} aria-describedby={error ? `${field.name}-error` : undefined}
> >
{previewUrl ? ( {previewUrl ? (
<img <img src={previewUrl} alt="Icon preview" className="w-full h-full object-cover" />
src={previewUrl}
alt="Icon preview"
className="w-full h-full object-cover"
/>
) : ( ) : (
<ImagePlus <ImagePlus className={`w-10 h-10 ${error ? "text-destructive" : "text-muted-foreground"}`} />
className={`w-10 h-10 ${error ? "text-destructive" : "text-muted-foreground"}`}
/>
)} )}
<input <input
type="file" type="file"
@@ -152,12 +142,7 @@ export function IconUploadField({
</Button> */} </Button> */}
{showRemoveButton && ( {showRemoveButton && (
<Button <Button type="button" variant="destructive" size="sm" onClick={handleRemoveImage}>
type="button"
variant="destructive"
size="sm"
onClick={handleRemoveImage}
>
<XCircle className="mr-2 h-4 w-4" /> <XCircle className="mr-2 h-4 w-4" />
Remove Remove
</Button> </Button>

View File

@@ -5,10 +5,7 @@ import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function Label({ function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return ( return (
<LabelPrimitive.Root <LabelPrimitive.Root
data-slot="label" data-slot="label"

View File

@@ -14,11 +14,7 @@ function ScrollArea({
viewportRef?: React.Ref<HTMLDivElement>; viewportRef?: React.Ref<HTMLDivElement>;
}) { }) {
return ( return (
<ScrollAreaPrimitive.Root <ScrollAreaPrimitive.Root data-slot="scroll-area" className={cn("relative", className)} {...props}>
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport <ScrollAreaPrimitive.Viewport
ref={viewportRef} ref={viewportRef}
data-slot="scroll-area-viewport" data-slot="scroll-area-viewport"

View File

@@ -4,21 +4,15 @@ import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function Select({ function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />; return <SelectPrimitive.Root data-slot="select" {...props} />;
} }
function SelectGroup({ function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />; return <SelectPrimitive.Group data-slot="select-group" {...props} />;
} }
function SelectValue({ function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />; return <SelectPrimitive.Value data-slot="select-value" {...props} />;
} }
@@ -83,27 +77,17 @@ function SelectContent({
); );
} }
function SelectLabel({ function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return ( return (
<SelectPrimitive.Label <SelectPrimitive.Label
data-slot="select-label" data-slot="select-label"
className={cn( className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
"text-muted-foreground px-2 py-1.5 text-xs",
className,
)}
{...props} {...props}
/> />
); );
} }
function SelectItem({ function SelectItem({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Item>) {
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return ( return (
<SelectPrimitive.Item <SelectPrimitive.Item
data-slot="select-item" data-slot="select-item"
@@ -123,33 +107,21 @@ function SelectItem({
); );
} }
function SelectSeparator({ function SelectSeparator({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Separator>) {
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return ( return (
<SelectPrimitive.Separator <SelectPrimitive.Separator
data-slot="select-separator" data-slot="select-separator"
className={cn( className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
"bg-border pointer-events-none -mx-1 my-1 h-px",
className,
)}
{...props} {...props}
/> />
); );
} }
function SelectScrollUpButton({ function SelectScrollUpButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return ( return (
<SelectPrimitive.ScrollUpButton <SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button" data-slot="select-scroll-up-button"
className={cn( className={cn("flex cursor-default items-center justify-center py-1", className)}
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props} {...props}
> >
<ChevronUpIcon className="size-4" /> <ChevronUpIcon className="size-4" />
@@ -164,10 +136,7 @@ function SelectScrollDownButton({
return ( return (
<SelectPrimitive.ScrollDownButton <SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button" data-slot="select-scroll-down-button"
className={cn( className={cn("flex cursor-default items-center justify-center py-1", className)}
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props} {...props}
> >
<ChevronDownIcon className="size-4" /> <ChevronDownIcon className="size-4" />

View File

@@ -3,23 +3,11 @@ import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function Tabs({ function Tabs({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
className, return <TabsPrimitive.Root data-slot="tabs" className={cn("flex flex-col gap-2", className)} {...props} />;
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
);
} }
function TabsList({ function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return ( return (
<TabsPrimitive.List <TabsPrimitive.List
data-slot="tabs-list" data-slot="tabs-list"
@@ -32,10 +20,7 @@ function TabsList({
); );
} }
function TabsTrigger({ function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return ( return (
<TabsPrimitive.Trigger <TabsPrimitive.Trigger
data-slot="tabs-trigger" data-slot="tabs-trigger"
@@ -48,16 +33,9 @@ function TabsTrigger({
); );
} }
function TabsContent({ function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return ( return (
<TabsPrimitive.Content <TabsPrimitive.Content data-slot="tabs-content" className={cn("flex-1 outline-none", className)} {...props} />
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
); );
} }

View File

@@ -3,22 +3,11 @@ import * as React from "react";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
function TooltipProvider({ function TooltipProvider({ delayDuration = 0, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
delayDuration = 0, return <TooltipPrimitive.Provider data-slot="tooltip-provider" delayDuration={delayDuration} {...props} />;
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
} }
function Tooltip({ function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return ( return (
<TooltipProvider> <TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} /> <TooltipPrimitive.Root data-slot="tooltip" {...props} />
@@ -26,9 +15,7 @@ function Tooltip({
); );
} }
function TooltipTrigger({ function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />; return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
} }

View File

@@ -5,16 +5,11 @@ interface UserAvatarProps {
user: PartialUser | undefined; user: PartialUser | undefined;
} }
export default function UserAvatar({ export default function UserAvatar({ user, ...props }: UserAvatarProps & React.ComponentProps<typeof Avatar>) {
user,
...props
}: UserAvatarProps & React.ComponentProps<typeof Avatar>) {
return ( return (
<Avatar {...props}> <Avatar {...props}>
<AvatarImage src={user?.avatarUrl} /> <AvatarImage src={user?.avatarUrl} />
<AvatarFallback className="text-muted-foreground"> <AvatarFallback className="text-muted-foreground">{user?.username?.[0]}</AvatarFallback>
{user?.username?.[0]}
</AvatarFallback>
</Avatar> </Avatar>
); );
} }

View File

@@ -16,10 +16,7 @@ interface UserContextMenuProps {
children: React.ReactNode; children: React.ReactNode;
} }
export default function UserContextMenu({ export default function UserContextMenu({ userId, children }: UserContextMenuProps) {
userId,
children,
}: UserContextMenuProps) {
const currentUser = useUsersStore((state) => state.getCurrentUser()); const currentUser = useUsersStore((state) => state.getCurrentUser());
const navigate = useNavigate(); const navigate = useNavigate();

View File

@@ -91,11 +91,7 @@ export default function VisibleTrigger({
// Ensure it has some minimal dimension if no children are provided, // Ensure it has some minimal dimension if no children are provided,
// so the observer can detect its presence. // so the observer can detect its presence.
return ( return (
<div <div ref={elementRef} style={{ minHeight: children ? "auto" : "1px", ...style }} {...props}>
ref={elementRef}
style={{ minHeight: children ? "auto" : "1px", ...style }}
{...props}
>
{children} {/* Render any children passed to the component */} {children} {/* Render any children passed to the component */}
</div> </div>
); );

View File

@@ -7,10 +7,7 @@ export const useOrigin = () => {
setIsMounted(true); setIsMounted(true);
}, []); }, []);
const origin = const origin = typeof window !== "undefined" && window.location.origin ? window.location.origin : "";
typeof window !== "undefined" && window.location.origin
? window.location.origin
: "";
if (!isMounted) { if (!isMounted) {
return ""; return "";

View File

@@ -1,11 +1,7 @@
import axios from "../http-client"; import axios from "../http-client";
import { messageSchema, type ChannelId, type Uuid } from "../types"; import { messageSchema, type ChannelId, type Uuid } from "../types";
export async function paginatedMessages( export async function paginatedMessages(channelId: ChannelId, limit: number, before: ChannelId | undefined) {
channelId: ChannelId,
limit: number,
before: ChannelId | undefined,
) {
const response = await axios.get(`/channels/${channelId}/messages`, { const response = await axios.get(`/channels/${channelId}/messages`, {
params: { params: {
limit, limit,
@@ -13,16 +9,10 @@ export async function paginatedMessages(
}, },
}); });
return (response.data as any[]).map((value, _) => return (response.data as any[]).map((value, _) => messageSchema.parse(value));
messageSchema.parse(value),
);
} }
export async function sendMessage( export async function sendMessage(channelId: ChannelId, content: string, attachments?: Uuid[]) {
channelId: ChannelId,
content: string,
attachments?: Uuid[],
) {
const response = await axios.post(`/channels/${channelId}/messages`, { const response = await axios.post(`/channels/${channelId}/messages`, {
content, content,
attachments, attachments,

View File

@@ -1,12 +1,5 @@
import axios from "../http-client"; import axios from "../http-client";
import type { import type { ChannelId, ChannelType, Server, ServerChannel, ServerId, ServerInvite } from "../types";
ChannelId,
ChannelType,
Server,
ServerChannel,
ServerId,
ServerInvite,
} from "../types";
interface CreateServerRequest { interface CreateServerRequest {
name: string; name: string;
@@ -48,27 +41,20 @@ export async function listChannels(serverId: ServerId) {
return response.data as ServerChannel[]; return response.data as ServerChannel[];
} }
export async function createChannel( export async function createChannel(serverId: ServerId, request: CreateServerChannelRequest) {
serverId: ServerId,
request: CreateServerChannelRequest,
) {
const response = await axios.post(`/servers/${serverId}/channels`, request); const response = await axios.post(`/servers/${serverId}/channels`, request);
return response.data as ServerChannel; return response.data as ServerChannel;
} }
export async function getChannel(serverId: ServerId, channelId: ChannelId) { export async function getChannel(serverId: ServerId, channelId: ChannelId) {
const response = await axios.get( const response = await axios.get(`/servers/${serverId}/channels/${channelId}`);
`/servers/${serverId}/channels/${channelId}`,
);
return response.data as ServerChannel; return response.data as ServerChannel;
} }
export async function deleteChannel(serverId: ServerId, channelId: ChannelId) { export async function deleteChannel(serverId: ServerId, channelId: ChannelId) {
const response = await axios.delete( const response = await axios.delete(`/servers/${serverId}/channels/${channelId}`);
`/servers/${serverId}/channels/${channelId}`,
);
return response.data as ServerChannel; return response.data as ServerChannel;
} }

View File

@@ -1,11 +1,5 @@
import axios from "../http-client"; import axios from "../http-client";
import type { import type { FullUser, PartialUser, RecipientChannel, UserId, Uuid } from "../types";
FullUser,
PartialUser,
RecipientChannel,
UserId,
Uuid,
} from "../types";
export async function me() { export async function me() {
const response = await axios.get("/users/@me"); const response = await axios.get("/users/@me");

View File

@@ -5,9 +5,7 @@ export type TypeToZod<T> = {
? undefined extends T[K] ? undefined extends T[K]
? E extends object ? E extends object
? z.ZodOptional<z.ZodArray<z.ZodObject<TypeToZod<E>>>> ? z.ZodOptional<z.ZodArray<z.ZodObject<TypeToZod<E>>>>
: z.ZodOptional< : z.ZodOptional<z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>>
z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>
>
: E extends object : E extends object
? z.ZodArray<z.ZodObject<TypeToZod<E>>> ? z.ZodArray<z.ZodObject<TypeToZod<E>>>
: z.ZodArray<z.ZodType<Exclude<E, null | undefined>>> : z.ZodArray<z.ZodType<Exclude<E, null | undefined>>>

View File

@@ -32,11 +32,7 @@ export function createPrefixedLogger(prefix: string, styles?: string[]) {
result[methodName] = (...args: any[]) => { result[methodName] = (...args: any[]) => {
if (typeof args[0] === "string") { if (typeof args[0] === "string") {
originalMethod( originalMethod(`${prefix} ${args[0]}`, ...(styles || []), ...args.slice(1));
`${prefix} ${args[0]}`,
...(styles || []),
...args.slice(1),
);
} else { } else {
originalMethod(prefix, styles, ...args); originalMethod(prefix, styles, ...args);
} }

View File

@@ -102,10 +102,7 @@ export class GatewayClient {
}); });
} }
public onEvent<K extends keyof GatewayEvents>( public onEvent<K extends keyof GatewayEvents>(event: K | string, handler: GatewayEvents[K]): void {
event: K | string,
handler: GatewayEvents[K],
): void {
this.serverEventHandlers[event as K] = handler; this.serverEventHandlers[event as K] = handler;
} }
@@ -113,10 +110,7 @@ export class GatewayClient {
delete this.serverEventHandlers[event]; delete this.serverEventHandlers[event];
} }
public onControl<K extends keyof ControlEvents>( public onControl<K extends keyof ControlEvents>(event: K, handler: ControlEvents[K]): void {
event: K,
handler: ControlEvents[K],
): void {
this.eventHandlers[event] = handler; this.eventHandlers[event] = handler;
} }
@@ -226,11 +220,7 @@ export class GatewayClient {
this.userId = message.data.userId; this.userId = message.data.userId;
this.sessionKey = message.data.sessionKey; this.sessionKey = message.data.sessionKey;
this.setState(ConnectionState.CONNECTED); this.setState(ConnectionState.CONNECTED);
this.emitControl( this.emitControl("authenticated", message.data.userId, message.data.sessionKey);
"authenticated",
message.data.userId,
message.data.sessionKey,
);
break; break;
case ServerMessageType.AUTHENTICATE_DENIED: case ServerMessageType.AUTHENTICATE_DENIED:
@@ -239,10 +229,7 @@ export class GatewayClient {
break; break;
case ServerMessageType.ERROR: case ServerMessageType.ERROR:
this.emitError( this.emitError(new Error(`Server error: ${message.data.code}`), message.data.code);
new Error(`Server error: ${message.data.code}`),
message.data.code,
);
break; break;
case ServerMessageType.EVENT: case ServerMessageType.EVENT:
@@ -264,9 +251,7 @@ export class GatewayClient {
if (this.socket && this.socket.readyState === WebSocket.OPEN) { if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(message)); this.socket.send(JSON.stringify(message));
} else { } else {
this.emitError( this.emitError(new Error("Cannot send message: socket not connected"));
new Error("Cannot send message: socket not connected"),
);
} }
} }
@@ -286,20 +271,14 @@ export class GatewayClient {
this.emitControl("error", error, code); this.emitControl("error", error, code);
} }
private emitControl<K extends keyof ControlEvents>( private emitControl<K extends keyof ControlEvents>(event: K, ...args: Parameters<ControlEvents[K]>): void {
event: K,
...args: Parameters<ControlEvents[K]>
): void {
const handler = this.eventHandlers[event]; const handler = this.eventHandlers[event];
if (handler) { if (handler) {
(handler as Function)(...args); (handler as Function)(...args);
} }
} }
private emitEvent<K extends keyof GatewayEvents>( private emitEvent<K extends keyof GatewayEvents>(event: K, ...args: Parameters<GatewayEvents[K]>): void {
event: K,
...args: Parameters<GatewayEvents[K]>
): void {
const handler = this.serverEventHandlers[event]; const handler = this.serverEventHandlers[event];
if (handler) { if (handler) {
(handler as Function)(...args); (handler as Function)(...args);
@@ -322,10 +301,7 @@ export class GatewayClient {
this.socket.onclose = null; this.socket.onclose = null;
// Close the connection if it's still open // Close the connection if it's still open
if ( if (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING) {
this.socket.readyState === WebSocket.OPEN ||
this.socket.readyState === WebSocket.CONNECTING
) {
this.socket.close(); this.socket.close();
} }
@@ -337,7 +313,4 @@ export class GatewayClient {
} }
} }
const logger = createPrefixedLogger("%cGateway WS%c:", [ const logger = createPrefixedLogger("%cGateway WS%c:", ["color: red; font-weight: bold;", ""]);
"color: red; font-weight: bold;",
"",
]);

View File

@@ -1,12 +1,4 @@
import type { import type { ChannelId, Message, MessageId, PartialUser, Server, ServerId, UserId } from "~/lib/api/types";
ChannelId,
Message,
MessageId,
PartialUser,
Server,
ServerId,
UserId,
} from "~/lib/api/types";
type Channel = any; // TODO: Define Channel type type Channel = any; // TODO: Define Channel type
@@ -78,10 +70,7 @@ export interface RequestVoiceStatesMessage {
}; };
} }
export type ClientMessage = export type ClientMessage = AuthenticateMessage | VoiceStateUpdateMessage | RequestVoiceStatesMessage;
| AuthenticateMessage
| VoiceStateUpdateMessage
| RequestVoiceStatesMessage;
// Server message types // Server message types
export interface AuthenticateAcceptedMessage { export interface AuthenticateAcceptedMessage {
@@ -245,11 +234,7 @@ export interface EventMessage {
}; };
} }
export type ServerMessage = export type ServerMessage = AuthenticateAcceptedMessage | AuthenticateDeniedMessage | EventMessage | ErrorMessage;
| AuthenticateAcceptedMessage
| AuthenticateDeniedMessage
| EventMessage
| ErrorMessage;
// Connection states // Connection states
export enum ConnectionState { export enum ConnectionState {

View File

@@ -1,11 +1,5 @@
import { createPrefixedLogger } from "~/lib/utils"; import { createPrefixedLogger } from "~/lib/utils";
import { import { ClientMessageType, ConnectionState, ServerMessageType, type ClientMessage, type ServerMessage } from "./types";
ClientMessageType,
ConnectionState,
ServerMessageType,
type ClientMessage,
type ServerMessage,
} from "./types";
export class WebRTCClient { export class WebRTCClient {
private socket: WebSocket | null = null; private socket: WebSocket | null = null;
@@ -42,10 +36,7 @@ export class WebRTCClient {
this.connectionLock = true; this.connectionLock = true;
if ( if (this.state !== ConnectionState.DISCONNECTED && this.state !== ConnectionState.ERROR) {
this.state !== ConnectionState.DISCONNECTED &&
this.state !== ConnectionState.ERROR
) {
this.disconnect(); this.disconnect();
} }
@@ -97,9 +88,7 @@ export class WebRTCClient {
} }
}; };
} catch (error) { } catch (error) {
this.handleError( this.handleError(error instanceof Error ? error : new Error("Unknown error"));
error instanceof Error ? error : new Error("Unknown error"),
);
} }
}; };
@@ -190,17 +179,11 @@ export class WebRTCClient {
}); });
} }
} catch (error) { } catch (error) {
this.handleError( this.handleError(error instanceof Error ? error : new Error("Error creating WebRTC offer"));
error instanceof Error
? error
: new Error("Error creating WebRTC offer"),
);
} }
}; };
private handleServerMessage = async ( private handleServerMessage = async (event: MessageEvent): Promise<void> => {
event: MessageEvent,
): Promise<void> => {
try { try {
const message: ServerMessage = JSON.parse(event.data); const message: ServerMessage = JSON.parse(event.data);
@@ -223,17 +206,11 @@ export class WebRTCClient {
warn("Unhandled message type:", message); warn("Unhandled message type:", message);
} }
} catch (error) { } catch (error) {
this.handleError( this.handleError(error instanceof Error ? error : new Error("Failed to process message"));
error instanceof Error
? error
: new Error("Failed to process message"),
);
} }
}; };
private handleSdpAnswer = async ( private handleSdpAnswer = async (sdp: RTCSessionDescription): Promise<void> => {
sdp: RTCSessionDescription,
): Promise<void> => {
log("Received SDP answer: %o", sdp); log("Received SDP answer: %o", sdp);
if (!this.peerConnection) { if (!this.peerConnection) {
@@ -244,11 +221,7 @@ export class WebRTCClient {
try { try {
await this.peerConnection.setRemoteDescription(sdp); await this.peerConnection.setRemoteDescription(sdp);
} catch (error) { } catch (error) {
this.handleError( this.handleError(error instanceof Error ? error : new Error("Error setting remote description"));
error instanceof Error
? error
: new Error("Error setting remote description"),
);
} }
}; };
@@ -258,9 +231,7 @@ export class WebRTCClient {
if (this.socket && this.socket.readyState === WebSocket.OPEN) { if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(message)); this.socket.send(JSON.stringify(message));
} else { } else {
this.handleError( this.handleError(new Error("Cannot send message: socket not connected"));
new Error("Cannot send message: socket not connected"),
);
} }
}; };
@@ -293,7 +264,4 @@ export class WebRTCClient {
}; };
} }
const { log, warn, ...other } = createPrefixedLogger("%cWebRTC WS%c:", [ const { log, warn, ...other } = createPrefixedLogger("%cWebRTC WS%c:", ["color: blue; font-weight: bold;", ""]);
"color: blue; font-weight: bold;",
"",
]);

View File

@@ -1,11 +1,4 @@
import { import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
isRouteErrorResponse,
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from "react-router";
import { ThemeProvider } from "~/components/theme/theme-provider"; import { ThemeProvider } from "~/components/theme/theme-provider";
import type { Route } from "./+types/root"; import type { Route } from "./+types/root";
@@ -38,10 +31,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
<html lang="en"> <html lang="en">
<head> <head>
<meta charSet="utf-8" /> <meta charSet="utf-8" />
<meta <meta name="viewport" content="width=device-width, initial-scale=1" />
name="viewport"
content="width=device-width, initial-scale=1"
/>
<Meta /> <Meta />
<Links /> <Links />
</head> </head>
@@ -61,10 +51,7 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
if (isRouteErrorResponse(error)) { if (isRouteErrorResponse(error)) {
message = error.status === 404 ? "404" : "Error"; message = error.status === 404 ? "404" : "Error";
details = details = error.status === 404 ? "The requested page could not be found." : error.statusText || details;
error.status === 404
? "The requested page could not be found."
: error.statusText || details;
} else if (import.meta.env.DEV && error && error instanceof Error) { } else if (import.meta.env.DEV && error && error instanceof Error) {
details = error.message; details = error.message;
stack = error.stack; stack = error.stack;

View File

@@ -1,10 +1,4 @@
import { import { type RouteConfig, index, layout, prefix, route } from "@react-router/dev/routes";
type RouteConfig,
index,
layout,
prefix,
route,
} from "@react-router/dev/routes";
export default [ export default [
index("routes/index.tsx"), index("routes/index.tsx"),
@@ -21,10 +15,7 @@ export default [
...prefix("/@me", [ ...prefix("/@me", [
layout("routes/app/me/layout.tsx", [ layout("routes/app/me/layout.tsx", [
index("routes/app/me/index.tsx"), index("routes/app/me/index.tsx"),
route( route("/channels/:channelId", "routes/app/me/channel.tsx"),
"/channels/:channelId",
"routes/app/me/channel.tsx",
),
]), ]),
]), ]),
...prefix("/server/:serverId", [ ...prefix("/server/:serverId", [

View File

@@ -5,9 +5,7 @@ export async function clientLoader({ params }: Route.ClientLoaderArgs) {
const inviteCode = params.inviteCode; const inviteCode = params.inviteCode;
try { try {
const response = await import("~/lib/api/client/server").then((m) => const response = await import("~/lib/api/client/server").then((m) => m.default.getInvite(inviteCode));
m.default.getInvite(inviteCode),
);
return redirect(`/app/server/${response.id}`); return redirect(`/app/server/${response.id}`);
} catch (error) { } catch (error) {

View File

@@ -7,9 +7,7 @@ import { useUsersStore } from "~/stores/users-store";
async function fetchServers() { async function fetchServers() {
const { addServers } = useServerListStore.getState(); const { addServers } = useServerListStore.getState();
const newServers = await import("~/lib/api/client/server").then((m) => const newServers = await import("~/lib/api/client/server").then((m) => m.default.list());
m.default.list(),
);
addServers(newServers); addServers(newServers);
return null; return null;
@@ -18,9 +16,7 @@ async function fetchServers() {
async function fetchCurrentUser() { async function fetchCurrentUser() {
const { setCurrentUserId, addUser } = useUsersStore.getState(); const { setCurrentUserId, addUser } = useUsersStore.getState();
const user = await import("~/lib/api/client/user").then((m) => const user = await import("~/lib/api/client/user").then((m) => m.default.me());
m.default.me(),
);
setCurrentUserId(user.id); setCurrentUserId(user.id);
addUser(user); addUser(user);

View File

@@ -10,33 +10,20 @@ export default function Channel({ params }: Route.ComponentProps) {
const channelId = params.channelId; const channelId = params.channelId;
const currentUserId = useUsersStore((state) => state.currentUserId); const currentUserId = useUsersStore((state) => state.currentUserId);
const nativeChannel = usePrivateChannelsStore( const nativeChannel = usePrivateChannelsStore(useShallow((state) => state.channels[channelId]));
useShallow((state) => state.channels[channelId]),
);
if (!nativeChannel) return null; if (!nativeChannel) return null;
const recipients = nativeChannel.recipients.filter( const recipients = nativeChannel.recipients.filter((recipient) => recipient.id !== currentUserId);
(recipient) => recipient.id !== currentUserId,
);
const renderSystemBadge = const renderSystemBadge = recipients.some((recipient) => recipient.system) && recipients.length === 1;
recipients.some((recipient) => recipient.system) &&
recipients.length === 1;
const channel = { const channel = {
...nativeChannel, ...nativeChannel,
name: ( name: (
<> <>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div> <div>{recipients.map((recipient) => recipient.displayName || recipient.username).join(", ")}</div>
{recipients
.map(
(recipient) =>
recipient.displayName || recipient.username,
)
.join(", ")}
</div>
{renderSystemBadge && ( {renderSystemBadge && (
<Badge variant="default"> <Badge variant="default">
{" "} {" "}

View File

@@ -9,23 +9,16 @@ import { usePrivateChannelsStore } from "~/stores/private-channels-store";
async function fetchPrivateChannels() { async function fetchPrivateChannels() {
const { addChannels } = usePrivateChannelsStore.getState(); const { addChannels } = usePrivateChannelsStore.getState();
const channels = await import("~/lib/api/client/user").then((m) => const channels = await import("~/lib/api/client/user").then((m) => m.default.channels());
m.default.channels(),
);
addChannels(channels); addChannels(channels);
return null; return null;
} }
function ListComponent() { function ListComponent() {
const channels = Object.values( const channels = Object.values(usePrivateChannelsStore(useShallow((state) => state.channels)));
usePrivateChannelsStore(useShallow((state) => state.channels)),
);
const sortedChannels = React.useMemo( const sortedChannels = React.useMemo(
() => () => channels.sort((a, b) => ((a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1)),
channels.sort((a, b) =>
(a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1,
),
[channels], [channels],
); );
@@ -37,9 +30,7 @@ function ListComponent() {
return ( return (
<div className="h-full flex flex-col"> <div className="h-full flex flex-col">
<div className="w-full min-h-12"> <div className="w-full min-h-12">
<div className="border-b-2 h-full flex items-center justify-center"> <div className="border-b-2 h-full flex items-center justify-center">Private Messages</div>
Private Messages
</div>
</div> </div>
<ScrollArea className="overflow-auto" scrollbarSize="narrow"> <ScrollArea className="overflow-auto" scrollbarSize="narrow">

View File

@@ -4,13 +4,9 @@ import ChannelArea from "~/components/channel-area";
import { useServerChannelsStore } from "~/stores/server-channels-store"; import { useServerChannelsStore } from "~/stores/server-channels-store";
import type { Route } from "./+types/channel"; import type { Route } from "./+types/channel";
export default function Channel({ export default function Channel({ params: { serverId, channelId } }: Route.ComponentProps) {
params: { serverId, channelId },
}: Route.ComponentProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const channel = useServerChannelsStore( const channel = useServerChannelsStore(useShallow((state) => state.channels[serverId][channelId]));
useShallow((state) => state.channels[serverId][channelId]),
);
if (!channel) { if (!channel) {
setTimeout(() => navigate(`/app/server/${serverId}`), 0); setTimeout(() => navigate(`/app/server/${serverId}`), 0);

View File

@@ -42,16 +42,10 @@ function ListComponent() {
const currentUserId = useUsersStore((state) => state.currentUserId); const currentUserId = useUsersStore((state) => state.currentUserId);
const onOpen = useModalStore((state) => state.onOpen); const onOpen = useModalStore((state) => state.onOpen);
const server = useServerListStore( const server = useServerListStore(useShallow((state) => state.servers[serverId] || null));
useShallow((state) => state.servers[serverId] || null),
);
const channels = Array.from( const channels = Array.from(
Object.values( Object.values(useServerChannelsStore(useShallow((state) => state.channels[serverId] || {}))),
useServerChannelsStore(
useShallow((state) => state.channels[serverId] || {}),
),
),
); );
if (!server) { if (!server) {
@@ -100,9 +94,7 @@ function ListComponent() {
</DropdownMenuItem> </DropdownMenuItem>
)} )}
{currentUserId !== server.ownerId && ( {currentUserId !== server.ownerId && (
<DropdownMenuItem variant="destructive"> <DropdownMenuItem variant="destructive">Leave</DropdownMenuItem>
Leave
</DropdownMenuItem>
)} )}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
@@ -111,12 +103,7 @@ function ListComponent() {
<ScrollArea className="overflow-auto" scrollbarSize="narrow"> <ScrollArea className="overflow-auto" scrollbarSize="narrow">
<div className="p-2 flex flex-col gap-1 h-full"> <div className="p-2 flex flex-col gap-1 h-full">
{channels {channels
.sort((a, b) => .sort((a, b) => ((a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1))
(a.lastMessageId ?? a.id) <
(b.lastMessageId ?? b.id)
? 1
: -1,
)
.map((channel, _) => ( .map((channel, _) => (
<React.Fragment key={channel.id}> <React.Fragment key={channel.id}>
<ServerChannelListItem channel={channel} /> <ServerChannelListItem channel={channel} />
@@ -133,9 +120,7 @@ export const handle = {
}; };
export default function Layout({ params: { serverId } }: Route.ComponentProps) { export default function Layout({ params: { serverId } }: Route.ComponentProps) {
const server = useServerListStore( const server = useServerListStore(useShallow((state) => state.servers[serverId!] || null));
useShallow((state) => state.servers[serverId!] || null),
);
const navigate = useNavigate(); const navigate = useNavigate();
if (!server) { if (!server) {

View File

@@ -3,14 +3,7 @@ import { LogOutIcon, UserIcon } from "lucide-react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
import { Button } from "~/components/ui/button"; import { Button } from "~/components/ui/button";
import { import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "~/components/ui/form";
import { IconUploadField } from "~/components/ui/icon-upload-field"; import { IconUploadField } from "~/components/ui/icon-upload-field";
import { Input } from "~/components/ui/input"; import { Input } from "~/components/ui/input";
import file from "~/lib/api/client/file"; import file from "~/lib/api/client/file";
@@ -39,8 +32,7 @@ export default function Settings() {
const onSubmit = async (values: z.infer<typeof schema>) => { const onSubmit = async (values: z.infer<typeof schema>) => {
if (!values) return; if (!values) return;
let avatarId: string | null | undefined = let avatarId: string | null | undefined = values.avatar === null ? null : undefined;
values.avatar === null ? null : undefined;
if (values.avatar) { if (values.avatar) {
avatarId = (await file.uploadFile(values.avatar))[0]; avatarId = (await file.uploadFile(values.avatar))[0];
} }
@@ -80,11 +72,7 @@ export default function Settings() {
</Button> </Button>
<div className="mt-auto"> <div className="mt-auto">
<Button <Button variant="destructive" className="w-full" onClick={onLogout}>
variant="destructive"
className="w-full"
onClick={onLogout}
>
<LogOutIcon className="mr-2 h-4 w-4" /> <LogOutIcon className="mr-2 h-4 w-4" />
Logout Logout
</Button> </Button>
@@ -95,31 +83,18 @@ export default function Settings() {
<div className="flex-1 p-8"> <div className="flex-1 p-8">
<div className="max-w-2xl mx-auto"> <div className="max-w-2xl mx-auto">
<Form {...form}> <Form {...form}>
<form <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField <FormField
control={form.control} control={form.control}
name="avatar" name="avatar"
render={({ field, fieldState }) => ( render={({ field, fieldState }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.avatar.isOptional()}>Avatar</FormLabel>
required={
!schema.shape.avatar.isOptional()
}
>
Avatar
</FormLabel>
<FormControl> <FormControl>
<div className="flex flex-col items-center justify-center"> <div className="flex flex-col items-center justify-center">
<IconUploadField <IconUploadField
defaultPreview={ defaultPreview={user?.avatarUrl}
user?.avatarUrl formDefaultValue={user?.avatarUrl}
}
formDefaultValue={
user?.avatarUrl
}
field={field} field={field}
error={fieldState.error} error={fieldState.error}
/> />
@@ -134,11 +109,7 @@ export default function Settings() {
name="displayName" name="displayName"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel <FormLabel required={!schema.shape.displayName.isOptional()}>
required={
!schema.shape.displayName.isOptional()
}
>
Display Name Display Name
</FormLabel> </FormLabel>
<FormControl> <FormControl>
@@ -148,13 +119,8 @@ export default function Settings() {
</FormItem> </FormItem>
)} )}
/> />
<Button <Button type="submit" disabled={form.formState.isSubmitting}>
type="submit" {form.formState.isSubmitting ? "Saving..." : "Save"}
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting
? "Saving..."
: "Save"}
</Button> </Button>
</form> </form>
</Form> </Form>

View File

@@ -7,22 +7,8 @@ import { useShallow } from "zustand/react/shallow";
import { PasswordInput } from "~/components/custom-ui/password-input"; import { PasswordInput } from "~/components/custom-ui/password-input";
import { ThemeToggle } from "~/components/theme/theme-toggle"; import { ThemeToggle } from "~/components/theme/theme-toggle";
import { Button, buttonVariants } from "~/components/ui/button"; import { Button, buttonVariants } from "~/components/ui/button";
import { import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
Card, import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
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 { Input } from "~/components/ui/input";
import auth from "~/lib/api/client/auth"; import auth from "~/lib/api/client/auth";
import { useTokenStore } from "~/stores/token-store"; import { useTokenStore } from "~/stores/token-store";
@@ -79,10 +65,7 @@ export default function Login() {
return ( return (
<Card style={{ viewTransitionName: "auth-card-view" }}> <Card style={{ viewTransitionName: "auth-card-view" }}>
<CardHeader <CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative">
style={{ viewTransitionName: "auth-card-header-view" }}
className="relative"
>
<CardTitle>Welcome back!</CardTitle> <CardTitle>Welcome back!</CardTitle>
<CardDescription>Please sign in to continue.</CardDescription> <CardDescription>Please sign in to continue.</CardDescription>
<div <div
@@ -94,9 +77,7 @@ export default function Login() {
<ThemeToggle /> <ThemeToggle />
</div> </div>
</CardHeader> </CardHeader>
<CardContent <CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
style={{ viewTransitionName: "auth-card-content-view" }}
>
<Form {...form}> <Form {...form}>
<form <form
onSubmit={form.handleSubmit(onSubmit)} onSubmit={form.handleSubmit(onSubmit)}
@@ -126,8 +107,7 @@ export default function Login() {
render={({ field }) => ( render={({ field }) => (
<FormItem <FormItem
style={{ style={{
viewTransitionName: viewTransitionName: "password-field-view",
"password-field-view",
}} }}
> >
<FormLabel required>Password</FormLabel> <FormLabel required>Password</FormLabel>
@@ -138,11 +118,7 @@ export default function Login() {
</FormItem> </FormItem>
)} )}
/> />
<Button <Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>
className="w-full"
type="submit"
style={{ viewTransitionName: "submit-button-view" }}
>
Log In Log In
</Button> </Button>
</form> </form>
@@ -150,9 +126,7 @@ export default function Login() {
</CardContent> </CardContent>
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}> <CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
<div className="flex items-center"> <div className="flex items-center">
<span className="text-muted-foreground text-sm"> <span className="text-muted-foreground text-sm">Don't have an account?</span>
Don't have an account?
</span>
<Link <Link
className={buttonVariants({ className={buttonVariants({
variant: "link", variant: "link",

View File

@@ -5,22 +5,8 @@ import { z } from "zod";
import { PasswordInput } from "~/components/custom-ui/password-input"; import { PasswordInput } from "~/components/custom-ui/password-input";
import { ThemeToggle } from "~/components/theme/theme-toggle"; import { ThemeToggle } from "~/components/theme/theme-toggle";
import { Button, buttonVariants } from "~/components/ui/button"; import { Button, buttonVariants } from "~/components/ui/button";
import { import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
Card, import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
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 { Input } from "~/components/ui/input";
import auth from "~/lib/api/client/auth"; import auth from "~/lib/api/client/auth";
@@ -49,14 +35,9 @@ export default function Register() {
return ( return (
<Card style={{ viewTransitionName: "auth-card-view" }}> <Card style={{ viewTransitionName: "auth-card-view" }}>
<CardHeader <CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative">
style={{ viewTransitionName: "auth-card-header-view" }}
className="relative"
>
<CardTitle>Create an account</CardTitle> <CardTitle>Create an account</CardTitle>
<CardDescription> <CardDescription>Please fill out the form below to create an account.</CardDescription>
Please fill out the form below to create an account.
</CardDescription>
<div <div
className="absolute top-0 right-0 px-6" className="absolute top-0 right-0 px-6"
style={{ style={{
@@ -66,9 +47,7 @@ export default function Register() {
<ThemeToggle /> <ThemeToggle />
</div> </div>
</CardHeader> </CardHeader>
<CardContent <CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
style={{ viewTransitionName: "auth-card-content-view" }}
>
<Form {...form}> <Form {...form}>
<form <form
onSubmit={form.handleSubmit(onSubmit)} onSubmit={form.handleSubmit(onSubmit)}
@@ -86,11 +65,7 @@ export default function Register() {
> >
<FormLabel required>Email</FormLabel> <FormLabel required>Email</FormLabel>
<FormControl> <FormControl>
<Input <Input type="email" placeholder="email@example.com" {...field} />
type="email"
placeholder="email@example.com"
{...field}
/>
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -128,8 +103,7 @@ export default function Register() {
render={({ field }) => ( render={({ field }) => (
<FormItem <FormItem
style={{ style={{
viewTransitionName: viewTransitionName: "password-field-view",
"password-field-view",
}} }}
> >
<FormLabel required>Password</FormLabel> <FormLabel required>Password</FormLabel>
@@ -140,11 +114,7 @@ export default function Register() {
</FormItem> </FormItem>
)} )}
/> />
<Button <Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>
className="w-full"
type="submit"
style={{ viewTransitionName: "submit-button-view" }}
>
Register Register
</Button> </Button>
</form> </form>
@@ -152,9 +122,7 @@ export default function Register() {
</CardContent> </CardContent>
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}> <CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
<div className="flex items-center"> <div className="flex items-center">
<span className="text-muted-foreground text-sm"> <span className="text-muted-foreground text-sm">Already have an account?</span>
Already have an account?
</span>
<Link <Link
className={buttonVariants({ className={buttonVariants({
variant: "link", variant: "link",

View File

@@ -13,11 +13,7 @@ interface ChannelVoiceState {
interface ChannelsVoiceState { interface ChannelsVoiceState {
channels: Record<ChannelId, ChannelVoiceState>; channels: Record<ChannelId, ChannelVoiceState>;
addUser: ( addUser: (channelId: ChannelId, userId: UserId, userVoiceState: UserVoiceState) => void;
channelId: ChannelId,
userId: UserId,
userVoiceState: UserVoiceState,
) => void;
removeUser: (channelId: ChannelId, userId: UserId) => void; removeUser: (channelId: ChannelId, userId: UserId) => void;
removeChannel: (channelId: ChannelId) => void; removeChannel: (channelId: ChannelId) => void;
} }

View File

@@ -1,19 +1,8 @@
import type { QueryClient } from "@tanstack/react-query"; import type { QueryClient } from "@tanstack/react-query";
import { create } from "zustand"; import { create } from "zustand";
import { import { messageSchema, type ChannelId, type Message, type MessageId, type ServerId } from "~/lib/api/types";
messageSchema,
type ChannelId,
type Message,
type MessageId,
type ServerId,
} from "~/lib/api/types";
import { GatewayClient } from "~/lib/websocket/gateway/client"; import { GatewayClient } from "~/lib/websocket/gateway/client";
import { import { ConnectionState, EventType, type EventData, type VoiceServerUpdateEvent } from "~/lib/websocket/gateway/types";
ConnectionState,
EventType,
type EventData,
type VoiceServerUpdateEvent,
} from "~/lib/websocket/gateway/types";
import { useChannelsVoiceStateStore } from "./channels-voice-state"; import { useChannelsVoiceStateStore } from "./channels-voice-state";
import { usePrivateChannelsStore } from "./private-channels-store"; import { usePrivateChannelsStore } from "./private-channels-store";
import { useServerChannelsStore } from "./server-channels-store"; import { useServerChannelsStore } from "./server-channels-store";
@@ -23,10 +12,7 @@ import { useUsersStore } from "./users-store";
const GATEWAY_URL = "ws://localhost:12345/gateway/ws"; const GATEWAY_URL = "ws://localhost:12345/gateway/ws";
const HANDLERS = { const HANDLERS = {
[EventType.ADD_SERVER]: ( [EventType.ADD_SERVER]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_SERVER }>["data"]) => {
self: GatewayState,
data: Extract<EventData, { type: EventType.ADD_SERVER }>["data"],
) => {
useServerListStore.getState().addServer(data.server); useServerListStore.getState().addServer(data.server);
}, },
@@ -59,31 +45,20 @@ const HANDLERS = {
[EventType.ADD_SERVER_CHANNEL]: ( [EventType.ADD_SERVER_CHANNEL]: (
self: GatewayState, self: GatewayState,
data: Extract< data: Extract<EventData, { type: EventType.ADD_SERVER_CHANNEL }>["data"],
EventData,
{ type: EventType.ADD_SERVER_CHANNEL }
>["data"],
) => { ) => {
useServerChannelsStore.getState().addChannel(data.channel); useServerChannelsStore.getState().addChannel(data.channel);
}, },
[EventType.REMOVE_SERVER_CHANNEL]: ( [EventType.REMOVE_SERVER_CHANNEL]: (
self: GatewayState, self: GatewayState,
data: Extract< data: Extract<EventData, { type: EventType.REMOVE_SERVER_CHANNEL }>["data"],
EventData,
{ type: EventType.REMOVE_SERVER_CHANNEL }
>["data"],
) => { ) => {
useServerChannelsStore useServerChannelsStore.getState().removeChannel(data.serverId, data.channelId);
.getState()
.removeChannel(data.serverId, data.channelId);
useChannelsVoiceStateStore.getState().removeChannel(data.serverId); useChannelsVoiceStateStore.getState().removeChannel(data.serverId);
}, },
[EventType.ADD_USER]: ( [EventType.ADD_USER]: (self: GatewayState, data: Extract<EventData, { type: EventType.ADD_USER }>["data"]) => {
self: GatewayState,
data: Extract<EventData, { type: EventType.ADD_USER }>["data"],
) => {
useUsersStore.getState().addUser(data.user); useUsersStore.getState().addUser(data.user);
}, },
@@ -103,10 +78,7 @@ const HANDLERS = {
[EventType.REMOVE_SERVER_MEMBER]: ( [EventType.REMOVE_SERVER_MEMBER]: (
self: GatewayState, self: GatewayState,
data: Extract< data: Extract<EventData, { type: EventType.REMOVE_SERVER_MEMBER }>["data"],
EventData,
{ type: EventType.REMOVE_SERVER_MEMBER }
>["data"],
) => { ) => {
useUsersStore.getState().removeUser(data.userId); useUsersStore.getState().removeUser(data.userId);
}, },
@@ -123,15 +95,9 @@ const HANDLERS = {
(oldData: { pages: Message[][]; pageParams: MessageId[] }) => { (oldData: { pages: Message[][]; pageParams: MessageId[] }) => {
return { return {
pages: oldData?.pages pages: oldData?.pages
? [ ? [[message, ...oldData.pages[0]], ...oldData.pages.slice(1)]
[message, ...oldData.pages[0]],
...oldData.pages.slice(1),
]
: [[message]], : [[message]],
pageParams: oldData?.pageParams ?? [ pageParams: oldData?.pageParams ?? [undefined, message.id],
undefined,
message.id,
],
}; };
}, },
); );
@@ -143,43 +109,28 @@ const HANDLERS = {
data: Extract<EventData, { type: EventType.REMOVE_MESSAGE }>["data"], data: Extract<EventData, { type: EventType.REMOVE_MESSAGE }>["data"],
) => { ) => {
if (self.queryClient) { if (self.queryClient) {
self.queryClient.setQueryData( self.queryClient.setQueryData(["messages", data.channelId], (oldData: any) => {
["messages", data.channelId], if (!oldData) return [];
(oldData: any) => { return oldData.filter((message: any) => message.id !== data.messageId);
if (!oldData) return []; });
return oldData.filter(
(message: any) => message.id !== data.messageId,
);
},
);
} }
}, },
[EventType.VOICE_CHANNEL_CONNECTED]: ( [EventType.VOICE_CHANNEL_CONNECTED]: (
self: GatewayState, self: GatewayState,
data: Extract< data: Extract<EventData, { type: EventType.VOICE_CHANNEL_CONNECTED }>["data"],
EventData,
{ type: EventType.VOICE_CHANNEL_CONNECTED }
>["data"],
) => { ) => {
useChannelsVoiceStateStore useChannelsVoiceStateStore.getState().addUser(data.channelId, data.userId, {
.getState() deaf: false,
.addUser(data.channelId, data.userId, { muted: false,
deaf: false, });
muted: false,
});
}, },
[EventType.VOICE_CHANNEL_DISCONNECTED]: ( [EventType.VOICE_CHANNEL_DISCONNECTED]: (
self: GatewayState, self: GatewayState,
data: Extract< data: Extract<EventData, { type: EventType.VOICE_CHANNEL_DISCONNECTED }>["data"],
EventData,
{ type: EventType.VOICE_CHANNEL_DISCONNECTED }
>["data"],
) => { ) => {
useChannelsVoiceStateStore useChannelsVoiceStateStore.getState().removeUser(data.channelId, data.userId);
.getState()
.removeUser(data.channelId, data.userId);
}, },
}; };
@@ -195,19 +146,13 @@ interface GatewayState {
updateVoiceState: (serverId: ServerId, channelId: ChannelId) => void; updateVoiceState: (serverId: ServerId, channelId: ChannelId) => void;
requestVoiceStates: (serverId: ServerId) => void; requestVoiceStates: (serverId: ServerId) => void;
onVoiceServerUpdate: ( onVoiceServerUpdate: (handler: (event: VoiceServerUpdateEvent["data"]) => void | Promise<void>) => () => void;
handler: (
event: VoiceServerUpdateEvent["data"],
) => void | Promise<void>,
) => () => void;
} }
export const useGatewayStore = create<GatewayState>()((set, get) => { export const useGatewayStore = create<GatewayState>()((set, get) => {
const client = new GatewayClient(GATEWAY_URL); const client = new GatewayClient(GATEWAY_URL);
const voiceHandlers = new Set< const voiceHandlers = new Set<(event: VoiceServerUpdateEvent["data"]) => void>();
(event: VoiceServerUpdateEvent["data"]) => void
>();
client.onEvent(EventType.VOICE_SERVER_UPDATE, (event) => { client.onEvent(EventType.VOICE_SERVER_UPDATE, (event) => {
voiceHandlers.forEach((handler) => handler(event)); voiceHandlers.forEach((handler) => handler(event));

View File

@@ -30,10 +30,7 @@ export type CreateServerChannelModalData = {
}; };
}; };
export type ModalData = export type ModalData = CreateServerChannelModalData | CreateServerInviteModalData | DeleteServerConfirmModalData;
| CreateServerChannelModalData
| CreateServerInviteModalData
| DeleteServerConfirmModalData;
interface ModalState { interface ModalState {
type: ModalType | null; type: ModalType | null;

View File

@@ -51,12 +51,10 @@ export const useUsersStore = create<UsersStore>()(
}, },
addUser: (user) => addUser: (user) =>
set((state) => { set((state) => {
if (user.id !== get().currentUserId) if (user.id !== get().currentUserId) state.users[user.id] = user;
state.users[user.id] = user;
else { else {
const currentUser = get().users[user.id]; const currentUser = get().users[user.id];
if (currentUser) if (currentUser) state.users[user.id] = { ...currentUser, ...user };
state.users[user.id] = { ...currentUser, ...user };
else state.users[user.id] = user; else state.users[user.id] = user;
} }
}), }),
@@ -70,9 +68,6 @@ export const useUsersStore = create<UsersStore>()(
state.currentUserId = userId; state.currentUserId = userId;
}), }),
getCurrentUser: () => getCurrentUser: () => (!!get().currentUserId ? (get().users[get().currentUserId!] as FullUser) : undefined),
!!get().currentUserId
? (get().users[get().currentUserId!] as FullUser)
: undefined,
})), })),
); );

View File

@@ -1,10 +1,5 @@
{ {
"include": [ "include": ["**/*", "**/.server/**/*", "**/.client/**/*", ".react-router/types/**/*"],
"**/*",
"**/.server/**/*",
"**/.client/**/*",
".react-router/types/**/*"
],
"compilerOptions": { "compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"], "lib": ["DOM", "DOM.Iterable", "ES2022"],
"types": ["node", "vite/client"], "types": ["node", "vite/client"],