web: added the base for the web project

This commit is contained in:
Carl-Gerhard Lindesvärd
2023-10-26 20:53:11 +02:00
parent 15e29edaa7
commit 8a87fff689
107 changed files with 3607 additions and 512 deletions

View File

@@ -0,0 +1,8 @@
import { type HtmlProps } from "@/types";
import { cn } from "@/utils/cn";
export function ButtonContainer({className,...props}: HtmlProps<HTMLDivElement>) {
return (
<div className={cn("flex justify-between mt-6", className)} {...props} />
);
}

View File

@@ -0,0 +1,9 @@
import { type HtmlProps } from "@/types";
export function Card({children}: HtmlProps<HTMLDivElement>) {
return (
<div className="border border-border rounded">
{children}
</div>
)
}

View File

@@ -3,6 +3,6 @@ import { cn } from "@/utils/cn";
export function Container({className,...props}: HtmlProps<HTMLDivElement>) {
return (
<div className={cn("mx-auto w-full max-w-4xl", className)} {...props} />
<div className={cn("mx-auto w-full max-w-4xl px-4", className)} {...props} />
);
}

View File

@@ -0,0 +1,50 @@
import { cn } from "@/utils/cn";
type ContentHeaderProps = {
title: string;
text: string;
children?: React.ReactNode;
};
export function ContentHeader({ title, text, children }: ContentHeaderProps) {
return (
<div className="flex items-center justify-between py-6 first:pt-0">
<div>
<h2 className="h2">{title}</h2>
<p className="text-sm text-muted-foreground">{text}</p>
</div>
<div>{children}</div>
</div>
);
}
type ContentSectionProps = {
title: string;
text: string;
children: React.ReactNode;
asCol?: boolean;
};
export function ContentSection({
title,
text,
children,
asCol,
}: ContentSectionProps) {
return (
<div
className={cn(
"first:pt-0] flex py-6",
asCol ? "col flex" : "justify-between",
)}
>
{title && (
<div className="max-w-[50%]">
<h4 className="h4">{title}</h4>
<p className="text-sm text-muted-foreground">{text}</p>
</div>
)}
<div>{children}</div>
</div>
);
}

View File

@@ -0,0 +1,66 @@
import { type ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table"
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
}
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
})
return (
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
)
}

View File

@@ -0,0 +1,49 @@
import { cloneElement } from "react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "./ui/dropdown-menu";
type DropdownProps<Value> = {
children: React.ReactNode;
label?: string;
items: Array<{
label: string;
value: Value;
}>;
onChange?: (value: Value) => void;
};
export function Dropdown<Value extends string>({ children, label, items, onChange }: DropdownProps<Value>) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="start">
{label && (
<>
<DropdownMenuLabel>{label}</DropdownMenuLabel>
<DropdownMenuSeparator />
</>
)}
<DropdownMenuGroup>
{items.map((item) => (
<DropdownMenuItem
className="cursor-pointer"
key={item.value}
onClick={() => {
onChange?.(item.value);
}}
>
{item.label}
</DropdownMenuItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -1,10 +0,0 @@
import Link from "next/link";
export function Navbar() {
return (
<div className="flex gap-4 text-sm uppercase">
<Link href="/">Dashboards</Link>
<Link href="/reports">Reports</Link>
</div>
);
}

View File

@@ -0,0 +1,11 @@
import { type HtmlProps } from "@/types";
type PageTitleProps = HtmlProps<HTMLDivElement>;
export function PageTitle({ children }: PageTitleProps) {
return (
<div className="my-8 flex justify-between border-b border-border py-4">
<h1 className="h1">{children}</h1>
</div>
);
}

View File

@@ -0,0 +1,13 @@
import { Light as SyntaxHighlighter } from "react-syntax-highlighter";
import ts from "react-syntax-highlighter/dist/cjs/languages/hljs/typescript";
import docco from "react-syntax-highlighter/dist/cjs/styles/hljs/docco";
SyntaxHighlighter.registerLanguage("typescript", ts);
type SyntaxProps = {
code: string;
};
export default function Syntax({ code }: SyntaxProps) {
return <SyntaxHighlighter style={docco}>{code}</SyntaxHighlighter>;
}

View File

@@ -1,34 +0,0 @@
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { User } from "lucide-react";
export function UserDropdown() {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button>
<Avatar>
<AvatarFallback>CL</AvatarFallback>
</Avatar>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuGroup>
<DropdownMenuItem>
<User className="mr-2 h-4 w-4" />
Profile
</DropdownMenuItem>
<DropdownMenuItem>
<User className="mr-2 h-4 w-4" />
Organization
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-red-600">
<User className="mr-2 h-4 w-4" />
Logout
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
)
}

View File

@@ -0,0 +1,21 @@
import { type HtmlProps } from "@/types";
type WithSidebarProps = HtmlProps<HTMLDivElement>
export function WithSidebar({children}: WithSidebarProps) {
return (
<div className="grid grid-cols-[200px_minmax(0,1fr)] gap-8">
{children}
</div>
)
}
type SidebarProps = HtmlProps<HTMLDivElement>
export function Sidebar({children}: SidebarProps) {
return (
<div className="flex flex-col gap-1">
{children}
</div>
)
}

View File

@@ -0,0 +1,69 @@
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { Button } from "../ui/button";
import { MoreHorizontal } from "lucide-react";
import { pushModal, showConfirm } from "@/modals";
import { type IClientWithProject } from "@/types";
import { clipboard } from "@/utils/clipboard";
import { api } from "@/utils/api";
import { useRefetchActive } from "@/hooks/useRefetchActive";
import { toast } from "../ui/use-toast";
export function ClientActions({ id }: IClientWithProject) {
const refetch = useRefetchActive()
const deletion = api.client.remove.useMutation({
onSuccess() {
toast({
title: 'Success',
description: 'Client revoked, incoming requests will be rejected.',
})
refetch()
}
})
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem onClick={() => clipboard(id)}>
Copy client ID
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
pushModal("EditClient", { id });
}}
>
Edit
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive"
onClick={() => {
showConfirm({
title: 'Revoke client',
text: 'Are you sure you want to revoke this client? This action cannot be undone.',
onConfirm() {
deletion.mutate({
id,
})
}
})
}}
>
Revoke
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,43 @@
import { formatDate } from "@/utils/date";
import { type ColumnDef } from "@tanstack/react-table";
import { type IClientWithProject } from "@/types";
import { ClientActions } from "./ClientActions";
export const columns: ColumnDef<IClientWithProject>[] = [
{
accessorKey: "name",
header: "Name",
cell: ({ row }) => {
return (
<div>
<div>{row.original.name}</div>
<div className="text-sm text-muted-foreground">
{row.original.project.name}
</div>
</div>
);
},
},
{
accessorKey: "id",
header: "Client ID",
},
{
accessorKey: "secret",
header: "Secret",
cell: () => <div className="italic text-muted-foreground">Hidden</div>,
},
{
accessorKey: "createdAt",
header: "Created at",
cell({ row }) {
const date = row.original.createdAt;
return <div>{formatDate(date)}</div>;
},
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => <ClientActions {...row.original} />,
},
];

View File

@@ -0,0 +1,18 @@
import { forwardRef } from "react";
import { Input, type InputProps } from "../ui/input";
import { Label } from "../ui/label";
type InputWithLabelProps = InputProps & {
label: string;
};
export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(({ label, ...props }, ref) => {
return (
<div>
<Label htmlFor={label} className="block mb-2">{label}</Label>
<Input ref={ref} id={label} {...props} />
</div>
);
});
InputWithLabel.displayName = "InputWithLabel";

View File

@@ -1,35 +0,0 @@
import Head from "next/head";
import { UserDropdown } from "../UserDropdown";
import { Navbar } from "../Navbar";
type MainLayoutProps = {
children: React.ReactNode;
className?: string;
}
export function MainLayout({ children, className }: MainLayoutProps) {
return (
<>
<Head>
<title>Create T3 App</title>
<meta name="description" content="Generated by create-t3-app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<nav className="flex h-20 items-center justify-between border-b border-border bg-gradient-to-r from-blue-900 to-purple-600 px-8 text-white">
<div className="flex flex-col [&_*]:leading-tight">
<span className="text-2xl font-extrabold">MIXAN</span>
<span className="text-xs text-gray-500">v0.0.1</span>
</div>
<Navbar />
<div>
<UserDropdown />
</div>
</nav>
<main className={className}>
{children}
</main>
</>
);
}

View File

@@ -0,0 +1,29 @@
import { NavbarUserDropdown } from "../navbar/NavbarUserDropdown";
import { NavbarMenu } from "../navbar/NavbarMenu";
import { Container } from "../Container";
import Link from "next/link";
type MainLayoutProps = {
children: React.ReactNode;
className?: string;
};
export function MainLayout({ children, className }: MainLayoutProps) {
return (
<>
<div className="h-2 w-full bg-gradient-to-r from-blue-900 to-purple-600"></div>
<nav className="border-b border-border">
<Container className="flex h-20 items-center justify-between ">
<Link href="/" className="text-3xl">mixan</Link>
<div className="flex items-center gap-8">
<NavbarMenu />
<div>
<NavbarUserDropdown />
</div>
</div>
</Container>
</nav>
<main className={className}>{children}</main>
</>
);
}

View File

@@ -0,0 +1,52 @@
import { Container } from "../Container";
import { MainLayout } from "./MainLayout";
import { usePathname } from "next/navigation";
import { Sidebar, WithSidebar } from "../WithSidebar";
import Link from "next/link";
import { cn } from "@/utils/cn";
import { PageTitle } from "../PageTitle";
import { useOrganizationParams } from "@/hooks/useOrganizationParams";
type SettingsLayoutProps = {
children: React.ReactNode;
className?: string;
};
export function SettingsLayout({ children, className }: SettingsLayoutProps) {
const params = useOrganizationParams();
const pathname = usePathname();
const links = [
{ href: `/${params.organization}/settings/organization`, label: "Organization" },
{ href: `/${params.organization}/settings/projects`, label: "Projects" },
{ href: `/${params.organization}/settings/clients`, label: "Clients" },
{ href: `/${params.organization}/settings/profile`, label: "Profile" },
];
return (
<MainLayout>
<Container>
<PageTitle>Settings</PageTitle>
<WithSidebar>
<Sidebar>
{links.map(({ href, label }) => (
<Link
key={href}
href={href}
className={cn(
"p-4 py-3 leading-none rounded-lg transition-colors",
pathname.startsWith(href)
? "bg-slate-100"
: "hover:bg-slate-100",
)}
>
{label}
</Link>
))}
</Sidebar>
<div className={cn('flex flex-col', className)}>
{children}
</div>
</WithSidebar>
</Container>
</MainLayout>
);
}

View File

@@ -0,0 +1,36 @@
import { LineChart } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useOrganizationParams } from "@/hooks/useOrganizationParams";
import Link from "next/link";
export function NavbarCreate() {
const params = useOrganizationParams();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm">Create</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem asChild>
<Link href={`/${params.organization}/reports`}>
<LineChart className="mr-2 h-4 w-4" />
<span>Create a report</span>
</Link>
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,13 @@
import { useOrganizationParams } from "@/hooks/useOrganizationParams";
import Link from "next/link";
import { NavbarCreate } from "./NavbarCreate";
export function NavbarMenu() {
const params = useOrganizationParams()
return (
<div className="flex gap-6 items-center">
<Link href={`/${params.organization}`}>Home</Link>
<NavbarCreate />
</div>
);
}

View File

@@ -0,0 +1,67 @@
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useOrganizationParams } from "@/hooks/useOrganizationParams";
import { User } from "lucide-react";
import { signOut } from "next-auth/react";
import Link from "next/link";
export function NavbarUserDropdown() {
const params = useOrganizationParams();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button>
<Avatar>
<AvatarFallback>CL</AvatarFallback>
</Avatar>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuGroup>
<DropdownMenuItem asChild className="cursor-pointer">
<Link href={`/${params.organization}/settings/organization`}>
<User className="mr-2 h-4 w-4" />
Organization
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild className="cursor-pointer">
<Link href={`/${params.organization}/settings/projects`}>
<User className="mr-2 h-4 w-4" />
Projects
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild className="cursor-pointer">
<Link href={`/${params.organization}/settings/clients`}>
<User className="mr-2 h-4 w-4" />
Clients
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild className="cursor-pointer">
<Link href={`/${params.organization}/settings/profile`}>
<User className="mr-2 h-4 w-4" />
Profile
</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-red-600 cursor-pointer"
onClick={() => {
signOut().catch(console.error);
}}
>
<User className="mr-2 h-4 w-4" />
Logout
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,70 @@
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { Button } from "../ui/button";
import { MoreHorizontal } from "lucide-react";
import { pushModal, showConfirm } from "@/modals";
import { type IProject } from "@/types";
import { clipboard } from "@/utils/clipboard";
import { useRefetchActive } from "@/hooks/useRefetchActive";
import { api } from "@/utils/api";
import { toast } from "../ui/use-toast";
export function ProjectActions({ id }: IProject) {
const refetch = useRefetchActive()
const deletion = api.project.remove.useMutation({
onSuccess() {
toast({
title: 'Success',
description: 'Project deleted successfully.',
})
refetch()
}
})
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem onClick={() => clipboard(id)}>
Copy project ID
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
pushModal("EditProject", { id });
}}
>
Edit
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive"
onClick={() => {
showConfirm({
title: 'Delete project',
text: 'This will delete all events for this project. This action cannot be undone.',
onConfirm() {
deletion.mutate({
id,
})
}
})
}}
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,26 @@
import { formatDate } from "@/utils/date";
import { type ColumnDef } from "@tanstack/react-table";
import { type Project as IProject } from "@prisma/client";
import { ProjectActions } from "./ProjectActions";
export type Project = IProject;
export const columns: ColumnDef<Project>[] = [
{
accessorKey: "name",
header: "Name",
},
{
accessorKey: "createdAt",
header: "Created at",
cell({ row }) {
const date = row.original.createdAt;
return <div>{formatDate(date)}</div>;
},
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => <ProjectActions {...row.original} />,
},
];

View File

@@ -13,11 +13,18 @@ export function ReportDateRange() {
<RadioGroup>
<RadioGroupItem
onClick={() => {
dispatch(changeDateRanges(1));
dispatch(changeDateRanges('today'));
}}
>
Today
</RadioGroupItem>
<RadioGroupItem
onClick={() => {
dispatch(changeDateRanges(1));
}}
>
24 hours
</RadioGroupItem>
<RadioGroupItem
onClick={() => {
dispatch(changeDateRanges(7));

View File

@@ -31,7 +31,9 @@ export function ReportLineChart({
}: ReportLineChartProps) {
const [visibleSeries, setVisibleSeries] = useState<string[]>([]);
const chart = api.chartMeta.chart.useQuery(
const hasEmptyFilters = events.some((event) => event.filters.some((filter) => filter.value.length === 0));
const chart = api.chart.chart.useQuery(
{
interval,
chartType,
@@ -42,7 +44,7 @@ export function ReportLineChart({
name,
},
{
enabled: events.length > 0,
enabled: events.length > 0 && !hasEmptyFilters,
},
);
@@ -67,10 +69,11 @@ export function ReportLineChart({
<AutoSizer disableHeight>
{({ width }) => (
<LineChart width={width} height={Math.min(width * 0.5, 400)}>
<YAxis dataKey={"count"}></YAxis>
<YAxis dataKey={"count"} width={30} fontSize={12}></YAxis>
<Tooltip content={<ReportLineChartTooltip />} />
<CartesianGrid strokeDasharray="3 3" />
<XAxis
fontSize={12}
dataKey="date"
tickFormatter={(m: Date) => {
return formatDate(m);

View File

@@ -1,3 +1,4 @@
import { useMappings } from "@/hooks/useMappings";
import { type IToolTipProps } from "@/types";
type ReportLineChartTooltipProps = IToolTipProps<{
@@ -8,13 +9,15 @@ type ReportLineChartTooltipProps = IToolTipProps<{
count: number;
label: string;
};
}>
}>;
export function ReportLineChartTooltip({
active,
payload,
}: ReportLineChartTooltipProps) {
if (!active || !payload) {
const getLabel = useMappings();
if (!active || !payload) {
return null;
}
@@ -22,7 +25,6 @@ export function ReportLineChartTooltip({
return null;
}
const limit = 3;
const sorted = payload.slice(0).sort((a, b) => b.value - a.value);
const visible = sorted.slice(0, limit);
@@ -39,7 +41,7 @@ export function ReportLineChartTooltip({
></div>
<div className="flex flex-col">
<div className="min-w-0 max-w-[200px] overflow-hidden text-ellipsis whitespace-nowrap font-medium">
{item.payload.label}
{getLabel(item.payload.label)}
</div>
<div>{item.payload.count}</div>
</div>

View File

@@ -5,9 +5,11 @@ import { useSelector } from "@/redux";
import { Checkbox } from "@/components/ui/checkbox";
import { getChartColor } from "@/utils/theme";
import { cn } from "@/utils/cn";
import { useMappings } from "@/hooks/useMappings";
type ReportTableProps = {
data: RouterOutputs["chartMeta"]["chart"];
data: RouterOutputs["chart"]["chart"];
visibleSeries: string[];
setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;
};
@@ -19,6 +21,7 @@ export function ReportTable({
}: ReportTableProps) {
const interval = useSelector((state) => state.report.interval);
const formatDate = useFormatDateInterval(interval);
const getLabel = useMappings()
function handleChange(name: string, checked: boolean) {
setVisibleSeries((prev) => {
@@ -34,7 +37,7 @@ export function ReportTable({
const cell = "p-2 last:pr-8 last:w-[8rem]";
const value = "min-w-[6rem] text-right";
const header = "text-sm font-medium";
const total = 'bg-gray-50 text-emerald-600 font-bold border-r border-border'
const total = 'bg-gray-50 text-emerald-600 font-medium border-r border-border'
return (
<div className="flex w-fit max-w-full rounded-md border border-border">
{/* Labels */}
@@ -63,7 +66,7 @@ export function ReportTable({
checked={checked}
/>
<div className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap">
{serie.name}
{getLabel(serie.name)}
</div>
</div>
);

View File

@@ -11,7 +11,7 @@ type InitialState = IChartInput;
// First approach: define the initial state using that type
const initialState: InitialState = {
name: "",
name: "screen_view",
chartType: "linear",
startDate: getDaysOldDate(7),
endDate: new Date(),
@@ -102,7 +102,18 @@ export const reportSlice = createSlice({
state.endDate = action.payload;
},
changeDateRanges: (state, action: PayloadAction<number>) => {
changeDateRanges: (state, action: PayloadAction<number | 'today'>) => {
if(action.payload === 'today') {
state.startDate = new Date();
state.endDate = new Date();
state.startDate.setHours(0,0,0,0)
state.interval = 'hour'
return state
}
state.startDate = getDaysOldDate(action.payload);
state.endDate = new Date();
if (action.payload === 1) {
state.interval = "hour";
} else if (action.payload <= 30) {
@@ -110,8 +121,6 @@ export const reportSlice = createSlice({
} else {
state.interval = "month";
}
state.startDate = getDaysOldDate(action.payload);
state.endDate = new Date();
},
},
});

View File

@@ -34,7 +34,7 @@ export function ReportBreakdownMore({ onClick }: ReportBreakdownMoreProps) {
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuContent align="start" className="w-[200px]">
<DropdownMenuGroup>
<DropdownMenuItem className="text-red-600" onClick={() => onClick('remove')}>
<Trash className="mr-2 h-4 w-4" />

View File

@@ -5,14 +5,15 @@ import { addBreakdown, changeBreakdown, removeBreakdown } from "../reportSlice";
import { type ReportEventMoreProps } from "./ReportEventMore";
import { type IChartBreakdown } from "@/types";
import { ReportBreakdownMore } from "./ReportBreakdownMore";
import { RenderDots } from "@/components/ui/RenderDots";
export function ReportBreakdowns() {
const selectedBreakdowns = useSelector((state) => state.report.breakdowns);
const dispatch = useDispatch();
const propertiesQuery = api.chartMeta.properties.useQuery();
const propertiesQuery = api.chart.properties.useQuery();
const propertiesCombobox = (propertiesQuery.data ?? []).map((item) => ({
value: item,
label: item,
label: item, // <RenderDots truncate>{item}</RenderDots>,
}));
const handleMore = (breakdown: IChartBreakdown) => {

View File

@@ -1,10 +1,10 @@
import { api } from "@/utils/api";
import { type IChartEvent } from "@/types";
import {
CreditCard,
SlidersHorizontal,
Trash,
} from "lucide-react";
type IChartEvent,
type IChartEventFilterValue,
type IChartEventFilter,
} from "@/types";
import { CreditCard, SlidersHorizontal, Trash } from "lucide-react";
import {
CommandDialog,
CommandEmpty,
@@ -18,8 +18,11 @@ import { type Dispatch } from "react";
import { RenderDots } from "@/components/ui/RenderDots";
import { useDispatch } from "@/redux";
import { changeEvent } from "../reportSlice";
import { Combobox } from "@/components/ui/combobox";
import { Button } from "@/components/ui/button";
import { ComboboxMulti } from "@/components/ui/combobox-multi";
import { Dropdown } from "@/components/Dropdown";
import { operators } from "@/utils/constants";
import { useMappings } from "@/hooks/useMappings";
type ReportEventFiltersProps = {
event: IChartEvent;
@@ -33,7 +36,7 @@ export function ReportEventFilters({
setIsCreating,
}: ReportEventFiltersProps) {
const dispatch = useDispatch();
const propertiesQuery = api.chartMeta.properties.useQuery(
const propertiesQuery = api.chart.properties.useQuery(
{
event: event.name,
},
@@ -50,7 +53,7 @@ export function ReportEventFilters({
})}
<CommandDialog open={isCreating} onOpenChange={setIsCreating} modal>
<CommandInput placeholder="Type a command or search..." />
<CommandInput placeholder="Search properties" />
<CommandList>
<CommandEmpty>Such emptyness 🤨</CommandEmpty>
<CommandGroup heading="Properties">
@@ -67,7 +70,8 @@ export function ReportEventFilters({
{
id: (event.filters.length + 1).toString(),
name: item,
value: "",
operator: "is",
value: [],
},
],
}),
@@ -93,8 +97,9 @@ type FilterProps = {
};
function Filter({ filter, event }: FilterProps) {
const getLabel = useMappings()
const dispatch = useDispatch();
const potentialValues = api.chartMeta.values.useQuery({
const potentialValues = api.chart.values.useQuery({
event: event.name,
property: filter.name,
});
@@ -102,7 +107,7 @@ function Filter({ filter, event }: FilterProps) {
const valuesCombobox =
potentialValues.data?.values?.map((item) => ({
value: item,
label: item,
label: getLabel(item),
})) ?? [];
const removeFilter = () => {
@@ -114,7 +119,9 @@ function Filter({ filter, event }: FilterProps) {
);
};
const changeFilter = (value: string) => {
const changeFilterValue = (
value: IChartEventFilterValue | IChartEventFilterValue[],
) => {
dispatch(
changeEvent({
...event,
@@ -122,7 +129,25 @@ function Filter({ filter, event }: FilterProps) {
if (item.id === filter.id) {
return {
...item,
value,
value: Array.isArray(value) ? value : [value],
};
}
return item;
}),
}),
);
};
const changeFilterOperator = (operator: IChartEventFilter["operator"]) => {
dispatch(
changeEvent({
...event,
filters: event.filters.map((item) => {
if (item.id === filter.id) {
return {
...item,
operator,
};
}
@@ -141,21 +166,54 @@ function Filter({ filter, event }: FilterProps) {
<div className="flex h-5 w-5 flex-shrink-0 items-center justify-center rounded bg-emerald-600 text-xs font-medium text-white">
<SlidersHorizontal size={10} />
</div>
<RenderDots className="text-sm flex-1">{filter.name}</RenderDots>
<div className="flex flex-1 text-sm">
<RenderDots truncate>{filter.name}</RenderDots>
</div>
<Button variant="ghost" size="sm" onClick={removeFilter}>
<Trash size={16} />
</Button>
</div>
{/* <ComboboxMulti items={valuesCombobox} selected={[]} setSelected={(fn) => {
return fn(filter.value)
//
}} /> */}
<Combobox
<div className="flex gap-1">
<Dropdown
onChange={changeFilterOperator}
items={Object.entries(operators).map(([key, value]) => ({
value: key as IChartEventFilter["operator"],
label: value,
}))}
label="Segment"
>
<Button variant={"ghost"} className="whitespace-nowrap">
{operators[filter.operator]}
</Button>
</Dropdown>
<ComboboxMulti
placeholder="Select values"
items={valuesCombobox}
selected={filter.value.map((item) => ({
value: item?.toString() ?? "__filter_value_null__",
label: getLabel(item?.toString() ?? "__filter_value_null__"),
}))}
setSelected={(setFn) => {
if(typeof setFn === "function") {
const newValues = setFn(
filter.value.map((item) => ({
value: item?.toString() ?? "__filter_value_null__",
label: getLabel(item?.toString() ?? "__filter_value_null__"),
})),
);
changeFilterValue(newValues.map((item) => item.value));
} else {
changeFilterValue(setFn.map((item) => item.value));
}
}}
/>
</div>
{/* <Combobox
items={valuesCombobox}
value={filter.value}
placeholder="Select value"
onChange={changeFilter}
/>
/> */}
{/* <Input
value={filter.value}
onChange={(e) => {

View File

@@ -6,12 +6,14 @@ import { ReportEventFilters } from "./ReportEventFilters";
import { useState } from "react";
import { ReportEventMore, type ReportEventMoreProps } from "./ReportEventMore";
import { type IChartEvent } from "@/types";
import { Filter, GanttChart, Users } from "lucide-react";
import { Dropdown } from "@/components/Dropdown";
export function ReportEvents() {
const [isCreating, setIsCreating] = useState(false);
const selectedEvents = useSelector((state) => state.report.events);
const dispatch = useDispatch();
const eventsQuery = api.chartMeta.events.useQuery();
const eventsQuery = api.chart.events.useQuery();
const eventsCombobox = (eventsQuery.data ?? []).map((item) => ({
value: item.name,
label: item.name,
@@ -38,9 +40,11 @@ export function ReportEvents() {
<div className="flex flex-col gap-4">
{selectedEvents.map((event) => {
return (
<div key={event.name} className="border rounded-lg">
<div className="flex gap-2 items-center p-2 px-4">
<div className="flex-shrink-0 bg-purple-500 w-5 h-5 rounded text-xs flex items-center justify-center text-white font-medium">{event.id}</div>
<div key={event.name} className="rounded-lg border">
<div className="flex items-center gap-2 p-2">
<div className="flex h-5 w-5 flex-shrink-0 items-center justify-center rounded bg-purple-500 text-xs font-medium text-white">
{event.id}
</div>
<Combobox
value={event.name}
onChange={(value) => {
@@ -57,10 +61,50 @@ export function ReportEvents() {
/>
<ReportEventMore onClick={handleMore(event)} />
</div>
<ReportEventFilters
{...{ isCreating, setIsCreating, event }}
/>
{/* Segment and Filter buttons */}
<div className="flex gap-2 p-2 pt-0 text-sm">
<Dropdown
onChange={(segment) => {
dispatch(
changeEvent({
...event,
segment,
}),
);
}}
items={[
{
value: "event",
label: "All events",
},
{
value: "user",
label: "Unique users",
},
]}
label="Segment"
>
<button className="flex items-center gap-1 rounded-md border border-border p-1 px-2 font-medium leading-none text-xs">
{event.segment === "user" ? (
<><Users size={12} /> Unique users</>
) : (
<><GanttChart size={12} /> All events</>
)}
</button>
</Dropdown>
<button
onClick={() => {
handleMore(event)("createFilter");
}}
className="flex items-center gap-1 rounded-md border border-border p-1 px-2 font-medium leading-none text-xs"
>
<Filter size={12} /> Filter
</button>
</div>
{/* Filters */}
<ReportEventFilters {...{ isCreating, setIsCreating, event }} />
</div>
);
})}
@@ -71,6 +115,7 @@ export function ReportEvents() {
dispatch(
addEvent({
name: value,
segment: "event",
filters: [],
}),
);

View File

@@ -1,21 +1,51 @@
import { cn } from "@/utils/cn";
import { ChevronRight } from "lucide-react";
import { Asterisk, ChevronRight } from "lucide-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";
interface RenderDotsProps extends React.HTMLAttributes<HTMLDivElement> {
children: string;
truncate?: boolean;
}
export function RenderDots({ children, className, ...props }: RenderDotsProps) {
export function RenderDots({
children,
className,
truncate,
...props
}: RenderDotsProps) {
const parts = children.split(".");
const sliceAt = truncate && parts.length > 3 ? 3 : 0;
return (
<div {...props} className={cn('flex gap-1', className)}>
{children.split(".").map((str, index) => {
return (
<div className="flex items-center gap-1" key={str + index}>
{index !== 0 && <ChevronRight className="flex-shrink-0 !w-3 !h-3 top-[0.5px] relative" />}
<span>{str}</span>
</div>
);
})}
</div>
<Tooltip disableHoverableContent={true} open={sliceAt === 0 ? false : undefined}>
<TooltipTrigger>
<div
{...props}
className={cn("flex items-center gap-1", className)}
>
{parts.slice(-sliceAt).map((str, index) => {
return (
<div className="flex items-center gap-1" key={str + index}>
{index !== 0 && (
<ChevronRight className="relative top-[0.9px] !h-3 !w-3 flex-shrink-0" />
)}
{str.includes("[*]") ? (
<>
{str.replace("[*]", "")}
<Asterisk className="relative top-[0.9px] !h-3 !w-3 flex-shrink-0" />
</>
) : str === "*" ? (
<Asterisk className="relative top-[0.9px] !h-3 !w-3 flex-shrink-0" />
) : (
str
)}
</div>
);
})}
</div>
</TooltipTrigger>
<TooltipContent align="start">
<p>{children}</p>
</TooltipContent>
</Tooltip>
);
}

View File

@@ -0,0 +1,139 @@
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/utils/cn"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, children, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View File

@@ -52,5 +52,8 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
}
)
Button.displayName = "Button"
Button.defaultProps = {
type: 'button'
}
export { Button, buttonVariants }

View File

@@ -9,21 +9,22 @@ import {
} from "@/components/ui/command";
import { Command as CommandPrimitive } from "cmdk";
type Framework = Record<"value" | "label", string>;
type Item = Record<"value" | "label", string>;
type ComboboxMultiProps = {
selected: Framework[];
setSelected: React.Dispatch<React.SetStateAction<Framework[]>>;
items: Framework[];
selected: Item[];
setSelected: React.Dispatch<React.SetStateAction<Item[]>>;
items: Item[];
placeholder: string
}
export function ComboboxMulti({ items, selected, setSelected, ...props }: ComboboxMultiProps) {
export function ComboboxMulti({ items, selected, setSelected, placeholder, ...props }: ComboboxMultiProps) {
const inputRef = React.useRef<HTMLInputElement>(null);
const [open, setOpen] = React.useState(false);
const [inputValue, setInputValue] = React.useState("");
const handleUnselect = React.useCallback((framework: Framework) => {
setSelected(prev => prev.filter(s => s.value !== framework.value));
const handleUnselect = React.useCallback((item: Item) => {
setSelected(prev => prev.filter(s => s.value !== item.value));
}, []);
const handleKeyDown = React.useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
@@ -45,30 +46,30 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
}
}, []);
const selectables = items.filter(framework => !selected.includes(framework));
const selectables = items.filter(item => !selected.find(s => s.value === item.value));
return (
<Command onKeyDown={handleKeyDown} className="overflow-visible bg-white">
<div
className="group border border-input px-3 py-2 text-sm ring-offset-background rounded-md focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2"
>
<div className="flex gap-1 flex-wrap">
{selected.map((framework) => {
{selected.map((item) => {
return (
<Badge key={framework.value} variant="secondary">
{framework.label}
<Badge key={item.value} variant="secondary">
{item.label}
<button
className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
onKeyDown={(e) => {
if (e.key === "Enter") {
handleUnselect(framework);
handleUnselect(item);
}
}}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
onClick={() => handleUnselect(framework)}
onClick={() => handleUnselect(item)}
>
<X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
</button>
@@ -82,7 +83,7 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
onValueChange={setInputValue}
onBlur={() => setOpen(false)}
onFocus={() => setOpen(true)}
placeholder="Select frameworks..."
placeholder={placeholder}
className="ml-2 bg-transparent outline-none placeholder:text-muted-foreground flex-1"
/>
</div>
@@ -91,21 +92,21 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
{open && selectables.length > 0 ?
<div className="absolute w-full z-10 top-0 rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in">
<CommandGroup className="h-full overflow-auto">
{selectables.map((framework) => {
{selectables.map((item) => {
return (
<CommandItem
key={framework.value}
key={item.value}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
onSelect={(value) => {
setInputValue("")
setSelected(prev => [...prev, framework])
setSelected(prev => [...prev, item])
}}
className={"cursor-pointer"}
>
{framework.label}
{item.label}
</CommandItem>
);
})}

View File

@@ -24,6 +24,7 @@ type ComboboxProps = {
}>;
value: string;
onChange: (value: string) => void;
children?: React.ReactNode
};
export function Combobox({
@@ -31,6 +32,7 @@ export function Combobox({
items,
value,
onChange,
children
}: ComboboxProps) {
const [open, setOpen] = React.useState(false);
@@ -43,17 +45,17 @@ export function Combobox({
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
{children ?? <Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-full min-w-0 justify-between"
>
{value ? find(value)?.label ?? "No match" : placeholder}
<span className="overflow-hidden text-ellipsis">{value ? find(value)?.label ?? "No match" : placeholder}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</Button>}
</PopoverTrigger>
<PopoverContent className="w-full min-w-0 p-0">
<PopoverContent className="w-full min-w-0 p-0" align="start">
<Command>
<CommandInput placeholder="Search item..." />
<CommandEmpty>Nothing selected</CommandEmpty>
@@ -61,8 +63,9 @@ export function Combobox({
{items.map((item) => (
<CommandItem
key={item.value}
value={item.value}
onSelect={(currentValue) => {
const value = find(currentValue)?.value ?? "";
const value = find(currentValue)?.value ?? currentValue;
onChange(value);
setOpen(false);
}}

View File

@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/utils/cn"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 block mb-2"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@@ -10,7 +10,7 @@ const RadioGroup = React.forwardRef<HTMLDivElement, RadioGroupProps>(
return (
<div
className={cn(
"flex h-10 w-full divide-x rounded-md border border-input bg-background text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
"flex h-10 divide-x rounded-md border border-input bg-background text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
@@ -22,7 +22,7 @@ const RadioGroup = React.forwardRef<HTMLDivElement, RadioGroupProps>(
const RadioGroupItem = React.forwardRef<HTMLButtonElement, RadioGroupItemProps>(({className, ...props}, ref) => {
return (
<button {...props} className={cn('flex-1 hover:bg-slate-100 transition-colors font-medium', className)} type="button" ref={ref} />
<button {...props} className={cn('flex-1 px-3 whitespace-nowrap leading-none hover:bg-slate-100 transition-colors font-medium', className)} type="button" ref={ref} />
)
})

View File

@@ -0,0 +1,114 @@
import * as React from "react"
import { cn } from "@/utils/cn"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn("bg-primary font-medium text-primary-foreground", className)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,127 @@
import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/utils/cn"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}

View File

@@ -0,0 +1,33 @@
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
import { useToast } from "@/components/ui/use-toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

View File

@@ -0,0 +1,28 @@
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/utils/cn"
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md 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",
className
)}
{...props}
/>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@@ -0,0 +1,192 @@
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_VALUE
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }