3895 lines
132 KiB
Plaintext
3895 lines
132 KiB
Plaintext
|
|
// file: ./app/routes/index.tsx
|
|
import { redirect } from "react-router";
|
|
import type { Route } from "./+types/index";
|
|
|
|
export function meta({ }: Route.MetaArgs) {
|
|
return [
|
|
{ title: "New React Router App" },
|
|
];
|
|
}
|
|
|
|
export function clientLoader() {
|
|
return redirect("/login");
|
|
}
|
|
|
|
export default function Index() {
|
|
return <></>;
|
|
}
|
|
|
|
// file: ./app/routes/auth/layout.tsx
|
|
import { Outlet } from "react-router";
|
|
|
|
export default function Layout() {
|
|
return (
|
|
<div className="min-h-screen min-w-screen grid place-items-center">
|
|
<div className="min-w-md">
|
|
<Outlet />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// file: ./app/routes/auth/login.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { AxiosError } from "axios";
|
|
import { useForm } from "react-hook-form";
|
|
import { Link, redirect, useNavigate } from "react-router";
|
|
import { z } from "zod";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { PasswordInput } from "~/components/custom-ui/password-input";
|
|
import { ThemeToggle } from "~/components/theme/theme-toggle";
|
|
import { Button, buttonVariants } from "~/components/ui/button";
|
|
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
|
|
import {
|
|
Form,
|
|
FormControl,
|
|
FormField,
|
|
FormItem,
|
|
FormLabel,
|
|
FormMessage,
|
|
} from "~/components/ui/form";
|
|
import { Input } from "~/components/ui/input";
|
|
import auth from "~/lib/api/client/auth";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
const schema = z.object({
|
|
username: z.string(),
|
|
password: z.string().min(8),
|
|
});
|
|
|
|
export async function clientLoader() {
|
|
const { token, setToken } = useTokenStore.getState()
|
|
|
|
if (token) {
|
|
try {
|
|
await import("~/lib/api/client/user").then(m => m.default.me())
|
|
|
|
return redirect("/app/@me")
|
|
} catch (error) {
|
|
const axiosError = error as AxiosError
|
|
|
|
if (axiosError.status === 401) {
|
|
setToken(undefined)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export default function Login() {
|
|
let navigate = useNavigate()
|
|
let setToken = useTokenStore(state => state.setToken)
|
|
const { setCurrentUserId, addUser } = useUsersStore(useShallow(state => {
|
|
return {
|
|
setCurrentUserId: state.setCurrentUserId,
|
|
addUser: state.addUser
|
|
}
|
|
}))
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
})
|
|
|
|
async function onSubmit(values: z.infer<typeof schema>) {
|
|
const response = await auth.login(values)
|
|
|
|
setToken(response.token)
|
|
setCurrentUserId(response.user.id)
|
|
addUser(response.user)
|
|
|
|
navigate("/app")
|
|
}
|
|
|
|
return (
|
|
<Card style={{ viewTransitionName: "auth-card-view" }}>
|
|
<CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative" >
|
|
<CardTitle>Welcome back!</CardTitle>
|
|
<CardDescription>Please sign in to continue.</CardDescription>
|
|
<div className="absolute top-0 right-0 px-6" style={{ viewTransitionName: "auth-card-header-mode-toggle-view" }}>
|
|
<ThemeToggle />
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" style={{ viewTransitionName: "auth-form-view" }}>
|
|
<FormField
|
|
control={form.control}
|
|
name="username"
|
|
render={({ field }) => (
|
|
<FormItem style={{ viewTransitionName: "email-field-view" }}>
|
|
<FormLabel required>Username</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="password"
|
|
render={({ field }) => (
|
|
<FormItem style={{ viewTransitionName: "password-field-view" }}>
|
|
<FormLabel required>Password</FormLabel>
|
|
<FormControl>
|
|
<PasswordInput {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>Log In</Button>
|
|
</form>
|
|
</Form>
|
|
</CardContent>
|
|
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
|
|
<div className="flex items-center">
|
|
<span className="text-muted-foreground text-sm">Don't have an account?</span>
|
|
<Link className={buttonVariants({ variant: "link", size: "sm" })} to="/register" viewTransition>Register</Link>
|
|
</div>
|
|
</CardFooter>
|
|
</Card>
|
|
);
|
|
}
|
|
// file: ./app/routes/auth/register.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { Link, useNavigate } from "react-router";
|
|
import { z } from "zod";
|
|
import { PasswordInput } from "~/components/custom-ui/password-input";
|
|
import { ThemeToggle } from "~/components/theme/theme-toggle";
|
|
import { Button, buttonVariants } from "~/components/ui/button";
|
|
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
|
|
import {
|
|
Form,
|
|
FormControl,
|
|
FormField,
|
|
FormItem,
|
|
FormLabel,
|
|
FormMessage,
|
|
} from "~/components/ui/form";
|
|
import { Input } from "~/components/ui/input";
|
|
import auth from "~/lib/api/client/auth";
|
|
|
|
const schema = z.object({
|
|
email: z.string().email(),
|
|
displayName: z.string().min(1).optional(),
|
|
username: z.string().min(3).regex(/^[a-zA-Z0-9_.]+$/),
|
|
password: z.string().min(8),
|
|
});
|
|
|
|
export default function Register() {
|
|
let navigate = useNavigate()
|
|
|
|
const form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
})
|
|
|
|
async function onSubmit(values: z.infer<typeof schema>) {
|
|
await auth.register(values)
|
|
|
|
navigate("/login")
|
|
}
|
|
|
|
return (
|
|
<Card style={{ viewTransitionName: "auth-card-view" }}>
|
|
<CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative">
|
|
<CardTitle>Create an account</CardTitle>
|
|
<CardDescription>Please fill out the form below to create an account.</CardDescription>
|
|
<div className="absolute top-0 right-0 px-6" style={{ viewTransitionName: "auth-card-header-mode-toggle-view" }}>
|
|
<ThemeToggle />
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" style={{ viewTransitionName: "auth-form-view" }}>
|
|
<FormField
|
|
control={form.control}
|
|
name="email"
|
|
render={({ field }) => (
|
|
<FormItem style={{ viewTransitionName: "email-field-view" }}>
|
|
<FormLabel required>Email</FormLabel>
|
|
<FormControl>
|
|
<Input type="email" placeholder="email@example.com" {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="username"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required>Username</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="displayName"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel>Display Name</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="password"
|
|
render={({ field }) => (
|
|
<FormItem style={{ viewTransitionName: "password-field-view" }}>
|
|
<FormLabel required>Password</FormLabel>
|
|
<FormControl>
|
|
<PasswordInput {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>Register</Button>
|
|
</form>
|
|
</Form>
|
|
</CardContent>
|
|
<CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
|
|
<div className="flex items-center">
|
|
<span className="text-muted-foreground text-sm">Already have an account?</span>
|
|
<Link className={buttonVariants({ variant: "link", size: "sm" })} to="/login" viewTransition>Log In</Link>
|
|
</div>
|
|
</CardFooter>
|
|
</Card>
|
|
);
|
|
}
|
|
// file: ./app/routes/app/layout.tsx
|
|
import { Outlet, redirect } from "react-router";
|
|
import AppLayout from "~/components/app-layout";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
|
|
export async function clientLoader() {
|
|
const { servers, addServers } = useServerListStore.getState()
|
|
|
|
try {
|
|
if (!servers || Object.values(servers).length === 0) {
|
|
const newServers = await import("~/lib/api/client/server").then(m => m.default.list())
|
|
addServers(newServers)
|
|
}
|
|
|
|
} catch (error) {
|
|
return redirect("/login")
|
|
}
|
|
}
|
|
|
|
export default function Layout() {
|
|
|
|
return (
|
|
<AppLayout >
|
|
<Outlet />
|
|
</AppLayout>
|
|
);
|
|
}
|
|
// file: ./app/routes/app/index.tsx
|
|
import { redirect } from "react-router";
|
|
|
|
export function clientLoader() {
|
|
return redirect("/app/@me")
|
|
}
|
|
|
|
export default function Index() {
|
|
return null;
|
|
}
|
|
|
|
// file: ./app/routes/app/me/index.tsx
|
|
|
|
export default function Index() {
|
|
return (
|
|
<>
|
|
{/* <div className="h-full">
|
|
<div className="size-full relative">
|
|
<div className="absolute bottom-0 w-full max-h-1/2">
|
|
<div className="p-2">
|
|
<TextBox value={""}
|
|
onChange={(m) => { }}
|
|
placeholder="Type your message here..."
|
|
// Example of custom styling:
|
|
// wrapperClassName="bg-gray-700 border-gray-600 rounded-lg"
|
|
// inputClassName="text-lg"
|
|
aria-label="Message input" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div> */}
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: ./app/routes/app/me/channel.tsx
|
|
import type { Route } from ".react-router/types/app/routes/app/me/+types/channel";
|
|
import { Check } from "lucide-react";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import ChannelArea from "~/components/channel-area";
|
|
import { Badge } from "~/components/ui/badge";
|
|
import { usePrivateChannelsStore } from "~/stores/private-channels-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
export default function Channel({
|
|
params
|
|
}: Route.ComponentProps) {
|
|
const channelId = params.channelId
|
|
const currentUserId = useUsersStore(state => state.currentUserId)
|
|
|
|
const nativeChannel = usePrivateChannelsStore(useShallow(state => state.channels[channelId]))
|
|
const recipients = nativeChannel.recipients.filter(recipient => recipient.id !== currentUserId)
|
|
|
|
const renderSystemBadge = recipients.some(recipient => recipient.system) && recipients.length === 1
|
|
|
|
const channel = {
|
|
...nativeChannel,
|
|
name: <>
|
|
<div className="flex items-center gap-2">
|
|
<div>
|
|
{recipients.map(recipient => recipient.displayName || recipient.username).join(", ")}
|
|
</div>
|
|
{renderSystemBadge && <Badge variant="default"> <Check />System</Badge>}
|
|
</div>
|
|
</>
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<ChannelArea channel={channel} />
|
|
</>
|
|
);
|
|
}
|
|
// file: ./app/routes/app/me/layout.tsx
|
|
import React from "react";
|
|
import { Outlet } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import PrivateChannelListItem from "~/components/custom-ui/private-channel-list-item";
|
|
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
import { usePrivateChannelsStore } from "~/stores/private-channels-store";
|
|
|
|
export async function clientLoader() {
|
|
const { channels, addChannels: setChannels } = usePrivateChannelsStore.getState()
|
|
|
|
const channelList = Object.values(channels)
|
|
|
|
if (!channels || channelList.length === 0) {
|
|
const channels = await import("~/lib/api/client/user").then(m => m.default.channels())
|
|
setChannels(channels)
|
|
}
|
|
}
|
|
|
|
function ListComponent() {
|
|
const channels = usePrivateChannelsStore(useShallow(state => Object.values(state.channels)))
|
|
|
|
return (
|
|
<div className="h-full flex flex-col">
|
|
<div className="w-full min-h-12">
|
|
<div className="border-b-2 h-full flex items-center justify-center">
|
|
Private Messages
|
|
</div>
|
|
</div>
|
|
|
|
<ScrollArea className="overflow-auto" scrollbarSize="narrow">
|
|
<div className="p-2 flex flex-col gap-1 h-full">
|
|
{channels.sort((a, b) => (a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1).map((channel, _) => (
|
|
<React.Fragment key={channel.id}>
|
|
<PrivateChannelListItem channel={channel} />
|
|
</React.Fragment>
|
|
))}
|
|
</div>
|
|
</ScrollArea>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export const handle = {
|
|
listComponent: <ListComponent />
|
|
}
|
|
|
|
export default function Layout() {
|
|
return (
|
|
<>
|
|
<Outlet />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: ./app/routes/app/server/layout.tsx
|
|
import React from "react";
|
|
import { Outlet, redirect, useNavigate, useParams, type ShouldRevalidateFunctionArgs } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import ServerChannelListItem from "~/components/custom-ui/channel-list-item";
|
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "~/components/ui/dropdown-menu";
|
|
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
import type { ServerId } from "~/lib/api/types";
|
|
import { useGatewayStore } from "~/stores/gateway-store";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { useServerChannelsStore } from "~/stores/server-channels-store";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import type { Route } from "../server/+types/layout";
|
|
|
|
export async function clientLoader({
|
|
params: { serverId }
|
|
}: Route.ClientLoaderArgs) {
|
|
const { channels, addChannels, addServer } = useServerChannelsStore.getState()
|
|
|
|
const server = useServerListStore.getState().servers[serverId as ServerId] || undefined
|
|
|
|
if (!server) {
|
|
return redirect("/app/@me")
|
|
}
|
|
|
|
const channelList = channels[serverId as ServerId]
|
|
|
|
if (channelList === undefined) {
|
|
const channels = await import("~/lib/api/client/server").then(m => m.default.listChannels(serverId as ServerId))
|
|
addServer(serverId as ServerId)
|
|
addChannels(channels)
|
|
|
|
useGatewayStore.getState().requestVoiceStates(serverId as ServerId)
|
|
}
|
|
}
|
|
|
|
export function shouldRevalidate(
|
|
arg: ShouldRevalidateFunctionArgs
|
|
) {
|
|
return true
|
|
}
|
|
|
|
function ListComponent() {
|
|
const serverId = useParams<{ serverId: ServerId }>().serverId!
|
|
const currentUserId = useUsersStore(state => state.currentUserId)
|
|
const onOpen = useModalStore(state => state.onOpen)
|
|
|
|
const server = useServerListStore(useShallow(state => state.servers[serverId] || null))
|
|
|
|
const channels = Array.from(useServerChannelsStore(useShallow(state => Object.values(state.channels[serverId] || {}))))
|
|
|
|
if (!server) {
|
|
return null
|
|
}
|
|
|
|
return (
|
|
<div className="h-full flex flex-col">
|
|
<div className="w-full min-h-12">
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<div className="border-b-2 h-full flex items-center justify-center cursor-pointer">
|
|
{server?.name}
|
|
</div>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent>
|
|
<DropdownMenuItem onClick={() => onOpen(ModalType.CREATE_SERVER_INVITE, { serverId })}>Create invite</DropdownMenuItem>
|
|
<DropdownMenuItem onClick={() => onOpen(ModalType.CREATE_SERVER_CHANNEL, { serverId })}>Create channel</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
{currentUserId === server.ownerId &&
|
|
<DropdownMenuItem variant="destructive" onClick={() => onOpen(ModalType.DELETE_SERVER_CONFIRM, { serverId })}>Delete</DropdownMenuItem>}
|
|
{currentUserId !== server.ownerId &&
|
|
<DropdownMenuItem variant="destructive">Leave</DropdownMenuItem>}
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
</div>
|
|
|
|
<ScrollArea className="overflow-auto" scrollbarSize="narrow">
|
|
<div className="p-2 flex flex-col gap-1 h-full">
|
|
{channels.sort((a, b) => (a.lastMessageId ?? a.id) < (b.lastMessageId ?? b.id) ? 1 : -1).map((channel, _) => (
|
|
<React.Fragment key={channel.id}>
|
|
<ServerChannelListItem channel={channel} />
|
|
</React.Fragment>
|
|
))}
|
|
</div>
|
|
</ScrollArea>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export const handle = {
|
|
listComponent: <ListComponent />
|
|
}
|
|
|
|
export default function Layout(
|
|
{ params: { serverId } }: Route.ComponentProps
|
|
) {
|
|
const server = useServerListStore(useShallow(state => state.servers[serverId!] || null))
|
|
const navigate = useNavigate()
|
|
|
|
if (!server) {
|
|
setTimeout(() => navigate("/app/@me"), 0)
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Outlet />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: ./app/routes/app/server/index.tsx
|
|
|
|
export default function Index() {
|
|
return (
|
|
<>
|
|
{/* <div className="h-full">
|
|
<div className="size-full relative">
|
|
<div className="absolute bottom-0 w-full max-h-1/2">
|
|
<div className="p-2">
|
|
<TextBox value={""}
|
|
onChange={(m) => { }}
|
|
placeholder="Type your message here..."
|
|
// Example of custom styling:
|
|
// wrapperClassName="bg-gray-700 border-gray-600 rounded-lg"
|
|
// inputClassName="text-lg"
|
|
aria-label="Message input" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div> */}
|
|
</>
|
|
);
|
|
}
|
|
|
|
// file: ./app/routes/app/server/channel.tsx
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import ChannelArea from "~/components/channel-area";
|
|
import { useServerChannelsStore } from "~/stores/server-channels-store";
|
|
import type { Route } from "./+types/channel";
|
|
|
|
export default function Channel(
|
|
{ params: { serverId, channelId } }: Route.ComponentProps
|
|
) {
|
|
const channel = useServerChannelsStore(useShallow(state => state.channels[serverId][channelId]))
|
|
|
|
return (
|
|
<>
|
|
<ChannelArea channel={channel} />
|
|
</>
|
|
);
|
|
}
|
|
// file: ./app/routes/app/invite.tsx
|
|
import { redirect } from "react-router";
|
|
import type { Route } from "./+types/invite";
|
|
|
|
export async function clientLoader(
|
|
{ params }: Route.ClientLoaderArgs
|
|
) {
|
|
const inviteCode = params.inviteCode
|
|
|
|
try {
|
|
const response = await import("~/lib/api/client/server").then(m => m.default.getInvite(inviteCode))
|
|
|
|
return redirect(`/app/server/${response.id}`)
|
|
} catch (error) {
|
|
return redirect("/app/@me")
|
|
}
|
|
}
|
|
|
|
export default function Index() {
|
|
return null;
|
|
}
|
|
|
|
// file: ./app/routes/app/providers.tsx
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { Outlet, redirect } from "react-router";
|
|
import { create } from "zustand";
|
|
import { GatewayWebSocketConnectionManager } from "~/components/manager/gateway-websocket-connection-manager";
|
|
import { WebRTCConnectionManager } from "~/components/manager/webrtc-connection-manager";
|
|
import ModalProvider from "~/components/providers/modal-provider";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
export async function clientLoader() {
|
|
const { currentUserId, setCurrentUserId, addUser } = useUsersStore.getState()
|
|
|
|
try {
|
|
if (!currentUserId) {
|
|
const user = await import("~/lib/api/client/user").then(m => m.default.me())
|
|
setCurrentUserId(user.id)
|
|
addUser(user)
|
|
}
|
|
} catch (error) {
|
|
return redirect("/login")
|
|
}
|
|
}
|
|
|
|
const useQueryClient = create(() => new QueryClient());
|
|
|
|
export default function Layout() {
|
|
const queryClient = useQueryClient();
|
|
|
|
return (
|
|
<QueryClientProvider client={queryClient}>
|
|
<>
|
|
<ModalProvider />
|
|
<GatewayWebSocketConnectionManager />
|
|
<WebRTCConnectionManager />
|
|
<Outlet />
|
|
</>
|
|
</QueryClientProvider>
|
|
);
|
|
}
|
|
// file: ./app/root.tsx
|
|
import {
|
|
isRouteErrorResponse,
|
|
Links,
|
|
Meta,
|
|
Outlet,
|
|
Scripts,
|
|
ScrollRestoration,
|
|
} from "react-router";
|
|
|
|
import { ThemeProvider } from "~/components/theme/theme-provider";
|
|
import type { Route } from "./+types/root";
|
|
|
|
import "./app.css";
|
|
|
|
export const links: Route.LinksFunction = () => [
|
|
{ rel: "preconnect", href: "https://fonts.googleapis.com" },
|
|
{
|
|
rel: "preconnect",
|
|
href: "https://fonts.gstatic.com",
|
|
crossOrigin: "anonymous",
|
|
},
|
|
{
|
|
rel: "stylesheet",
|
|
href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap",
|
|
},
|
|
];
|
|
|
|
export default function App() {
|
|
return (
|
|
<ThemeProvider defaultTheme="system" storageKey="ui-theme">
|
|
<Outlet />
|
|
</ThemeProvider>
|
|
);
|
|
}
|
|
|
|
export function Layout({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<html lang="en">
|
|
<head>
|
|
<meta charSet="utf-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
<Meta />
|
|
<Links />
|
|
</head>
|
|
<body>
|
|
{children}
|
|
<ScrollRestoration />
|
|
<Scripts />
|
|
</body>
|
|
</html>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
|
|
let message = "Oops!";
|
|
let details = "An unexpected error occurred.";
|
|
let stack: string | undefined;
|
|
|
|
if (isRouteErrorResponse(error)) {
|
|
message = error.status === 404 ? "404" : "Error";
|
|
details =
|
|
error.status === 404
|
|
? "The requested page could not be found."
|
|
: error.statusText || details;
|
|
} else if (import.meta.env.DEV && error && error instanceof Error) {
|
|
details = error.message;
|
|
stack = error.stack;
|
|
}
|
|
|
|
return (
|
|
<main className="pt-16 p-4 container mx-auto">
|
|
<h1>{message}</h1>
|
|
<p>{details}</p>
|
|
{stack && (
|
|
<pre className="w-full p-4 overflow-x-auto">
|
|
<code>{stack}</code>
|
|
</pre>
|
|
)}
|
|
</main>
|
|
);
|
|
}
|
|
|
|
// file: ./app/components/ui/button.tsx
|
|
import { Slot } from "@radix-ui/react-slot"
|
|
import { cva, type VariantProps } from "class-variance-authority"
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
const buttonVariants = cva(
|
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
|
{
|
|
variants: {
|
|
variant: {
|
|
default:
|
|
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
|
destructive:
|
|
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
|
outline:
|
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
|
secondary:
|
|
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
|
ghost:
|
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
|
link: "text-primary underline-offset-4 hover:underline",
|
|
},
|
|
size: {
|
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
|
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
|
icon: "size-9",
|
|
none: ""
|
|
},
|
|
},
|
|
defaultVariants: {
|
|
variant: "default",
|
|
size: "default",
|
|
},
|
|
}
|
|
)
|
|
|
|
function Button({
|
|
className,
|
|
variant,
|
|
size,
|
|
asChild = false,
|
|
...props
|
|
}: React.ComponentProps<"button"> &
|
|
VariantProps<typeof buttonVariants> & {
|
|
asChild?: boolean
|
|
}) {
|
|
const Comp = asChild ? Slot : "button"
|
|
|
|
return (
|
|
<Comp
|
|
data-slot="button"
|
|
className={cn(buttonVariants({ variant, size, className }))}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Button, buttonVariants }
|
|
|
|
// file: ./app/components/ui/form.tsx
|
|
import * as LabelPrimitive from "@radix-ui/react-label"
|
|
import { Slot } from "@radix-ui/react-slot"
|
|
import * as React from "react"
|
|
import {
|
|
Controller,
|
|
FormProvider,
|
|
useFormContext,
|
|
useFormState,
|
|
type ControllerProps,
|
|
type FieldPath,
|
|
type FieldValues,
|
|
} from "react-hook-form"
|
|
|
|
import { Label } from "~/components/ui/label"
|
|
import { cn } from "~/lib/utils"
|
|
|
|
const Form = FormProvider
|
|
|
|
type FormFieldContextValue<
|
|
TFieldValues extends FieldValues = FieldValues,
|
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
|
> = {
|
|
name: TName,
|
|
}
|
|
|
|
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
|
{} as FormFieldContextValue
|
|
)
|
|
|
|
const FormField = <
|
|
TFieldValues extends FieldValues = FieldValues,
|
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
|
>({
|
|
...props
|
|
}: ControllerProps<TFieldValues, TName>) => {
|
|
return (
|
|
<FormFieldContext.Provider value={{ name: props.name }}>
|
|
<Controller {...props} />
|
|
</FormFieldContext.Provider>
|
|
)
|
|
}
|
|
|
|
const useFormField = () => {
|
|
const fieldContext = React.useContext(FormFieldContext)
|
|
const itemContext = React.useContext(FormItemContext)
|
|
const { getFieldState } = useFormContext()
|
|
const formState = useFormState({ name: fieldContext.name })
|
|
const fieldState = getFieldState(fieldContext.name, formState)
|
|
|
|
if (!fieldContext) {
|
|
throw new Error("useFormField should be used within <FormField>")
|
|
}
|
|
|
|
const { id } = itemContext
|
|
|
|
return {
|
|
id,
|
|
name: fieldContext.name,
|
|
formItemId: `${id}-form-item`,
|
|
formDescriptionId: `${id}-form-item-description`,
|
|
formMessageId: `${id}-form-item-message`,
|
|
...fieldState,
|
|
}
|
|
}
|
|
|
|
type FormItemContextValue = {
|
|
id: string,
|
|
}
|
|
|
|
const FormItemContext = React.createContext<FormItemContextValue>(
|
|
{} as FormItemContextValue
|
|
)
|
|
|
|
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
|
const id = React.useId()
|
|
|
|
return (
|
|
<FormItemContext.Provider value={{ id }}>
|
|
<div
|
|
data-slot="form-item"
|
|
className={cn("grid gap-2", className)}
|
|
{...props}
|
|
/>
|
|
</FormItemContext.Provider>
|
|
)
|
|
}
|
|
|
|
function FormLabel({
|
|
className,
|
|
required,
|
|
...props
|
|
}: React.ComponentProps<typeof LabelPrimitive.Root> & { required?: boolean }) {
|
|
const { error, formItemId } = useFormField()
|
|
|
|
return (
|
|
<div className="flex items-center gap-1">
|
|
<Label
|
|
data-slot="form-label"
|
|
data-error={!!error}
|
|
className={cn("data-[error=true]:text-destructive", className)}
|
|
htmlFor={formItemId}
|
|
{...props}
|
|
/>
|
|
{required && <Label className="text-destructive">*</Label>}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
|
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
|
|
|
return (
|
|
<Slot
|
|
data-slot="form-control"
|
|
id={formItemId}
|
|
aria-describedby={
|
|
!error
|
|
? `${formDescriptionId}`
|
|
: `${formDescriptionId} ${formMessageId}`
|
|
}
|
|
aria-invalid={!!error}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
|
const { formDescriptionId } = useFormField()
|
|
|
|
return (
|
|
<p
|
|
data-slot="form-description"
|
|
id={formDescriptionId}
|
|
className={cn("text-muted-foreground text-sm", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
|
const { error, formMessageId } = useFormField()
|
|
const body = error ? String(error?.message ?? "") : props.children
|
|
|
|
if (!body) {
|
|
return null
|
|
}
|
|
|
|
return (
|
|
<p
|
|
data-slot="form-message"
|
|
id={formMessageId}
|
|
className={cn("text-destructive text-sm", className)}
|
|
{...props}
|
|
>
|
|
{body}
|
|
</p>
|
|
)
|
|
}
|
|
|
|
export {
|
|
Form, FormControl,
|
|
FormDescription, FormField, FormItem,
|
|
FormLabel, FormMessage, useFormField
|
|
}
|
|
|
|
|
|
// file: ./app/components/ui/label.tsx
|
|
"use client"
|
|
|
|
import * as React from "react"
|
|
import * as LabelPrimitive from "@radix-ui/react-label"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Label({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
|
return (
|
|
<LabelPrimitive.Root
|
|
data-slot="label"
|
|
className={cn(
|
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Label }
|
|
|
|
// file: ./app/components/ui/input.tsx
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
|
return (
|
|
<input
|
|
type={type}
|
|
data-slot="input"
|
|
className={cn(
|
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
|
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
|
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Input }
|
|
|
|
// file: ./app/components/ui/tabs.tsx
|
|
import * as React from "react"
|
|
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Tabs({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
|
return (
|
|
<TabsPrimitive.Root
|
|
data-slot="tabs"
|
|
className={cn("flex flex-col gap-2", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function TabsList({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
|
return (
|
|
<TabsPrimitive.List
|
|
data-slot="tabs-list"
|
|
className={cn(
|
|
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function TabsTrigger({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
|
return (
|
|
<TabsPrimitive.Trigger
|
|
data-slot="tabs-trigger"
|
|
className={cn(
|
|
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function TabsContent({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
|
return (
|
|
<TabsPrimitive.Content
|
|
data-slot="tabs-content"
|
|
className={cn("flex-1 outline-none", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
|
|
|
// file: ./app/components/ui/card.tsx
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card"
|
|
className={cn(
|
|
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-header"
|
|
className={cn(
|
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-title"
|
|
className={cn("leading-none font-semibold", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-description"
|
|
className={cn("text-muted-foreground text-sm", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-action"
|
|
className={cn(
|
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-content"
|
|
className={cn("px-6", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card-footer"
|
|
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export {
|
|
Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle
|
|
}
|
|
|
|
|
|
// file: ./app/components/ui/dropdown-menu.tsx
|
|
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function DropdownMenu({
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
|
}
|
|
|
|
function DropdownMenuPortal({
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
|
return (
|
|
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
|
)
|
|
}
|
|
|
|
function DropdownMenuTrigger({
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
|
return (
|
|
<DropdownMenuPrimitive.Trigger
|
|
data-slot="dropdown-menu-trigger"
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuContent({
|
|
className,
|
|
sideOffset = 4,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
|
return (
|
|
<DropdownMenuPrimitive.Portal>
|
|
<DropdownMenuPrimitive.Content
|
|
data-slot="dropdown-menu-content"
|
|
sideOffset={sideOffset}
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
</DropdownMenuPrimitive.Portal>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuGroup({
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
|
return (
|
|
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
|
)
|
|
}
|
|
|
|
function DropdownMenuItem({
|
|
className,
|
|
inset,
|
|
variant = "default",
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
|
inset?: boolean
|
|
variant?: "default" | "destructive"
|
|
}) {
|
|
return (
|
|
<DropdownMenuPrimitive.Item
|
|
data-slot="dropdown-menu-item"
|
|
data-inset={inset}
|
|
data-variant={variant}
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuCheckboxItem({
|
|
className,
|
|
children,
|
|
checked,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
|
return (
|
|
<DropdownMenuPrimitive.CheckboxItem
|
|
data-slot="dropdown-menu-checkbox-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className
|
|
)}
|
|
checked={checked}
|
|
{...props}
|
|
>
|
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
|
<DropdownMenuPrimitive.ItemIndicator>
|
|
<CheckIcon className="size-4" />
|
|
</DropdownMenuPrimitive.ItemIndicator>
|
|
</span>
|
|
{children}
|
|
</DropdownMenuPrimitive.CheckboxItem>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuRadioGroup({
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
|
return (
|
|
<DropdownMenuPrimitive.RadioGroup
|
|
data-slot="dropdown-menu-radio-group"
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuRadioItem({
|
|
className,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
|
return (
|
|
<DropdownMenuPrimitive.RadioItem
|
|
data-slot="dropdown-menu-radio-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
|
<DropdownMenuPrimitive.ItemIndicator>
|
|
<CircleIcon className="size-2 fill-current" />
|
|
</DropdownMenuPrimitive.ItemIndicator>
|
|
</span>
|
|
{children}
|
|
</DropdownMenuPrimitive.RadioItem>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuLabel({
|
|
className,
|
|
inset,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
|
inset?: boolean
|
|
}) {
|
|
return (
|
|
<DropdownMenuPrimitive.Label
|
|
data-slot="dropdown-menu-label"
|
|
data-inset={inset}
|
|
className={cn(
|
|
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuSeparator({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
|
return (
|
|
<DropdownMenuPrimitive.Separator
|
|
data-slot="dropdown-menu-separator"
|
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuShortcut({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<"span">) {
|
|
return (
|
|
<span
|
|
data-slot="dropdown-menu-shortcut"
|
|
className={cn(
|
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuSub({
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
|
}
|
|
|
|
function DropdownMenuSubTrigger({
|
|
className,
|
|
inset,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
|
inset?: boolean
|
|
}) {
|
|
return (
|
|
<DropdownMenuPrimitive.SubTrigger
|
|
data-slot="dropdown-menu-sub-trigger"
|
|
data-inset={inset}
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<ChevronRightIcon className="ml-auto size-4" />
|
|
</DropdownMenuPrimitive.SubTrigger>
|
|
)
|
|
}
|
|
|
|
function DropdownMenuSubContent({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
|
return (
|
|
<DropdownMenuPrimitive.SubContent
|
|
data-slot="dropdown-menu-sub-content"
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export {
|
|
DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent,
|
|
DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup,
|
|
DropdownMenuRadioItem,
|
|
DropdownMenuSeparator,
|
|
DropdownMenuShortcut,
|
|
DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger
|
|
}
|
|
|
|
|
|
// file: ./app/components/ui/separator.tsx
|
|
import * as React from "react"
|
|
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Separator({
|
|
className,
|
|
orientation = "horizontal",
|
|
decorative = true,
|
|
...props
|
|
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
|
return (
|
|
<SeparatorPrimitive.Root
|
|
data-slot="separator-root"
|
|
decorative={decorative}
|
|
orientation={orientation}
|
|
className={cn(
|
|
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Separator }
|
|
|
|
// file: ./app/components/ui/avatar.tsx
|
|
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Avatar({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
|
return (
|
|
<AvatarPrimitive.Root
|
|
data-slot="avatar"
|
|
className={cn(
|
|
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function AvatarImage({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
|
return (
|
|
<AvatarPrimitive.Image
|
|
data-slot="avatar-image"
|
|
className={cn("aspect-square size-full", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function AvatarFallback({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
|
return (
|
|
<AvatarPrimitive.Fallback
|
|
data-slot="avatar-fallback"
|
|
className={cn(
|
|
"bg-muted flex size-full items-center justify-center rounded-full",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Avatar, AvatarFallback, AvatarImage }
|
|
|
|
|
|
// file: ./app/components/ui/scroll-area.tsx
|
|
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function ScrollArea({
|
|
className,
|
|
children,
|
|
scrollbarSize,
|
|
viewportRef,
|
|
...props
|
|
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
|
|
scrollbarSize?: "default" | "narrow" | "none",
|
|
viewportRef?: React.Ref<HTMLDivElement>
|
|
}) {
|
|
return (
|
|
<ScrollAreaPrimitive.Root
|
|
data-slot="scroll-area"
|
|
className={cn("relative", className)}
|
|
{...props}
|
|
>
|
|
<ScrollAreaPrimitive.Viewport
|
|
ref={viewportRef}
|
|
data-slot="scroll-area-viewport"
|
|
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
|
>
|
|
{children}
|
|
</ScrollAreaPrimitive.Viewport>
|
|
<ScrollBar size={scrollbarSize} />
|
|
<ScrollAreaPrimitive.Corner />
|
|
</ScrollAreaPrimitive.Root>
|
|
)
|
|
}
|
|
|
|
function ScrollBar({
|
|
className,
|
|
orientation = "vertical",
|
|
size = "default",
|
|
...props
|
|
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar> & {
|
|
size?: "default" | "narrow" | "none"
|
|
}) {
|
|
const classes = {
|
|
vertical: {
|
|
className: "h-full border-l border-l-transparent",
|
|
size: {
|
|
default: "w-2.5",
|
|
narrow: "w-1.5",
|
|
none: "hidden",
|
|
},
|
|
},
|
|
horizontal: {
|
|
className: "flex-col border-t border-t-transparent",
|
|
size: {
|
|
default: "h-2.5",
|
|
narrow: "h-1.5",
|
|
none: "hidden",
|
|
},
|
|
},
|
|
}
|
|
|
|
return (
|
|
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
|
data-slot="scroll-area-scrollbar"
|
|
orientation={orientation}
|
|
className={cn(
|
|
"flex touch-none p-px transition-colors select-none",
|
|
classes[orientation].className,
|
|
classes[orientation].size[size],
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
<ScrollAreaPrimitive.ScrollAreaThumb
|
|
data-slot="scroll-area-thumb"
|
|
className="bg-border relative flex-1 rounded-full"
|
|
/>
|
|
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
|
)
|
|
}
|
|
|
|
export { ScrollArea, ScrollBar }
|
|
|
|
// file: ./app/components/ui/textarea.tsx
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
|
return (
|
|
<textarea
|
|
data-slot="textarea"
|
|
className={cn(
|
|
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Textarea }
|
|
|
|
// file: ./app/components/ui/dialog.tsx
|
|
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
|
import { XIcon } from "lucide-react"
|
|
import * as React from "react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Dialog({
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
|
}
|
|
|
|
function DialogTrigger({
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
|
}
|
|
|
|
function DialogPortal({
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
|
}
|
|
|
|
function DialogClose({
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
|
}
|
|
|
|
function DialogOverlay({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
|
return (
|
|
<DialogPrimitive.Overlay
|
|
data-slot="dialog-overlay"
|
|
className={cn(
|
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DialogContent({
|
|
className,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
|
|
return (
|
|
<DialogPortal data-slot="dialog-portal">
|
|
<DialogOverlay />
|
|
<DialogPrimitive.Content
|
|
data-slot="dialog-content"
|
|
className={cn(
|
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
|
<XIcon />
|
|
<span className="sr-only">Close</span>
|
|
</DialogPrimitive.Close>
|
|
</DialogPrimitive.Content>
|
|
</DialogPortal>
|
|
)
|
|
}
|
|
|
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="dialog-header"
|
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="dialog-footer"
|
|
className={cn(
|
|
"flex flex-col-reverse gap-2 sm:flex-row",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DialogTitle({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
|
return (
|
|
<DialogPrimitive.Title
|
|
data-slot="dialog-title"
|
|
className={cn("text-lg leading-none font-semibold", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function DialogDescription({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
|
return (
|
|
<DialogPrimitive.Description
|
|
data-slot="dialog-description"
|
|
className={cn("text-muted-foreground text-sm", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export {
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogOverlay,
|
|
DialogPortal,
|
|
DialogTitle,
|
|
DialogTrigger
|
|
}
|
|
|
|
|
|
// file: ./app/components/ui/tooltip.tsx
|
|
import * as React from "react"
|
|
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function TooltipProvider({
|
|
delayDuration = 0,
|
|
...props
|
|
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
|
return (
|
|
<TooltipPrimitive.Provider
|
|
data-slot="tooltip-provider"
|
|
delayDuration={delayDuration}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function Tooltip({
|
|
...props
|
|
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
|
return (
|
|
<TooltipProvider>
|
|
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
|
</TooltipProvider>
|
|
)
|
|
}
|
|
|
|
function TooltipTrigger({
|
|
...props
|
|
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
|
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
|
}
|
|
|
|
function TooltipContent({
|
|
className,
|
|
sideOffset = 0,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
|
return (
|
|
<TooltipPrimitive.Portal>
|
|
<TooltipPrimitive.Content
|
|
data-slot="tooltip-content"
|
|
sideOffset={sideOffset}
|
|
className={cn(
|
|
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
|
</TooltipPrimitive.Content>
|
|
</TooltipPrimitive.Portal>
|
|
)
|
|
}
|
|
|
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
|
|
|
// file: ./app/components/ui/icon-upload-field.tsx
|
|
import { ImagePlus, XCircle } from "lucide-react";
|
|
import React, { useCallback, useEffect, useRef, useState } from "react";
|
|
import type { ControllerRenderProps, FieldError } from "react-hook-form";
|
|
import { Button } from "./button"; // Your existing Button component
|
|
|
|
// Props for our custom field component
|
|
interface IconUploadFieldProps {
|
|
field: ControllerRenderProps<any, string>; // Provided by RHF's FormField render prop
|
|
error?: FieldError; // Optional: if you want to pass error for internal styling
|
|
accept?: string; // e.g., "image/png, image/jpeg"
|
|
previewContainerClassName?: string; // Style for the preview box itself
|
|
// Add any other props you might want to customize its appearance/behavior
|
|
}
|
|
|
|
export function IconUploadField({
|
|
field,
|
|
error,
|
|
accept = "image/*",
|
|
previewContainerClassName = "w-24 h-24 rounded-full", // Default circular preview
|
|
}: IconUploadFieldProps) {
|
|
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
|
|
const currentFileValue = field.value as File | undefined | null;
|
|
|
|
useEffect(() => {
|
|
let objectUrl: string | null = null;
|
|
if (currentFileValue && currentFileValue instanceof File) {
|
|
objectUrl = URL.createObjectURL(currentFileValue);
|
|
setPreviewUrl(objectUrl);
|
|
} else {
|
|
setPreviewUrl(null);
|
|
}
|
|
|
|
return () => {
|
|
if (objectUrl) {
|
|
URL.revokeObjectURL(objectUrl);
|
|
}
|
|
};
|
|
}, [currentFileValue]);
|
|
|
|
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
const file = event.target.files?.[0];
|
|
field.onChange(file || undefined);
|
|
if (event.target) {
|
|
event.target.value = "";
|
|
}
|
|
};
|
|
|
|
const handleRemoveImage = useCallback((e: React.MouseEvent<HTMLButtonElement>) => {
|
|
e.preventDefault();
|
|
field.onChange(undefined);
|
|
if (fileInputRef.current) {
|
|
fileInputRef.current.value = "";
|
|
}
|
|
}, [field]);
|
|
|
|
const triggerFileInput = useCallback(() => {
|
|
fileInputRef.current?.click();
|
|
}, []);
|
|
|
|
return (
|
|
<div className="flex items-center space-x-4">
|
|
{/* Main clickable area for upload, also receives RHF's ref */}
|
|
<div
|
|
ref={field.ref} // Attach RHF's ref here for focus management
|
|
className={`relative ${previewContainerClassName} border-2 ${error ? "border-destructive" : "border-dashed border-muted-foreground"
|
|
} flex items-center justify-center cursor-pointer hover:border-primary transition-colors overflow-hidden`}
|
|
onClick={triggerFileInput}
|
|
onKeyDown={(e) => {
|
|
if (e.key === "Enter" || e.key === " ") {
|
|
e.preventDefault();
|
|
triggerFileInput();
|
|
}
|
|
}}
|
|
role="button"
|
|
tabIndex={0}
|
|
aria-label={previewUrl ? "Change icon" : "Upload icon"}
|
|
aria-invalid={!!error}
|
|
aria-describedby={error ? `${field.name}-error` : undefined}
|
|
>
|
|
{previewUrl ? (
|
|
<img
|
|
src={previewUrl}
|
|
alt="Icon preview"
|
|
className="w-full h-full object-cover"
|
|
/>
|
|
) : (
|
|
<ImagePlus className={`w-10 h-10 ${error ? "text-destructive" : "text-muted-foreground"}`} />
|
|
)}
|
|
<input
|
|
type="file"
|
|
ref={fileInputRef} // Internal ref for programmatic click
|
|
className="hidden" // Visually hidden
|
|
accept={accept}
|
|
onChange={handleFileChange}
|
|
onBlur={field.onBlur} // RHF's onBlur for touched state
|
|
name={field.name} // RHF's field name
|
|
// The `value` of a file input is not directly controlled by RHF's `field.value` (which is a File object)
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex flex-col space-y-2">
|
|
{/* <Button type="button" variant="outline" size="sm" onClick={triggerFileInput}>
|
|
{previewUrl ? "Change Icon" : "Upload Icon"}
|
|
</Button> */}
|
|
{currentFileValue && ( // Show remove button only if a file is selected
|
|
<Button
|
|
type="button"
|
|
variant="destructive"
|
|
size="sm"
|
|
onClick={handleRemoveImage}
|
|
>
|
|
<XCircle className="" />
|
|
Remove
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
// file: ./app/components/ui/badge.tsx
|
|
import * as React from "react"
|
|
import { Slot } from "@radix-ui/react-slot"
|
|
import { cva, type VariantProps } from "class-variance-authority"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
const badgeVariants = cva(
|
|
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
|
{
|
|
variants: {
|
|
variant: {
|
|
default:
|
|
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
|
secondary:
|
|
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
|
destructive:
|
|
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
|
outline:
|
|
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
|
},
|
|
},
|
|
defaultVariants: {
|
|
variant: "default",
|
|
},
|
|
}
|
|
)
|
|
|
|
function Badge({
|
|
className,
|
|
variant,
|
|
asChild = false,
|
|
...props
|
|
}: React.ComponentProps<"span"> &
|
|
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
|
const Comp = asChild ? Slot : "span"
|
|
|
|
return (
|
|
<Comp
|
|
data-slot="badge"
|
|
className={cn(badgeVariants({ variant }), className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export { Badge, badgeVariants }
|
|
|
|
// file: ./app/components/ui/select.tsx
|
|
import * as React from "react"
|
|
import * as SelectPrimitive from "@radix-ui/react-select"
|
|
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
|
|
|
import { cn } from "~/lib/utils"
|
|
|
|
function Select({
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
|
return <SelectPrimitive.Root data-slot="select" {...props} />
|
|
}
|
|
|
|
function SelectGroup({
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
|
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
|
}
|
|
|
|
function SelectValue({
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
|
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
|
}
|
|
|
|
function SelectTrigger({
|
|
className,
|
|
size = "default",
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
|
size?: "sm" | "default"
|
|
}) {
|
|
return (
|
|
<SelectPrimitive.Trigger
|
|
data-slot="select-trigger"
|
|
data-size={size}
|
|
className={cn(
|
|
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
{children}
|
|
<SelectPrimitive.Icon asChild>
|
|
<ChevronDownIcon className="size-4 opacity-50" />
|
|
</SelectPrimitive.Icon>
|
|
</SelectPrimitive.Trigger>
|
|
)
|
|
}
|
|
|
|
function SelectContent({
|
|
className,
|
|
children,
|
|
position = "popper",
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
|
return (
|
|
<SelectPrimitive.Portal>
|
|
<SelectPrimitive.Content
|
|
data-slot="select-content"
|
|
className={cn(
|
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
|
position === "popper" &&
|
|
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
|
className
|
|
)}
|
|
position={position}
|
|
{...props}
|
|
>
|
|
<SelectScrollUpButton />
|
|
<SelectPrimitive.Viewport
|
|
className={cn(
|
|
"p-1",
|
|
position === "popper" &&
|
|
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
|
)}
|
|
>
|
|
{children}
|
|
</SelectPrimitive.Viewport>
|
|
<SelectScrollDownButton />
|
|
</SelectPrimitive.Content>
|
|
</SelectPrimitive.Portal>
|
|
)
|
|
}
|
|
|
|
function SelectLabel({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
|
return (
|
|
<SelectPrimitive.Label
|
|
data-slot="select-label"
|
|
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function SelectItem({
|
|
className,
|
|
children,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
|
return (
|
|
<SelectPrimitive.Item
|
|
data-slot="select-item"
|
|
className={cn(
|
|
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
|
<SelectPrimitive.ItemIndicator>
|
|
<CheckIcon className="size-4" />
|
|
</SelectPrimitive.ItemIndicator>
|
|
</span>
|
|
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
|
</SelectPrimitive.Item>
|
|
)
|
|
}
|
|
|
|
function SelectSeparator({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
|
return (
|
|
<SelectPrimitive.Separator
|
|
data-slot="select-separator"
|
|
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
|
{...props}
|
|
/>
|
|
)
|
|
}
|
|
|
|
function SelectScrollUpButton({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
|
return (
|
|
<SelectPrimitive.ScrollUpButton
|
|
data-slot="select-scroll-up-button"
|
|
className={cn(
|
|
"flex cursor-default items-center justify-center py-1",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
<ChevronUpIcon className="size-4" />
|
|
</SelectPrimitive.ScrollUpButton>
|
|
)
|
|
}
|
|
|
|
function SelectScrollDownButton({
|
|
className,
|
|
...props
|
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
|
return (
|
|
<SelectPrimitive.ScrollDownButton
|
|
data-slot="select-scroll-down-button"
|
|
className={cn(
|
|
"flex cursor-default items-center justify-center py-1",
|
|
className
|
|
)}
|
|
{...props}
|
|
>
|
|
<ChevronDownIcon className="size-4" />
|
|
</SelectPrimitive.ScrollDownButton>
|
|
)
|
|
}
|
|
|
|
export {
|
|
Select,
|
|
SelectContent,
|
|
SelectGroup,
|
|
SelectItem,
|
|
SelectLabel,
|
|
SelectScrollDownButton,
|
|
SelectScrollUpButton,
|
|
SelectSeparator,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
}
|
|
|
|
// file: ./app/components/icons/Discord.tsx
|
|
import type { SVGProps } from "react";
|
|
|
|
const Discord = (props: SVGProps<SVGSVGElement>) => <svg viewBox="0 0 256 199" width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid" {...props}><path d="M216.856 16.597A208.502 208.502 0 0 0 164.042 0c-2.275 4.113-4.933 9.645-6.766 14.046-19.692-2.961-39.203-2.961-58.533 0-1.832-4.4-4.55-9.933-6.846-14.046a207.809 207.809 0 0 0-52.855 16.638C5.618 67.147-3.443 116.4 1.087 164.956c22.169 16.555 43.653 26.612 64.775 33.193A161.094 161.094 0 0 0 79.735 175.3a136.413 136.413 0 0 1-21.846-10.632 108.636 108.636 0 0 0 5.356-4.237c42.122 19.702 87.89 19.702 129.51 0a131.66 131.66 0 0 0 5.355 4.237 136.07 136.07 0 0 1-21.886 10.653c4.006 8.02 8.638 15.67 13.873 22.848 21.142-6.58 42.646-16.637 64.815-33.213 5.316-56.288-9.08-105.09-38.056-148.36ZM85.474 135.095c-12.645 0-23.015-11.805-23.015-26.18s10.149-26.2 23.015-26.2c12.867 0 23.236 11.804 23.015 26.2.02 14.375-10.148 26.18-23.015 26.18Zm85.051 0c-12.645 0-23.014-11.805-23.014-26.18s10.148-26.2 23.014-26.2c12.867 0 23.236 11.804 23.015 26.2 0 14.375-10.148 26.18-23.015 26.18Z" fill="#5865F2" /></svg>;
|
|
|
|
export default Discord;
|
|
// file: ./app/components/theme/theme-provider.tsx
|
|
import { createContext, useContext, useEffect, useState } from "react"
|
|
|
|
export type Theme = "dark" | "light" | "system"
|
|
|
|
type ThemeProviderProps = {
|
|
children: React.ReactNode
|
|
defaultTheme?: Theme
|
|
storageKey?: string
|
|
}
|
|
|
|
type ThemeProviderState = {
|
|
theme: Theme
|
|
setTheme: (theme: Theme) => void
|
|
}
|
|
|
|
const initialState: ThemeProviderState = {
|
|
theme: "system",
|
|
setTheme: () => null,
|
|
}
|
|
|
|
const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
|
|
|
|
export function ThemeProvider({
|
|
children,
|
|
defaultTheme = "system",
|
|
storageKey = "ui-theme",
|
|
...props
|
|
}: ThemeProviderProps) {
|
|
const [theme, setTheme] = useState<Theme>(
|
|
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
|
|
)
|
|
|
|
useEffect(() => {
|
|
const root = window.document.documentElement
|
|
|
|
root.classList.remove("light", "dark")
|
|
|
|
if (theme === "system") {
|
|
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
|
|
.matches
|
|
? "dark"
|
|
: "light"
|
|
|
|
root.classList.add(systemTheme)
|
|
return
|
|
}
|
|
|
|
root.classList.add(theme)
|
|
}, [theme])
|
|
|
|
const value = {
|
|
theme,
|
|
setTheme: (theme: Theme) => {
|
|
localStorage.setItem(storageKey, theme)
|
|
setTheme(theme)
|
|
},
|
|
}
|
|
|
|
return (
|
|
<ThemeProviderContext.Provider {...props} value={value}>
|
|
{children}
|
|
</ThemeProviderContext.Provider>
|
|
)
|
|
}
|
|
|
|
export const useTheme = () => {
|
|
const context = useContext(ThemeProviderContext)
|
|
|
|
if (context === undefined)
|
|
throw new Error("useTheme must be used within a ThemeProvider")
|
|
|
|
return context
|
|
}
|
|
|
|
// file: ./app/components/theme/theme-toggle.tsx
|
|
import { Moon, Sun } from "lucide-react"
|
|
|
|
import { useTheme, type Theme } from "~/components/theme/theme-provider"
|
|
import { Button } from "~/components/ui/button"
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuRadioGroup,
|
|
DropdownMenuRadioItem,
|
|
DropdownMenuTrigger
|
|
} from "~/components/ui/dropdown-menu"
|
|
|
|
export function ThemeToggle() {
|
|
const { theme, setTheme } = useTheme()
|
|
|
|
return (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="outline" size="icon">
|
|
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
|
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
|
<span className="sr-only">Toggle theme</span>
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent>
|
|
<DropdownMenuRadioGroup value={theme} onValueChange={(value) => setTheme(value as Theme)}>
|
|
<DropdownMenuRadioItem value="light">
|
|
Light
|
|
</DropdownMenuRadioItem>
|
|
<DropdownMenuRadioItem value="dark">
|
|
Dark
|
|
</DropdownMenuRadioItem>
|
|
<DropdownMenuRadioItem value="system">
|
|
System
|
|
</DropdownMenuRadioItem>
|
|
</DropdownMenuRadioGroup>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
)
|
|
}
|
|
// file: ./app/components/app-layout.tsx
|
|
import React from "react";
|
|
import { useMatches } from "react-router";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
import { CreateServerButton } from "./custom-ui/create-server-button";
|
|
import { HomeButton } from "./custom-ui/home-button";
|
|
import { ServerButton } from "./custom-ui/server-button";
|
|
import UserStatus from "./custom-ui/user-status";
|
|
import { ScrollArea } from "./ui/scroll-area";
|
|
import { Separator } from "./ui/separator";
|
|
|
|
interface AppLayoutProps {
|
|
children: React.ReactNode;
|
|
}
|
|
|
|
export default function AppLayout({ children }: AppLayoutProps) {
|
|
let servers = useServerListStore(useShallow((state) => Object.values(state.servers)))
|
|
|
|
const matches = useMatches();
|
|
|
|
let list = React.useMemo(() => {
|
|
return matches.map(match => (match.handle as {
|
|
listComponent?: React.ReactNode
|
|
})?.listComponent).reverse().find(component => !!component)
|
|
}, [matches])
|
|
|
|
return (
|
|
<div className="flex h-screen w-screen overflow-hidden">
|
|
<div className="grid h-full max-h-screen bg-background min-w-80 border-r-2" style={{ gridTemplateColumns: "auto 1fr", gridTemplateRows: "1fr auto" }}>
|
|
<div className="col-start-1 row-start-1 col-span-1 row-span-1 overflow-hidden border-r-2 min-w-fit">
|
|
<ScrollArea className="h-full px-1" scrollbarSize="none">
|
|
<aside className="flex flex-col gap-4 p-2 h-full">
|
|
<HomeButton />
|
|
<Separator />
|
|
{
|
|
servers.map((server, _) =>
|
|
<React.Fragment key={server.id}>
|
|
<ServerButton server={server} />
|
|
</React.Fragment>
|
|
)
|
|
}
|
|
{servers.length > 0 && <Separator />}
|
|
<CreateServerButton />
|
|
</aside>
|
|
</ScrollArea>
|
|
</div>
|
|
<div className="col-start-2 row-start-1 col-span-1 row-span-1 overflow-hidden">
|
|
{list}
|
|
</div>
|
|
|
|
<div className="col-start-1 row-start-2 col-span-2 row-span-1 mb-2 mx-2 min-w-fit z-1">
|
|
<UserStatus />
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grow">
|
|
{children}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
// file: ./app/components/manager/gateway-websocket-connection-manager.tsx
|
|
import { useQueryClient } from '@tanstack/react-query';
|
|
import { useEffect } from 'react';
|
|
import { ConnectionState } from '~/lib/websocket/gateway/types';
|
|
import { useGatewayStore } from '~/stores/gateway-store';
|
|
import { useTokenStore } from '~/stores/token-store';
|
|
|
|
export function GatewayWebSocketConnectionManager() {
|
|
const token = useTokenStore((state) =>
|
|
state.token,
|
|
);
|
|
|
|
const { setQueryClient } = useGatewayStore();
|
|
|
|
const queryClient = useQueryClient();
|
|
useEffect(() => {
|
|
setQueryClient(queryClient);
|
|
}, [queryClient])
|
|
|
|
useEffect(() => {
|
|
const { status, connect, disconnect } = useGatewayStore.getState();
|
|
|
|
if (!!token) {
|
|
connect(token);
|
|
} else {
|
|
if (status === ConnectionState.CONNECTED) {
|
|
disconnect();
|
|
}
|
|
}
|
|
|
|
return () => {
|
|
if (status === ConnectionState.CONNECTED) {
|
|
disconnect();
|
|
}
|
|
};
|
|
}, [token]);
|
|
|
|
return (
|
|
<>
|
|
{null}
|
|
</>
|
|
);
|
|
}
|
|
// file: ./app/components/manager/webrtc-connection-manager.tsx
|
|
import { useEffect, useRef } from "react";
|
|
import { ConnectionState } from "~/lib/websocket/voice/types";
|
|
import { useGatewayStore } from "~/stores/gateway-store";
|
|
import { useVoiceStateStore } from "~/stores/voice-state-store";
|
|
import { useWebRTCStore } from "~/stores/webrtc-store";
|
|
|
|
export function WebRTCConnectionManager() {
|
|
const gateway = useGatewayStore();
|
|
const voiceState = useVoiceStateStore();
|
|
const webrtc = useWebRTCStore();
|
|
|
|
const remoteStream = useWebRTCStore(state => state.remoteStream);
|
|
const audioRef = useRef<HTMLAudioElement>(null)
|
|
|
|
if (audioRef.current) {
|
|
audioRef.current.srcObject = remoteStream
|
|
}
|
|
|
|
useEffect(() => {
|
|
const unsubscribe = gateway.onVoiceServerUpdate(async (event) => {
|
|
await webrtc.connect(event.token);
|
|
voiceState.joinVoiceChannel(event.serverId, event.channelId);
|
|
|
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
audio: {
|
|
noiseSuppression: false,
|
|
},
|
|
video: false
|
|
});
|
|
|
|
webrtc.createOffer(stream);
|
|
});
|
|
|
|
return () => {
|
|
voiceState.leaveVoiceChannel();
|
|
unsubscribe();
|
|
};
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (webrtc.status === ConnectionState.DISCONNECTED) {
|
|
voiceState.leaveVoiceChannel();
|
|
}
|
|
|
|
}, [webrtc.status]);
|
|
|
|
return (
|
|
<>
|
|
<audio autoPlay ref={audioRef} className="hidden" />
|
|
</>
|
|
);
|
|
}
|
|
// file: ./app/components/modals/create-server-modal.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import file from "~/lib/api/client/file";
|
|
import server from "~/lib/api/client/server";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
|
import { IconUploadField } from "../ui/icon-upload-field";
|
|
import { Input } from "../ui/input";
|
|
|
|
const schema = z.object({
|
|
name: z.string().min(1).max(32),
|
|
icon: z.instanceof(File).optional(),
|
|
});
|
|
|
|
|
|
export default function CreateServerModal() {
|
|
const { type, isOpen, onClose } = useModalStore();
|
|
|
|
const isModalOpen = type === ModalType.CREATE_SERVER && isOpen
|
|
|
|
let form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
});
|
|
|
|
const onOpenChange = (openState: boolean) => {
|
|
form.reset()
|
|
onClose()
|
|
}
|
|
|
|
const onSubmit = async (values: z.infer<typeof schema>) => {
|
|
let iconId = undefined
|
|
if (values.icon) {
|
|
iconId = (await file.uploadFile(values.icon))[0]
|
|
}
|
|
|
|
const response = await server.create({
|
|
name: values.name,
|
|
iconId
|
|
})
|
|
|
|
form.reset()
|
|
onClose()
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Create server</DialogTitle>
|
|
<DialogDescription>
|
|
Give your server a name and choose a server icon.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
|
<FormField
|
|
control={form.control}
|
|
name="icon"
|
|
render={({ field, fieldState }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.icon.isOptional()}>Icon</FormLabel>
|
|
<FormControl>
|
|
<div className="flex flex-col items-center justify-center">
|
|
<IconUploadField
|
|
field={field}
|
|
error={fieldState.error}
|
|
/>
|
|
</div>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="name"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<DialogFooter className=" justify-between">
|
|
<DialogClose asChild>
|
|
<Button type="button" variant="secondary">
|
|
Close
|
|
</Button>
|
|
</DialogClose>
|
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
|
{form.formState.isSubmitting ? "Creating..." : "Create"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</Form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|
|
// file: ./app/components/modals/create-server-channel-modal.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import { ChannelType } from "~/lib/api/types";
|
|
import { ModalType, useModalStore, type CreateServerChannelModalData } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
|
import { Input } from "../ui/input";
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
|
|
|
|
const schema = z.object({
|
|
name: z.string().min(1).max(32),
|
|
type: z.nativeEnum(ChannelType),
|
|
});
|
|
|
|
|
|
export default function CreateServerChannelModal() {
|
|
const { type, data, isOpen, onClose } = useModalStore();
|
|
|
|
const isModalOpen = type === ModalType.CREATE_SERVER_CHANNEL && isOpen
|
|
|
|
let form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
defaultValues: {
|
|
type: ChannelType.SERVER_TEXT
|
|
}
|
|
});
|
|
|
|
const onOpenChange = () => {
|
|
form.reset()
|
|
onClose()
|
|
}
|
|
|
|
const onSubmit = async (values: z.infer<typeof schema>) => {
|
|
const response = await import("~/lib/api/client/server").then(m => m.default.createChannel((data as CreateServerChannelModalData['data']).serverId, values))
|
|
|
|
form.reset()
|
|
onClose()
|
|
}
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Create channel</DialogTitle>
|
|
<DialogDescription>
|
|
Give your channel a name and choose a channel type.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
|
<FormField
|
|
control={form.control}
|
|
name="name"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.name.isOptional()}>Name</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="type"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.type.isOptional()}>Type</FormLabel>
|
|
<Select defaultValue={field.value} onValueChange={field.onChange}>
|
|
<FormControl>
|
|
<SelectTrigger className="w-full">
|
|
<SelectValue placeholder="Select a channel type" />
|
|
</SelectTrigger>
|
|
</FormControl>
|
|
<SelectContent>
|
|
{Object.entries({
|
|
[ChannelType.SERVER_TEXT]: "Text",
|
|
[ChannelType.SERVER_VOICE]: "Voice",
|
|
}).map(([type, label]) => (
|
|
<SelectItem key={type} value={type}>
|
|
{label}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<DialogFooter className=" justify-between">
|
|
<DialogClose asChild>
|
|
<Button type="button" variant="secondary">
|
|
Close
|
|
</Button>
|
|
</DialogClose>
|
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
|
{form.formState.isSubmitting ? "Creating..." : "Create"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</Form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|
|
// file: ./app/components/modals/create-server-invite-modal.tsx
|
|
import { Check, Copy, RefreshCw } from "lucide-react";
|
|
import React from "react";
|
|
import { useOrigin } from "~/hooks/use-origin";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
|
import { Input } from "../ui/input";
|
|
import { Label } from "../ui/label";
|
|
|
|
export default function CreateServerInviteModal() {
|
|
const { type, data, isOpen, onClose } = useModalStore();
|
|
const [inviteCode, setInviteCode] = React.useState<string | undefined>(undefined)
|
|
const origin = useOrigin()
|
|
const [isCopied, setCopied] = React.useState(false)
|
|
|
|
const isModalOpen = type === ModalType.CREATE_SERVER_INVITE && isOpen
|
|
const inviteLink = `${origin}/app/invite/${inviteCode}`
|
|
|
|
const onOpenChange = (openState: boolean) => {
|
|
onClose()
|
|
}
|
|
|
|
const regenerateInviteCode = () => {
|
|
import("~/lib/api/client/server").then(m => m.default.createInvite((data as { serverId: string }).serverId)).then(invite => { setInviteCode(invite.code) })
|
|
}
|
|
|
|
const onCopy = () => {
|
|
navigator.clipboard.writeText(inviteLink)
|
|
setCopied(true)
|
|
|
|
setTimeout(() => setCopied(false), 1000)
|
|
}
|
|
|
|
React.useEffect(() => {
|
|
if (isModalOpen) {
|
|
import("~/lib/api/client/server").then(m => m.default.createInvite((data as { serverId: string }).serverId)).then(invite => { setInviteCode(invite.code) })
|
|
} else {
|
|
setInviteCode(undefined)
|
|
}
|
|
}, [isModalOpen])
|
|
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Invite your friends</DialogTitle>
|
|
</DialogHeader>
|
|
|
|
<Label>Server invite link</Label>
|
|
<div className="flex items-center gap-x-2">
|
|
<Input value={inviteLink} readOnly />
|
|
<Button variant="ghost" size="icon" onClick={onCopy}>
|
|
{isCopied ? <Check className="size-4" /> : <Copy className="size-4" />}
|
|
</Button>
|
|
</div>
|
|
<DialogFooter>
|
|
<Button variant="link" size="none" className="h-9 py-2" onClick={regenerateInviteCode}>
|
|
Generate a new invite
|
|
<RefreshCw />
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|
|
// file: ./app/components/modals/delete-server-confirm-modal.tsx
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { Button } from "../ui/button";
|
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
|
|
|
export default function DeleteServerConfirmModal() {
|
|
const { type, data, isOpen, onClose } = useModalStore();
|
|
|
|
const isModalOpen = type === ModalType.DELETE_SERVER_CONFIRM && isOpen
|
|
|
|
const onOpenChange = () => {
|
|
onClose()
|
|
}
|
|
|
|
const onConfirm = async () => {
|
|
await import("~/lib/api/client/server").then(m => m.default.delet((data as { serverId: string }).serverId))
|
|
onClose()
|
|
}
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Are you sure?</DialogTitle>
|
|
<DialogDescription>
|
|
This action cannot be undone.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<DialogFooter className="justify-between">
|
|
<Button variant="default" onClick={onClose}>
|
|
No
|
|
</Button>
|
|
<Button variant="destructive" onClick={onConfirm}>
|
|
Yes
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|
|
// file: ./app/components/modals/update-profile-modal.tsx
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import file from "~/lib/api/client/file";
|
|
import { patchUser } from "~/lib/api/client/user";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import { Button } from "../ui/button";
|
|
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
|
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
|
|
import { IconUploadField } from "../ui/icon-upload-field";
|
|
import { Input } from "../ui/input";
|
|
|
|
const schema = z.object({
|
|
displayName: z.string().min(1).max(32).optional(),
|
|
avatar: z.instanceof(File).optional(),
|
|
});
|
|
|
|
|
|
export default function UpdateProfileModal() {
|
|
const { type, isOpen, onClose } = useModalStore();
|
|
const user = useUsersStore(useShallow(state => state.getCurrentUser()))
|
|
|
|
const isModalOpen = type === ModalType.UPDATE_PROFILE && isOpen
|
|
|
|
let form = useForm<z.infer<typeof schema>>({
|
|
resolver: zodResolver(schema),
|
|
});
|
|
|
|
const onOpenChange = (openState: boolean) => {
|
|
form.reset()
|
|
onClose()
|
|
}
|
|
|
|
const onSubmit = async (values: z.infer<typeof schema>) => {
|
|
if (!values)
|
|
return
|
|
|
|
let avatarId = undefined
|
|
if (values.avatar) {
|
|
avatarId = (await file.uploadFile(values.avatar))[0]
|
|
}
|
|
|
|
const response = await patchUser({
|
|
displayName: values.displayName,
|
|
avatarId
|
|
})
|
|
|
|
form.reset()
|
|
onClose()
|
|
}
|
|
|
|
return (
|
|
<Dialog open={isModalOpen} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-md">
|
|
<DialogHeader>
|
|
<DialogTitle>Update profile</DialogTitle>
|
|
<DialogDescription>
|
|
Update your profile.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
|
<FormField
|
|
control={form.control}
|
|
name="avatar"
|
|
render={({ field, fieldState }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.avatar.isOptional()}>Avatar</FormLabel>
|
|
<FormControl>
|
|
<div className="flex flex-col items-center justify-center">
|
|
<IconUploadField
|
|
field={field}
|
|
error={fieldState.error}
|
|
/>
|
|
</div>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="displayName"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormLabel required={!schema.shape.displayName.isOptional()}>Display Name</FormLabel>
|
|
<FormControl>
|
|
<Input {...field} placeholder={user?.displayName} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<DialogFooter className=" justify-between">
|
|
<DialogClose asChild>
|
|
<Button type="button" variant="secondary">
|
|
Close
|
|
</Button>
|
|
</DialogClose>
|
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
|
{form.formState.isSubmitting ? "Updating..." : "Update"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</Form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|
|
// file: ./app/components/providers/modal-provider.tsx
|
|
import React from "react";
|
|
import CreateServerChannelModal from "../modals/create-server-channel-modal";
|
|
import CreateServerInviteModal from "../modals/create-server-invite-modal";
|
|
import CreateServerModal from "../modals/create-server-modal";
|
|
import DeleteServerConfirmModal from "../modals/delete-server-confirm-modal";
|
|
import UpdateProfileModal from "../modals/update-profile-modal";
|
|
|
|
export default function ModalProvider() {
|
|
const [isMounted, setIsMounted] = React.useState(false);
|
|
|
|
React.useEffect(() => {
|
|
setIsMounted(true);
|
|
}, []);
|
|
|
|
if (!isMounted) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<CreateServerModal />
|
|
<CreateServerChannelModal />
|
|
<CreateServerInviteModal />
|
|
<DeleteServerConfirmModal />
|
|
<UpdateProfileModal />
|
|
</>
|
|
);
|
|
}
|
|
// file: ./app/components/custom-ui/channel-list-item.tsx
|
|
import { ChevronDown, Hash, Volume2 } from "lucide-react"
|
|
import React from "react"
|
|
import { NavLink } from "react-router"
|
|
import { useShallow } from "zustand/react/shallow"
|
|
import { ChannelType, type ServerChannel } from "~/lib/api/types"
|
|
import { cn } from "~/lib/utils"
|
|
import { useChannelsVoiceStateStore } from "~/stores/channels-voice-state"
|
|
import { useGatewayStore } from "~/stores/gateway-store"
|
|
import { useUsersStore } from "~/stores/users-store"
|
|
import { Button } from "../ui/button"
|
|
import UserAvatar from "../user-avatar"
|
|
|
|
interface ChannelListItemProps {
|
|
channel: ServerChannel
|
|
}
|
|
|
|
function ServerCategory({ channel }: ChannelListItemProps) {
|
|
return (
|
|
<div className="text-xs flex flex-row justify-between mt-4">
|
|
<div className="grow">
|
|
<div className="flex items-center gap-1">
|
|
{channel.name}
|
|
<ChevronDown className="size-4" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function ServerVoice({ channel }: ChannelListItemProps) {
|
|
const updateVoiceState = useGatewayStore(state => state.updateVoiceState)
|
|
const channelVoiceState = useChannelsVoiceStateStore(state => state.channels[channel.id]) || {}
|
|
const userIds = Object.keys(channelVoiceState.users ?? {})
|
|
|
|
const { users, fetchUsersIfNotPresent } = useUsersStore(useShallow(state => ({
|
|
users: state.users,
|
|
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent
|
|
})))
|
|
|
|
const channelUsers = React.useMemo(() => userIds.map(userId => users[userId]).filter(Boolean), [userIds, users])
|
|
|
|
React.useEffect(() => {
|
|
fetchUsersIfNotPresent(userIds)
|
|
}, [userIds])
|
|
|
|
const onClick = () => {
|
|
updateVoiceState(channel.serverId, channel.id)
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Button variant="secondary" size="sm" className="justify-start" onClick={onClick}>
|
|
<div className="flex items-center gap-2 max-w-72">
|
|
<div>
|
|
<Volume2 />
|
|
</div>
|
|
<div className="truncate">
|
|
{channel.name}
|
|
</div>
|
|
</div>
|
|
</Button>
|
|
{channelUsers.length > 0 &&
|
|
<div className="ml-2 border-l-2 flex flex-col gap-1">
|
|
{
|
|
channelUsers
|
|
.map(user => (
|
|
<div key={user.id} className="flex items-center gap-2 max-w-72 pl-4">
|
|
<UserAvatar user={user} className="size-6" />
|
|
{user.displayName || user.username}
|
|
</div>
|
|
))
|
|
}
|
|
</div>}
|
|
</>
|
|
)
|
|
}
|
|
|
|
function ServerText({ channel }: ChannelListItemProps) {
|
|
return (
|
|
<NavLink to={`/app/server/${channel.serverId}/${channel.id}`} discover="none" >
|
|
{({ isActive }) => (
|
|
<Button variant="secondary" size="sm" className={
|
|
cn(
|
|
"justify-start w-full",
|
|
isActive ? "bg-accent hover:bg-accent" : "bg-secondary"
|
|
)
|
|
}>
|
|
<div className="flex items-center gap-2 max-w-72">
|
|
<div>
|
|
<Hash />
|
|
</div>
|
|
<div className="truncate">
|
|
{channel.name}
|
|
</div>
|
|
</div>
|
|
</Button>
|
|
)
|
|
}
|
|
</NavLink>
|
|
)
|
|
}
|
|
|
|
export default function ServerChannelListItem({ channel }: ChannelListItemProps) {
|
|
switch (channel.type) {
|
|
case ChannelType.SERVER_CATEGORY:
|
|
return <ServerCategory channel={channel} />
|
|
case ChannelType.SERVER_VOICE:
|
|
return <ServerVoice channel={channel} />
|
|
case ChannelType.SERVER_TEXT:
|
|
return <ServerText channel={channel} />
|
|
default:
|
|
return null
|
|
}
|
|
}
|
|
|
|
// file: ./app/components/custom-ui/create-server-button.tsx
|
|
import { CirclePlus } from "lucide-react";
|
|
|
|
|
|
import { Button } from "~/components/ui/button";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
|
|
export function CreateServerButton() {
|
|
const onOpen = useModalStore(state => state.onOpen)
|
|
|
|
return (
|
|
<Button variant="outline" size="none" onClick={() => onOpen(ModalType.CREATE_SERVER)}>
|
|
<CirclePlus className="size-8 m-2" />
|
|
</Button>
|
|
)
|
|
}
|
|
// file: ./app/components/custom-ui/home-button.tsx
|
|
import { NavLink } from "react-router";
|
|
import Discord from "../icons/Discord";
|
|
import { Button } from "../ui/button";
|
|
|
|
export function HomeButton() {
|
|
return (
|
|
<NavLink to={`/app/@me`}>
|
|
{
|
|
({ isActive }) => (
|
|
<Button variant="outline" size="none" asChild className={
|
|
isActive ? "bg-accent" : ""
|
|
}>
|
|
<div>
|
|
<Discord className="size-8 m-2" />
|
|
</div>
|
|
</Button>
|
|
)
|
|
}
|
|
</NavLink>
|
|
)
|
|
}
|
|
// file: ./app/components/custom-ui/online-status.tsx
|
|
import { Circle, CircleMinus, Moon } from "lucide-react";
|
|
|
|
export function OnlineStatus({
|
|
status,
|
|
...props
|
|
}: React.ComponentProps<"div"> & {
|
|
status: "online" | "dnd" | "idle" | "offline";
|
|
}) {
|
|
return (
|
|
<div className="relative">
|
|
<div {...props}></div>
|
|
<div className="absolute bottom-0 right-0 bg-background rounded-full p-0.5 size-1/2">
|
|
{status === "online" && <Circle className="size-full stroke-emerald-400 fill-emerald-400" />}
|
|
{status === "dnd" && <CircleMinus className="size-full stroke-red-400 stroke-3" />}
|
|
{status === "idle" && <Moon className="size-full stroke-amber-400 fill-amber-400" />}
|
|
{status === "offline" && <Circle className="size-full stroke-gray-400 stroke-3" />}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
// file: ./app/components/custom-ui/password-input.tsx
|
|
import { EyeIcon, EyeOffIcon } from "lucide-react"
|
|
import React from "react"
|
|
import { Button } from "../ui/button"
|
|
import { Input } from "../ui/input"
|
|
|
|
export function PasswordInput(props: React.ComponentProps<"input">) {
|
|
const [showPassword, setShowPassword] = React.useState(false)
|
|
const disabled = props.value === '' || props.value === undefined || props.disabled
|
|
|
|
return (
|
|
<div className="relative">
|
|
<Input type={showPassword ? "text" : "password"} {...props} />
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
|
onClick={() => setShowPassword((prev) => !prev)}
|
|
disabled={disabled}
|
|
>
|
|
{showPassword && !disabled ? (
|
|
<EyeIcon className="h-4 w-4" aria-hidden="true" />
|
|
) : (
|
|
<EyeOffIcon className="h-4 w-4" aria-hidden="true" />
|
|
)}
|
|
<span className="sr-only">{showPassword ? 'Hide password' : 'Show password'}</span>
|
|
</Button>
|
|
<style>
|
|
{`
|
|
.hide-password-toggle::-ms-reveal,
|
|
.hide-password-toggle::-ms-clear {
|
|
visibility: hidden;
|
|
pointer-events: none;
|
|
display: none;
|
|
}
|
|
`}
|
|
</style>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// file: ./app/components/custom-ui/private-channel-list-item.tsx
|
|
import { Check } from "lucide-react"
|
|
import { NavLink } from "react-router"
|
|
import type { RecipientChannel } from "~/lib/api/types"
|
|
import { cn } from "~/lib/utils"
|
|
import { useUsersStore } from "~/stores/users-store"
|
|
import { Badge } from "../ui/badge"
|
|
import { Button } from "../ui/button"
|
|
import UserAvatar from "../user-avatar"
|
|
import { OnlineStatus } from "./online-status"
|
|
|
|
interface PrivateChannelListItemProps {
|
|
channel: RecipientChannel
|
|
}
|
|
|
|
export default function PrivateChannelListItem({ channel }: PrivateChannelListItemProps) {
|
|
const currentUserId = useUsersStore(state => state.currentUserId)
|
|
const recipients = channel.recipients.filter(recipient => recipient.id !== currentUserId);
|
|
const renderSystemBadge = recipients.some(recipient => recipient.system) && recipients.length === 1
|
|
|
|
return (
|
|
<>
|
|
<NavLink to={`/app/@me/channels/${channel.id}`}>
|
|
{
|
|
({ isActive }) => (
|
|
<Button variant="secondary" size="none" asChild className={
|
|
cn(
|
|
isActive ? "bg-accent hover:bg-accent" : "",
|
|
"w-full flex flex-row justify-start"
|
|
)
|
|
}>
|
|
<div className="flex items-center gap-2 max-w-72 p-2">
|
|
<div>
|
|
<OnlineStatus status="online">
|
|
<UserAvatar user={channel.recipients.find(recipient => recipient.id !== currentUserId)} />
|
|
</OnlineStatus>
|
|
</div>
|
|
<div className="truncate">
|
|
{recipients.map(recipient => recipient.displayName || recipient.username).join(", ")}
|
|
</div>
|
|
{renderSystemBadge && <Badge variant="default"> <Check /> System</Badge>}
|
|
</div>
|
|
</Button>
|
|
)
|
|
}
|
|
</NavLink>
|
|
</>
|
|
)
|
|
}
|
|
|
|
// file: ./app/components/custom-ui/server-button.tsx
|
|
import { Avatar, AvatarFallback, AvatarImage } from "@radix-ui/react-avatar"
|
|
import { NavLink } from "react-router"
|
|
import type { Server } from "~/lib/api/types"
|
|
import { getFirstLetters } from "~/lib/utils"
|
|
import { Button } from "../ui/button"
|
|
|
|
export interface ServerButtonProps {
|
|
server: Server
|
|
}
|
|
|
|
export function ServerButton(
|
|
{ server }: ServerButtonProps
|
|
) {
|
|
return (
|
|
<NavLink to={`/app/server/${server.id}`}>
|
|
{
|
|
({ isActive }) => (
|
|
<Button variant="outline" size="none" asChild className={
|
|
isActive ? "bg-accent" : ""
|
|
}>
|
|
<div>
|
|
<Avatar className="size-12 rounded-none flex items-center justify-center">
|
|
<AvatarImage src={server.iconUrl} className="rounded-none" />
|
|
<AvatarFallback>
|
|
<div>
|
|
{getFirstLetters(server.name, 4)}
|
|
</div>
|
|
</AvatarFallback>
|
|
</Avatar>
|
|
</div>
|
|
</Button>
|
|
)
|
|
}
|
|
</NavLink>
|
|
)
|
|
}
|
|
// file: ./app/components/custom-ui/settings-button.tsx
|
|
import { Settings } from "lucide-react";
|
|
import { ModalType, useModalStore } from "~/stores/modal-store";
|
|
import { useTokenStore } from "~/stores/token-store";
|
|
import { Button } from "../ui/button";
|
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "../ui/dropdown-menu";
|
|
|
|
export function SettingsButton() {
|
|
const setToken = useTokenStore(state => state.setToken)
|
|
const onOpen = useModalStore(state => state.onOpen)
|
|
|
|
const onUpdateProfile = () => {
|
|
onOpen(ModalType.UPDATE_PROFILE)
|
|
}
|
|
|
|
const onLogout = () => {
|
|
setToken(undefined)
|
|
window.location.reload()
|
|
}
|
|
|
|
return (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="ghost" size="icon">
|
|
<Settings className="size-5 m-1.5" />
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent>
|
|
<DropdownMenuItem onClick={onUpdateProfile}>
|
|
Update profile
|
|
</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuItem variant="destructive" onClick={onLogout}>
|
|
Logout
|
|
</DropdownMenuItem>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
)
|
|
}
|
|
// file: ./app/components/custom-ui/text-box.tsx
|
|
import React, { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
|
|
import { cn } from '~/lib/utils';
|
|
|
|
export interface TextBoxProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'value'> {
|
|
value: string;
|
|
onChange: (value: string) => void;
|
|
placeholder?: string;
|
|
wrapperClassName?: string;
|
|
inputClassName?: string;
|
|
disabled?: boolean;
|
|
autoFocus?: boolean;
|
|
spellCheck?: boolean;
|
|
}
|
|
|
|
export const TextBox = forwardRef<HTMLDivElement, TextBoxProps>(
|
|
(
|
|
{
|
|
value,
|
|
onChange,
|
|
placeholder,
|
|
wrapperClassName,
|
|
inputClassName,
|
|
disabled = false,
|
|
autoFocus = false,
|
|
spellCheck = true,
|
|
onInput,
|
|
onBlur,
|
|
onFocus,
|
|
...rest
|
|
},
|
|
ref
|
|
) => {
|
|
const localRef = useRef<HTMLDivElement>(null);
|
|
useImperativeHandle(ref, () => localRef.current as HTMLDivElement);
|
|
|
|
// Function to handle DOM updates
|
|
const updateDOM = (newValue: string) => {
|
|
if (localRef.current) {
|
|
// Only update if different to avoid selection issues
|
|
if (localRef.current.textContent !== newValue) {
|
|
localRef.current.textContent = newValue;
|
|
|
|
// Clear any <br> elements if the content is empty
|
|
if (!newValue && localRef.current.innerHTML.includes('<br>')) {
|
|
localRef.current.innerHTML = '';
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
// Update DOM when value prop changes
|
|
useEffect(() => {
|
|
updateDOM(value);
|
|
}, [value]);
|
|
|
|
useEffect(() => {
|
|
if (autoFocus && localRef.current) {
|
|
localRef.current.focus();
|
|
}
|
|
}, [autoFocus]);
|
|
|
|
const handleInput = (event: React.FormEvent<HTMLDivElement>) => {
|
|
const newValue = event.currentTarget.textContent || '';
|
|
|
|
// Handle the case where the content is empty but contains a <br>
|
|
if (!newValue && event.currentTarget.innerHTML.includes('<br>')) {
|
|
event.currentTarget.innerHTML = '';
|
|
}
|
|
|
|
onChange(newValue);
|
|
onInput?.(event);
|
|
};
|
|
|
|
const handlePaste = (event: React.ClipboardEvent<HTMLDivElement>) => {
|
|
event.preventDefault();
|
|
const text = event.clipboardData.getData('text/plain');
|
|
|
|
// Use document.execCommand to maintain undo stack
|
|
document.execCommand('insertText', false, text);
|
|
|
|
// Manually trigger input event
|
|
const inputEvent = new Event('input', { bubbles: true });
|
|
event.currentTarget.dispatchEvent(inputEvent);
|
|
};
|
|
|
|
return (
|
|
<div
|
|
className={cn(
|
|
"max-h-96 w-full overflow-y-auto min-h-6 outline-none p-4 rounded-xl no-scrollbar bg-background border border-input",
|
|
"focus-within:ring-2 focus-within:ring-ring focus-within:border-ring",
|
|
wrapperClassName
|
|
)}
|
|
onClick={() => localRef.current?.focus()}
|
|
>
|
|
<div
|
|
ref={localRef}
|
|
contentEditable={!disabled}
|
|
onInput={handleInput}
|
|
onPaste={handlePaste}
|
|
onBlur={onBlur}
|
|
onFocus={onFocus}
|
|
className={cn(
|
|
"break-words whitespace-pre-wrap outline-none w-full",
|
|
"empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:cursor-text",
|
|
disabled && "cursor-not-allowed opacity-50",
|
|
inputClassName
|
|
)}
|
|
data-placeholder={placeholder}
|
|
role="textbox"
|
|
aria-multiline="true"
|
|
aria-disabled={disabled}
|
|
aria-placeholder={placeholder}
|
|
spellCheck={spellCheck}
|
|
suppressContentEditableWarning
|
|
tabIndex={0}
|
|
{...rest}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
);
|
|
|
|
TextBox.displayName = 'TextBox';
|
|
|
|
export default TextBox;
|
|
// file: ./app/components/custom-ui/user-status.tsx
|
|
import { PhoneMissed, Signal } from "lucide-react";
|
|
import { useServerChannelsStore } from "~/stores/server-channels-store";
|
|
import { useServerListStore } from "~/stores/server-list-store";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
import { useVoiceStateStore } from "~/stores/voice-state-store";
|
|
import { ThemeToggle } from "../theme/theme-toggle";
|
|
import { Button } from "../ui/button";
|
|
import { Separator } from "../ui/separator";
|
|
import UserAvatar from "../user-avatar";
|
|
import { OnlineStatus } from "./online-status";
|
|
import { SettingsButton } from "./settings-button";
|
|
|
|
function VoiceStatus({
|
|
voiceState
|
|
}: { voiceState: { serverId: string; channelId: string } }) {
|
|
// const webrtcState = useWebRTCStore(state => state.status)
|
|
|
|
const leaveVoiceChannel = () => {
|
|
useVoiceStateStore.getState().leaveVoiceChannel()
|
|
}
|
|
|
|
const channel = useServerChannelsStore(state => state.channels[voiceState.serverId]?.[voiceState.channelId])
|
|
const server = useServerListStore(state => state.servers[voiceState.serverId])
|
|
|
|
return (
|
|
<div className="gap-1 flex justify-between items-center ">
|
|
<div className="flex items-center gap-2 text-green-500">
|
|
<Signal className="size-5" />
|
|
<div className="truncate max-w-60 text-sm">
|
|
{channel?.name || "Unknown channel"} / {server?.name}
|
|
</div>
|
|
</div>
|
|
|
|
<Button variant="secondary" size="none" onClick={leaveVoiceChannel}>
|
|
<PhoneMissed className="size-5 m-1.5" />
|
|
</Button>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default function UserStatus() {
|
|
const user = useUsersStore(state => state.getCurrentUser()!)
|
|
const voiceState = useVoiceStateStore(state => state.activeChannel)
|
|
|
|
return (
|
|
<div className="outline-1 outline-none border border-input p-2 h-full rounded-xl flex flex-col gap-2">
|
|
{voiceState && <>
|
|
<VoiceStatus voiceState={voiceState} />
|
|
<Separator />
|
|
</>
|
|
}
|
|
<div className="flex justify-between items-center gap-2">
|
|
<div className="grow flex flex-row gap-2">
|
|
<OnlineStatus status="online">
|
|
<UserAvatar user={user} className="size-10" />
|
|
</OnlineStatus>
|
|
|
|
<div className="flex flex-col text-sm justify-center">
|
|
<div className="truncate max-w-30">
|
|
{user?.displayName || user?.username || "Unknown user"}
|
|
</div>
|
|
<span className="text-muted-foreground text-xs">@{user?.username}</span>
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<div className="flex flex-row-reverse gap-2 items-center">
|
|
<SettingsButton />
|
|
<ThemeToggle />
|
|
{/* <Button variant="secondary" size="none">
|
|
<Headphones className="size-5 m-1.5" />
|
|
</Button> */}
|
|
{/* <Button variant="secondary" size="none">
|
|
<Mic className="size-5 m-1.5" />
|
|
</Button> */}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
// file: ./app/components/visible-trigger.tsx
|
|
import { useEffect, useRef } from 'react';
|
|
|
|
interface VisibleTriggerProps {
|
|
onVisible: () => void | Promise<void>;
|
|
options?: IntersectionObserverInit;
|
|
triggerOnce?: boolean;
|
|
children?: React.ReactNode;
|
|
className?: string;
|
|
style?: React.CSSProperties;
|
|
}
|
|
|
|
/**
|
|
* A component that calls a function when it becomes visible in the viewport
|
|
* or a specified scrollable container.
|
|
*/
|
|
export default function VisibleTrigger({
|
|
onVisible, // Function to call when the element becomes visible
|
|
options = {}, // Optional: IntersectionObserver options (root, rootMargin, threshold)
|
|
triggerOnce = true, // Optional: If true, trigger only the first time it becomes visible
|
|
children,
|
|
style,
|
|
...props
|
|
}: VisibleTriggerProps & React.ComponentProps<'div'>) {
|
|
const elementRef = useRef(null); // Ref to attach to the DOM element we want to observe
|
|
|
|
useEffect(() => {
|
|
const element = elementRef.current;
|
|
|
|
// Only proceed if we have the DOM element and the function to call
|
|
if (!element) {
|
|
return;
|
|
}
|
|
|
|
// Default IntersectionObserver options
|
|
const defaultOptions = {
|
|
root: null, // default is the viewport
|
|
rootMargin: '0px', // No margin by default
|
|
threshold: 0, // Trigger as soon as any part of the element is visible
|
|
};
|
|
|
|
// Merge provided options with defaults
|
|
const observerOptions = { ...defaultOptions, ...options };
|
|
|
|
// Create the Intersection Observer instance
|
|
const observer = new IntersectionObserver(
|
|
(entries) => {
|
|
const entry = entries[0]; // Assuming only one target element
|
|
|
|
// If the element is intersecting (visible)...
|
|
if (entry.isIntersecting) {
|
|
// console.log('VisibleTrigger: Element is intersecting.', entry);
|
|
|
|
// Call the provided function
|
|
onVisible();
|
|
|
|
// If triggerOnce is true, stop observing this element immediately
|
|
if (triggerOnce) {
|
|
// console.log('VisibleTrigger: Triggered once, disconnecting observer.');
|
|
observer.disconnect(); // Disconnect stops all observations by this instance
|
|
}
|
|
} else {
|
|
// console.log('VisibleTrigger: Element is NOT intersecting.', entry);
|
|
}
|
|
},
|
|
observerOptions // Pass the options to the observer
|
|
);
|
|
|
|
// Start observing the element
|
|
// console.log('VisibleTrigger: Starting observation.', element);
|
|
observer.observe(element);
|
|
|
|
// Cleanup function: Disconnect the observer when the component unmounts
|
|
// or when the effect dependencies change.
|
|
return () => {
|
|
// console.log('VisibleTrigger: Cleaning up observer.');
|
|
if (observer) {
|
|
// Calling disconnect multiple times is safe.
|
|
observer.disconnect();
|
|
}
|
|
};
|
|
|
|
// Effect dependencies:
|
|
// - elementRef: Need the DOM element reference.
|
|
// - onVisible: If the function prop changes, we need a new observer with the new function.
|
|
// - options: If observer options change, we need a new observer.
|
|
// - triggerOnce: If triggerOnce changes, the logic inside the observer callback changes,
|
|
// so we need a new observer instance.
|
|
}, [elementRef, onVisible, options, triggerOnce]);
|
|
|
|
// Render a div that we will attach the ref to.
|
|
// Ensure it has some minimal dimension if no children are provided,
|
|
// so the observer can detect its presence.
|
|
return (
|
|
<div
|
|
ref={elementRef}
|
|
style={{ minHeight: children ? 'auto' : '1px', ...style }}
|
|
{...props}
|
|
>
|
|
{children} {/* Render any children passed to the component */}
|
|
</div>
|
|
);
|
|
};
|
|
// file: ./app/components/chat-message.tsx
|
|
import { Clock } from "lucide-react"
|
|
import React from "react"
|
|
import { useShallow } from "zustand/react/shallow"
|
|
import type { Message } from "~/lib/api/types"
|
|
import { useUsersStore } from "~/stores/users-store"
|
|
import UserAvatar from "./user-avatar"
|
|
|
|
interface ChatMessageProps {
|
|
message: Message
|
|
}
|
|
|
|
export default function ChatMessage(
|
|
{ message }: ChatMessageProps
|
|
) {
|
|
const { user, fetchUsersIfNotPresent } = useUsersStore(useShallow(state => ({
|
|
user: state.users[message.authorId],
|
|
fetchUsersIfNotPresent: state.fetchUsersIfNotPresent
|
|
})))
|
|
|
|
React.useEffect(() => {
|
|
fetchUsersIfNotPresent([message.authorId])
|
|
}, [])
|
|
|
|
const formatMessageDate = (date: Date) => {
|
|
const now = new Date()
|
|
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
|
const yesterday = new Date(today)
|
|
yesterday.setDate(yesterday.getDate() - 1)
|
|
|
|
const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
|
|
|
|
// Get localized time string
|
|
const timeString = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', hour12: false })
|
|
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)
|
|
|
|
if (messageDate.getTime() === today.getTime()) {
|
|
// Use Intl.RelativeTimeFormat for localized "Today"
|
|
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
|
|
return `${(capitalize(rtf.format(0, 'day')))}, ${timeString}`
|
|
} else if (messageDate.getTime() === yesterday.getTime()) {
|
|
// Use Intl.RelativeTimeFormat for localized "Yesterday"
|
|
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
|
|
return `${capitalize(rtf.format(-1, 'day'))}, ${timeString}`
|
|
} else {
|
|
return date.toLocaleDateString(undefined, {
|
|
month: 'short',
|
|
day: 'numeric',
|
|
hour: '2-digit',
|
|
minute: '2-digit',
|
|
hour12: false
|
|
})
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="grid gap-x-2" style={{ gridTemplateColumns: "auto 1fr", gridTemplateRows: "auto 1fr" }}>
|
|
<div className="row-start-1 col-start-1 row-span-2 col-span-1">
|
|
<UserAvatar user={user} />
|
|
</div>
|
|
<div className="row-start-1 col-start-2 row-span-1 col-span-1 flex items-center gap-2">
|
|
<span className="font-medium text-sm">
|
|
{user?.displayName || user?.username}
|
|
</span>
|
|
<div className="flex items-center gap-0.5 text-xs text-muted-foreground whitespace-nowrap">
|
|
<Clock className="size-3" />
|
|
<span>
|
|
{formatMessageDate(message.createdAt)}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
<div className="row-start-2 col-start-2 row-span-1 col-span-1">
|
|
<div className="wrap-break-word contain-inline-size">
|
|
{message.content}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
// file: ./app/components/user-avatar.tsx
|
|
import type { PartialUser } from "~/lib/api/types"
|
|
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"
|
|
|
|
interface UserAvatarProps {
|
|
user: PartialUser | undefined
|
|
}
|
|
|
|
export default function UserAvatar(
|
|
{ user, ...props }: UserAvatarProps & React.ComponentProps<typeof Avatar>
|
|
) {
|
|
return (
|
|
<Avatar {...props}>
|
|
<AvatarImage src={user?.avatarUrl} />
|
|
<AvatarFallback className="text-muted-foreground">
|
|
{user?.username?.[0]}
|
|
</AvatarFallback>
|
|
</Avatar>
|
|
)
|
|
}
|
|
// file: ./app/components/channel-area.tsx
|
|
import { useInfiniteQuery, type QueryFunctionContext } from "@tanstack/react-query"
|
|
import { Send } from "lucide-react"
|
|
import React from "react"
|
|
import type { Channel, MessageId } from "~/lib/api/types"
|
|
import ChatMessage from "./chat-message"
|
|
import TextBox from "./custom-ui/text-box"
|
|
import { Button } from "./ui/button"
|
|
import VisibleTrigger from "./visible-trigger"
|
|
|
|
interface ChannelAreaProps {
|
|
channel: Channel
|
|
}
|
|
|
|
export default function ChannelArea(
|
|
{ channel }: ChannelAreaProps
|
|
) {
|
|
const [text, setText] = React.useState("")
|
|
const channelId = channel.id
|
|
|
|
const fetchMessages = async ({ pageParam }: QueryFunctionContext) => {
|
|
return await import("~/lib/api/client/channel").then(m => m.default.paginatedMessages(channelId, 50, pageParam as MessageId | undefined))
|
|
}
|
|
|
|
const sendMessage = async () => {
|
|
const content = text.trim()
|
|
if (!content)
|
|
return
|
|
|
|
await import("~/lib/api/client/channel").then(m => m.default.sendMessage(channelId, text))
|
|
setText("")
|
|
}
|
|
|
|
React.useEffect(() => {
|
|
setText("")
|
|
}, [channelId])
|
|
|
|
const {
|
|
data,
|
|
error,
|
|
fetchNextPage,
|
|
hasNextPage,
|
|
isFetching,
|
|
isFetchingNextPage,
|
|
isPending,
|
|
status,
|
|
} = useInfiniteQuery({
|
|
queryKey: ["messages", channelId],
|
|
initialPageParam: undefined,
|
|
queryFn: fetchMessages,
|
|
getNextPageParam: (lastPage) => lastPage.length < 50 ? undefined : lastPage[lastPage.length - 1]?.id,
|
|
refetchOnMount: false,
|
|
refetchInterval: false,
|
|
})
|
|
|
|
const fetchNextPageVisible = () => {
|
|
if (!isFetchingNextPage && hasNextPage)
|
|
fetchNextPage()
|
|
}
|
|
|
|
let messageArea = null
|
|
|
|
if (isPending) {
|
|
messageArea = <div className="flex items-center justify-center size-full">
|
|
<span>Loading...</span>
|
|
</div>
|
|
} else {
|
|
messageArea = <>
|
|
<div className="flex-1" />
|
|
<div className="flex flex-col-reverse overflow-auto gap-2">
|
|
{
|
|
status === "success" && data.pages.map((page, i) => (
|
|
page.map((message) => (
|
|
<div key={message.id} className="w-full">
|
|
<ChatMessage message={message} />
|
|
</div>
|
|
))
|
|
)
|
|
)
|
|
}
|
|
<VisibleTrigger triggerOnce={false} onVisible={fetchNextPageVisible} />
|
|
</div>
|
|
</>
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<div className="flex flex-col size-full">
|
|
<div className="w-full min-h-12 border-b-2 flex items-center justify-center">
|
|
{channel?.name}
|
|
</div>
|
|
<div className="flex-1 overflow-y-auto flex flex-col pl-2 pr-0.5">
|
|
{messageArea}
|
|
</div>
|
|
<div className="w-full max-w-full max-h-1/2">
|
|
<div className="w-full max-w-full px-2 pb-2 flex items-center gap-2">
|
|
<TextBox value={text}
|
|
wrapperClassName="contain-inline-size"
|
|
onChange={(m) => {
|
|
setText(m)
|
|
}}
|
|
placeholder="Type your message here..."
|
|
aria-label="Message input" />
|
|
<Button size="icon" onClick={sendMessage}>
|
|
<Send />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</>
|
|
);
|
|
}
|
|
// file: ./app/stores/channels-voice-state.tsx
|
|
import { create } from "zustand";
|
|
import { immer } from "zustand/middleware/immer";
|
|
import type { ChannelId, UserId } from "~/lib/api/types";
|
|
|
|
interface UserVoiceState {
|
|
deaf: boolean;
|
|
muted: boolean;
|
|
}
|
|
|
|
interface ChannelVoiceState {
|
|
users: Record<UserId, UserVoiceState>;
|
|
}
|
|
|
|
interface ChannelsVoiceState {
|
|
channels: Record<ChannelId, ChannelVoiceState>;
|
|
addUser: (channelId: ChannelId, userId: UserId, userVoiceState: UserVoiceState) => void;
|
|
removeUser: (channelId: ChannelId, userId: UserId) => void;
|
|
removeChannel: (channelId: ChannelId) => void;
|
|
}
|
|
|
|
export const useChannelsVoiceStateStore = create<ChannelsVoiceState>()(
|
|
immer(
|
|
(set, get) => ({
|
|
channels: {},
|
|
addUser: (channelId, userId, userVoiceState) => set((state) => {
|
|
if (!state.channels[channelId]) {
|
|
state.channels[channelId] = {
|
|
users: {}
|
|
}
|
|
}
|
|
|
|
state.channels[channelId].users[userId] = userVoiceState;
|
|
}),
|
|
removeUser: (channelId, userId) => set((state) => {
|
|
if (state.channels[channelId]) {
|
|
delete state.channels[channelId].users[userId];
|
|
}
|
|
}),
|
|
removeChannel: (channelId) => set((state) => {
|
|
delete state.channels[channelId];
|
|
})
|
|
})
|
|
)
|
|
)
|
|
|
|
// file: ./app/stores/users-store.tsx
|
|
import { useQuery } from "@tanstack/react-query"
|
|
import { create as batshitCreate, keyResolver } from "@yornaath/batshit"
|
|
import { create } from "zustand"
|
|
import { immer } from "zustand/middleware/immer"
|
|
import { getUser } from "~/lib/api/client/user"
|
|
import type { FullUser, PartialUser, UserId } from "~/lib/api/types"
|
|
|
|
type UsersStore = {
|
|
users: Record<UserId, PartialUser>
|
|
currentUserId: UserId | undefined
|
|
fetchUsersIfNotPresent: (userIds: UserId[]) => Promise<void>
|
|
addUser: (user: PartialUser) => void
|
|
removeUser: (userId: UserId) => void
|
|
setCurrentUserId: (userId: UserId) => void
|
|
getCurrentUser: () => FullUser | undefined
|
|
}
|
|
|
|
const usersFetcher = batshitCreate({
|
|
fetcher: async (userIds: UserId[]) => {
|
|
let users = []
|
|
|
|
for (const userId of userIds) {
|
|
users.push(getUser(userId))
|
|
}
|
|
|
|
return await Promise.all(users)
|
|
},
|
|
resolver: keyResolver("id")
|
|
})
|
|
|
|
export const useUserQuery = (userId: UserId) => useQuery(
|
|
{
|
|
queryKey: ["users", userId],
|
|
queryFn: async () => {
|
|
const user = await getUser(userId)
|
|
return user
|
|
},
|
|
select: (data) => {
|
|
useUsersStore.getState().addUser(data)
|
|
return data
|
|
}
|
|
}
|
|
)
|
|
|
|
export const useUsersStore = create<UsersStore>()(
|
|
immer(
|
|
(set, get) => ({
|
|
users: {},
|
|
currentUserId: undefined,
|
|
fetchUsersIfNotPresent: async (userIds) => {
|
|
let userPromises: Promise<PartialUser>[] = []
|
|
for (const userId of userIds) {
|
|
const user = get().users[userId]
|
|
if (!user) {
|
|
userPromises.push(usersFetcher.fetch(userId))
|
|
}
|
|
}
|
|
|
|
const users = await Promise.all(userPromises)
|
|
const activeUsers = users.filter(Boolean)
|
|
|
|
set((state) => {
|
|
for (const user of activeUsers) {
|
|
if (user?.id)
|
|
state.users[user.id] = user
|
|
}
|
|
|
|
})
|
|
},
|
|
addUser: (user) => set((state) => {
|
|
if (user.id !== get().currentUserId)
|
|
state.users[user.id] = user
|
|
else {
|
|
const currentUser = get().users[user.id]
|
|
if (currentUser)
|
|
state.users[user.id] = { ...currentUser, ...user }
|
|
else
|
|
state.users[user.id] = user
|
|
}
|
|
}),
|
|
removeUser: (userId) => set((state) => {
|
|
delete state.users[userId]
|
|
}),
|
|
|
|
setCurrentUserId: (userId) => set((state) => {
|
|
state.currentUserId = userId
|
|
}),
|
|
|
|
getCurrentUser: () => !!get().currentUserId ? get().users[get().currentUserId!] as FullUser : undefined
|
|
}),
|
|
)
|
|
) |