fix: feature-base-refactoring (#297)

* docs: add AGENTS.md with feature-based architecture conventions

Defines the target src/ structure, feature list, naming conventions
(kebab-case, file type patterns), import direction rules, and
feature boundary guidelines for the planned big-bang refactor.

* docs: add features/channel/ to architecture conventions

Generic channel UI (card, modal, form) goes to features/channel/.
Provider-specific sub-folders: channel/notifications/ and channel/storages/.

* refactor: move event emitter to lib/, project service to db/services/, dedup use-mobile hook

* fix: remove unused auth import in db/services/project.ts

* refactor: migrate wrappers/common to components/common (flat)

* fix: remove dead commented-out code from button-with-loading.tsx

* refactor: merge features/browser into features/theme, flatten upload/updates, migrate statistics

* refactor: migrate wrappers/auth to features/auth

Move all auth components and forms from src/components/wrappers/auth/
into src/features/auth/ with flat kebab-case naming. Handle extra
reset-password-form.tsx and differing reset-password-schema.ts by
copying them as reset-password-page-form.tsx and reset-password-page.schema.ts.

* refactor: remove dead auth files and fix zPassword schema

Delete reset-password-section.tsx and reset-password-page-form.tsx (zero consumers).
Fix reset-password-page.schema.ts to import zPassword from @/lib/zod.

* refactor: migrate wrappers/dashboard/common to features/layout, rename Header.tsx to header.tsx

* fix: decouple layout from theme/updates cross-feature imports

Use slot props (actions, updateNotification) so app/ composes
ModeToggle and UpdateNotification into Header and AppSidebar.
Delete dead side-bar-logo.tsx (zero consumers).

* refactor: merge features/keys into features/agents, flatten sub-dirs, migrate agent wrappers

- Merge src/features/keys/keys.action.ts into src/features/agents/
- Flatten src/features/agents/components/ and hooks/ into feature root
- Migrate all src/components/wrappers/dashboard/agent/ files into src/features/agents/
- Update all import paths across app/ and src/ accordingly
- Fix broken code-snippet import in agent-key-modal.tsx (was pointing to non-existent wrappers path)

* fix: move github-releases to lib/, remove dead code and unused imports

Move GitHub release fetch logic from features/updates/github.ts to
lib/github-releases.ts so both features/updates and features/agents
can import it without cross-feature imports.
Remove commented-out impersonation block from agent-database-card.tsx.
Remove unused imports (CopyButton, Terminal, Key, Info).

* refactor: flatten features/projects/components, migrate project wrappers

Move project.dialog/form out of sub-dir, migrate project-card, project-database-card, and delete-project button/action from wrappers into features/projects/. Update all import paths across src/ and app/. Leave wrappers/dashboard/projects/database/ untouched for Task 10.

* fix: extract DatabaseCard to components/common, remove cross-feature import

DatabaseCard was imported by both features/projects and features/agents,
violating the no-cross-feature-import rule. Extract to components/common/
database-card.tsx so both features import from the shared layer.
Also tighten extendedProps type and remove commented-out maxCount prop.

* refactor: migrate all database/backup/restore/health UI to features/database

Consolidates ~40 files from 5 source locations (features/dashboard/backup,
features/dashboard/restore, wrappers/dashboard/backup, wrappers/dashboard/database,
wrappers/dashboard/health, wrappers/dashboard/projects/database) into the new
flat features/database directory with kebab-case filenames and updated @/ imports.

* fix: remove dead restore-form files and console.log from health-grid

Delete restore-form.tsx (186 lines all commented-out, zero consumers)
and restore-form.schema.ts (only a commented import).
Remove console.log(logs) from getOldestLog helper in health-grid.tsx.

Cross-feature imports (database→storages for dispatchStorage/storeBackupFiles)
are accepted as known architectural coupling — storage dispatch is called from
database server actions at runtime and cannot route through app/ props.

* refactor: migrate wrappers/admin/users to features/users, fix table-colums typo

* fix: fix relative imports, string interpolation, and console.error in users feature

Replace relative imports with @/ aliases in user-actions-cell.tsx and
admin-user-edit-modal.tsx. Fix string interpolation bug in dialog title
(was regular string, now template literal). Remove console.error from
admin-user-change-role-modal.tsx.

* refactor: migrate wrappers/profile to features/profile, fix profile-apperance typo

* fix: remove console.error calls and ts-ignore in profile feature

Remove console.error from profile-account.tsx, 2fa-form.tsx (x2).
Replace @ts-ignore on fileInput.onchange with typed cast in avatar-with-upload.tsx.

* refactor: rename features/organization to features/organizations, migrate all org wrappers

Moves 37 org-related files from features/organization/, features/dashboard/,
hooks/, wrappers/admin/organizations/, wrappers/admin/channels/organization/,
and wrappers/dashboard/organization/ into a flat features/organizations/ feature
directory. Updates all import paths codebase-wide. Fixes @ts-ignore and removes
unused @better-fetch/fetch import in admin-organization-form.

* fix: remove console.error, @ts-ignore, and unused destructures in features/organizations

* refactor: migrate wrappers/organization/migration to features/migration

Move all 5 migration files to src/features/migration/, update internal
imports to @/features/migration/ absolute paths, remove console.log,
and delete src/components/wrappers/dashboard/organization/ entirely.

* refactor: migrate wrappers/admin/settings to features/settings

Move all 14 settings files (email, notification, storage, s3) from
wrappers/dashboard/admin/settings/ into features/settings/, rewriting
imports, replacing @ts-ignore with @ts-expect-error, and renaming error
params to _error where applicable.

* refactor: rename notifications files to kebab convention, migrate notification logs

- Rename dispatch.ts/helpers.ts/types.ts to notifications.*.ts
- Migrate notification logs components from wrappers/dashboard/admin/notifications/logs/ to features/notifications/
- Fix all import paths across codebase and in providers/
- Remove unused useRouter import, replace @ts-ignore with @ts-expect-error
- Delete src/components/wrappers/dashboard/admin/notifications/

* refactor: rename storages dispatch/helpers/types to kebab convention

- Rename dispatch.ts/helpers.ts/types.ts to storages.*.ts
- Fix all import paths across codebase and in providers/
- Fix relative ../types and ../../types imports in all storage providers to absolute @/ paths
- Replace @ts-ignore with @ts-expect-error, remove console.debug/console.error

* refactor: create features/channel with generic UI and notifications/storages provider sub-folders

Consolidates 4 source locations into src/features/channel/:
- components/wrappers/dashboard/admin/channels/ → features/channel/ (11 generic UI files)
- features/notifications/providers/ → features/channel/notifications/ (9 backend + 18 form files)
- features/storages/providers/ → features/channel/storages/ (backend + forms)

The two conflicting google-drive/helpers.ts files (client helpers vs OAuth action)
are kept separate: helpers.ts and google-drive-refresh.action.ts.

Rewrites all imports codebase-wide to point to new locations.
Removes console.log/console.error calls, upgrades @ts-ignore to @ts-expect-error.

* fix: remove console.error from local storage provider

* fix: multi-select.tsx scroll issue

* fix: multi-select.tsx scroll issue
This commit is contained in:
Charles GTE
2026-05-24 17:09:12 +02:00
committed by GitHub
parent 4fadfcfaf2
commit 3fa0f9b76d
330 changed files with 627 additions and 1120 deletions
+18
View File
@@ -0,0 +1,18 @@
"use client";
import React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
type BackButtonProps = React.ComponentProps<typeof Button> & {
children: React.ReactNode;
};
export default function BackButton({ children, ...props }: BackButtonProps) {
const router = useRouter();
return (
<Button onClick={() => router.back()} aria-label={children?.toString()} {...props}>
{children}
</Button>
);
}
+95
View File
@@ -0,0 +1,95 @@
"use client"
import {
Breadcrumb,
BreadcrumbItem, BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import {usePathname} from "next/navigation";
import Link from "next/link";
import {useIsMobile} from "@/hooks/use-mobile";
import {capitalizeFirstLetter, isUUID} from "@/utils/text";
export function useBreadCrumbs() {
const pathname = usePathname();
const route_history = pathname
.split("/")
.filter((x: any) => x && x.length > 0);
const breadcrumb_routes = route_history.reduce(
(acc: { name: string; path: string }[], route) => {
const prev_path = acc[acc.length - 1]?.path ?? "";
acc.push({name: route, path: `${prev_path}/${route}`});
return acc;
},
[],
);
return {breadcrumb_routes};
}
interface BreadCrumbsProps {
}
export function BreadCrumbsWrapper() {
const isMobile = useIsMobile()
return (
<>
{!isMobile ? <BreadCrumbs/> : null}
</>
)
}
const FORBIDDEN_LINKS = ["organization", "dashboard", "database", "admin", "notifications", "storages"];
export function BreadCrumbs({}: BreadCrumbsProps) {
const {breadcrumb_routes} = useBreadCrumbs();
if (breadcrumb_routes.length < 2) return null;
return (
<div className="flex w-full flex-wrap px-3 md:justify-end">
<Breadcrumb>
<BreadcrumbList>
{breadcrumb_routes.map((crumb: any) => {
const label = isUUID(crumb.name) ? "details" : crumb.name;
const isLast = breadcrumb_routes.length - 1 === breadcrumb_routes.indexOf(crumb);
const isForbidden = FORBIDDEN_LINKS.includes(crumb.name.toLowerCase());
return (
<div className="flex items-center gap-2" key={crumb.path}>
<BreadcrumbItem key={crumb.path}>
{isLast ? (
<BreadcrumbPage>{capitalizeFirstLetter(label)}</BreadcrumbPage>
) : (
<> {isForbidden ?
<BreadcrumbLink asChild>
<Link
href={crumb.path}
onClick={(e) => e.preventDefault()}
className="cursor-not-allowed "
>
{capitalizeFirstLetter(label)}
</Link>
</BreadcrumbLink>
:
<BreadcrumbLink asChild>
<Link href={crumb.path}>{capitalizeFirstLetter(label)}</Link>
</BreadcrumbLink>
}
</>
)}
</BreadcrumbItem>
{!isLast && <BreadcrumbSeparator className="hidden md:block"/>}
</div>
);
})}
</BreadcrumbList>
</Breadcrumb>
</div>
);
}
@@ -0,0 +1,198 @@
"use client";
import { Button, ButtonVariantsProps } from "@/components/ui/button";
import { ReactNode, useState } from "react";
import { Loader2 } from "lucide-react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
export type ButtonWithConfirmProps = {
title: string;
description: string;
button?: {
main: {
className?: string;
type?: "button" | "submit" | "reset" | undefined;
text?: string;
icon?: any;
variant?: ButtonVariantsProps["variant"];
size?: ButtonVariantsProps["size"];
disabled?: boolean;
tooltipText?: string;
};
confirm: {
className?: string;
text: string;
icon?: any;
variant?: ButtonVariantsProps["variant"];
size?: ButtonVariantsProps["size"];
onClick?: () => void;
};
cancel: {
className?: string;
text: string;
icon?: any;
variant?: ButtonVariantsProps["variant"];
size?: ButtonVariantsProps["size"];
onClick?: () => void;
};
};
children?: ReactNode;
onConfirm?: (e: React.MouseEvent) => void;
onCancel?: (e: React.MouseEvent) => void;
confirmButtonText?: string;
cancelButtonText?: string;
isPending?: boolean;
};
export const ButtonWithConfirm = (props: ButtonWithConfirmProps) => {
const [isConfirming, setIsConfirming] = useState(false);
const isLegacy = !!props.button;
const isDisabled = isLegacy ? !!props.button?.main.disabled : false;
const handleConfirm = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (isLegacy) {
props.button?.confirm.onClick?.();
} else {
props.onConfirm?.(e);
}
setIsConfirming(false);
};
const handleCancel = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (isLegacy) {
props.button?.cancel.onClick?.();
} else {
props.onCancel?.(e);
}
setIsConfirming(false);
};
const triggerContent = isLegacy ? (
<Button
type={props.button?.main.type}
disabled={isDisabled}
variant={props.button?.main.variant ?? "default"}
size={props.button?.main.size ?? "default"}
className={props.button?.main.className}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
if (!isDisabled) setIsConfirming(true);
}}
>
{props.isPending && <Loader2 className="animate-spin mr-4" size={16} />}
{props.button?.main.icon}
{props.button?.main.text && <span>{props.button.main.text}</span>}
</Button>
) : (
<div
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setIsConfirming(true);
}}
>
{props.children}
</div>
);
const withTooltip =
isLegacy && props.button?.main.tooltipText && isDisabled ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div>{triggerContent}</div>
</TooltipTrigger>
<TooltipContent>
<p>{props.button?.main.tooltipText}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
triggerContent
);
return (
<Popover open={isConfirming} onOpenChange={setIsConfirming}>
<PopoverTrigger asChild>{withTooltip}</PopoverTrigger>
<PopoverContent
className="w-80"
onPointerDownOutside={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
onClick={(e) => e.stopPropagation()}
onMouseMove={(e) => e.stopPropagation()}
onMouseEnter={(e) => e.stopPropagation()}
onMouseLeave={(e) => e.stopPropagation()}
onOpenAutoFocus={(e) => e.preventDefault()}
>
<div className="grid gap-4">
<div className="space-y-2">
<h4 className="font-medium leading-none">{props.title}</h4>
<p className="text-sm text-muted-foreground">{props.description}</p>
</div>
<div className="grid gap-2">
<Button
onClick={handleConfirm}
variant={
isLegacy
? (props.button?.confirm.variant ?? "default")
: "default"
}
size={
isLegacy ? (props.button?.confirm.size ?? "default") : "default"
}
className={cn(
isLegacy ? props.button?.confirm.className : "",
"w-full",
)}
>
{props.isPending && (
<Loader2 className="animate-spin mr-4" size={16} />
)}
{isLegacy && props.button?.confirm.icon}
<span>
{isLegacy
? props.button?.confirm.text
: (props.confirmButtonText ?? "Confirm")}
</span>
</Button>
<Button
variant={
isLegacy
? (props.button?.cancel.variant ?? "outline")
: "outline"
}
onClick={handleCancel}
className={cn(
isLegacy ? props.button?.cancel.className : "",
"w-full",
)}
size={
isLegacy ? (props.button?.cancel.size ?? "default") : "default"
}
>
{isLegacy
? (props.button?.cancel.text ?? "Cancel")
: (props.cancelButtonText ?? "Cancel")}
</Button>
</div>
</div>
</PopoverContent>
</Popover>
);
};
@@ -0,0 +1,56 @@
"use client"
import { ButtonHTMLAttributes, ReactNode } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
export type VariantButton = {
secondary: string;
default: string;
outline: string;
ghost: string;
link: string;
destructive: string;
};
export type SizeButton = {
default: string;
icon: string;
sm: string;
lg: string;
};
export type ButtonWithLoadingProps = {
children?: string | ReactNode;
icon?: ReactNode;
variant?: keyof VariantButton;
className?: string;
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;
isPending?: boolean;
size?: keyof SizeButton;
} & ButtonHTMLAttributes<HTMLButtonElement>;
export const ButtonWithLoading = ({
icon,
children,
variant = "default",
className,
onClick,
isPending,
size = "default",
...rest
}: ButtonWithLoadingProps) => {
return (
<Button
onClick={(e) => onClick?.(e)}
variant={variant}
className={className}
size={size}
{...rest}
>
{isPending && <Loader2 className="mr-2 animate-spin" size={16} />}
{children && children}
<>{icon ? icon : null}</>
</Button>
);
};
@@ -0,0 +1,81 @@
"use client";
import React, { ComponentType, useState } from "react";
import { cn } from "@/lib/utils";
import { PaginationNavigation } from "@/components/common/pagination-navigation";
import { PaginationSize } from "@/components/common/pagination-size";
interface CardsWithPaginationProps<T> {
className?: string;
data: any[];
organizationSlug?: string;
cardItem: ComponentType<{ data: T } & Record<string, any>>;
cardsPerPage?: number;
numberOfColumns?: number;
maxVisiblePages?: number;
pageSizeOptions?: number[];
[key: string]: any;
}
export function CardsWithPagination<T>(props: CardsWithPaginationProps<T>) {
const { className, organizationSlug, data, cardItem, cardsPerPage = 5, numberOfColumns = 1, maxVisiblePages = 3, pageSizeOptions, ...rest } = props;
const CardItem = cardItem;
const [pageSize, setPageSize] = useState(cardsPerPage);
const [currentPage, setCurrentPage] = useState(1);
const totalPages = Math.ceil(data.length / pageSize);
const indexOfLastCard = currentPage * pageSize;
const indexOfFirstCard = indexOfLastCard - pageSize;
const currentCards = data.slice(indexOfFirstCard, indexOfLastCard);
const goToPage = (pageNumber: number) => {
setCurrentPage(pageNumber);
};
const goToPrevPage = () => {
goToPage(Math.max(1, currentPage - 1));
};
const goToNextPage = () => {
goToPage(Math.min(totalPages, currentPage + 1));
};
const handlePageSizeChange = (newSize: number) => {
if (!Number.isFinite(newSize) || newSize < 1) return;
setPageSize(newSize);
setCurrentPage(1);
};
const showSizeSelector = pageSizeOptions && pageSizeOptions.length > 0;
return (
<div className={cn("flex flex-col h-full justify-between", className)}>
<div className={cn(`grid h-max auto-rows-min gap-4 md:grid-cols-${numberOfColumns}`)}>
{currentCards.map((card, key) => (
<CardItem key={key} data={card} organizationSlug={organizationSlug} {...rest} />
))}
</div>
<div className="flex items-center justify-end mt-4 gap-4">
{showSizeSelector && (
<PaginationSize
pageSize={pageSize}
onPageSizeChange={handlePageSizeChange}
pageSizeOptions={pageSizeOptions}
/>
)}
<PaginationNavigation
className="justify-end"
totalPages={totalPages}
currentPage={currentPage}
goToPage={goToPage}
goToPrevPage={goToPrevPage}
goToNextPage={goToNextPage}
maxVisiblePages={maxVisiblePages}
/>
</div>
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
"use client";
import {PropsWithChildren, useState} from "react";
import {Button} from "@/components/ui/button";
import {Check, Copy, Terminal} from "lucide-react";
import {copyToClipboardWithMeta} from "@/components/common/copy-button";
import {cn} from "@/lib/utils";
export type CodeSnippetProps = PropsWithChildren<{
code: string;
title?: string;
className?: string;
}>;
export const CodeSnippet = (props: CodeSnippetProps) => {
const [isCopied, setIsCopied] = useState(false);
const handleCopy = async () => {
await copyToClipboardWithMeta(props.code);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
};
return (
<div className={cn("relative group rounded-md bg-muted/50 border overflow-hidden", props.className)}>
{props.title && (
<div className="flex items-center px-4 py-2 text-xs font-medium text-muted-foreground border-b bg-muted/30">
{props.title}
</div>
)}
<div className="flex items-center p-4">
<pre className="flex-1 overflow-x-auto font-mono text-sm leading-relaxed">
<code className="break-all whitespace-pre-wrap">{props.code}</code>
</pre>
<Button
variant="ghost"
size="icon"
className="ml-2 h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity"
onClick={handleCopy}
>
{isCopied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
<span className="sr-only">Copy code</span>
</Button>
</div>
</div>
);
};
+119
View File
@@ -0,0 +1,119 @@
"use client";
import {useEffect, useState} from "react";
import {Check, ChevronDown} from "lucide-react";
import {cn} from "@/lib/utils";
import {Button} from "@/components/ui/button";
import {Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList} from "@/components/ui/command";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
import {SidebarMenuButton} from "@/components/ui/sidebar";
import {Separator} from "@/components/ui/separator";
export type ComboBoxProps<T = string> = {
values: Array<{ value: T; label: string }>;
defaultValue?: T;
onValueChangeAction?: (value: T) => void;
searchField?: boolean;
sideBar?: boolean;
onAddItemAction?: () => void;
addItemLabel?: string;
};
export function ComboBox<T = string>(props: ComboBoxProps<T>) {
const {
values: choices,
defaultValue,
onValueChangeAction,
searchField = false,
sideBar = false,
onAddItemAction,
addItemLabel = "Add item",
} = props;
const [value, setValue] = useState<T | undefined>(defaultValue);
const [open, setOpen] = useState(false);
useEffect(() => {
setValue(defaultValue);
}, [defaultValue]);
return (
<div>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
{sideBar ? (
<SidebarMenuButton>
<label className="max-w-[170px] truncate">
{value ? choices.find((c) => c.value === value)?.label : "Select choice..."}
</label>
<ChevronDown className="ml-auto"/>
</SidebarMenuButton>
) : (
<Button variant="outline" role="combobox" aria-expanded={open}
className="w-full justify-between">
<label className="max-w-[170px] truncate">
{value ? choices.find((c) => c.value === value)?.label : "Select choice..."}
</label>
<ChevronDown className="opacity-50"/>
</Button>
)}
</PopoverTrigger>
<PopoverContent
className="p-0"
align="start"
sideOffset={4}
style={{width: 'var(--radix-popover-trigger-width)'}}
>
<Command>
{searchField && <CommandInput placeholder="Search choice..." className="h-9"/>}
<CommandList>
<CommandEmpty>No choice found.</CommandEmpty>
<CommandGroup>
{choices.map((choice) => (
<CommandItem
key={String(choice.value)}
value={String(choice.value)}
onSelect={(currentValue) => {
const v = choices.find(c => String(c.value) === currentValue)?.value;
if (v !== undefined) {
setValue(v);
onValueChangeAction?.(v);
setOpen(false);
}
}}
>
<label className="max-w-[170px] truncate">
{choice.label}
</label>
<Check
className={cn("ml-auto", value === choice.value ? "opacity-100" : "opacity-0")}/>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
{onAddItemAction && (
<>
<Separator/>
{sideBar ? (
<SidebarMenuButton onClick={() => {
setOpen(false);
onAddItemAction();
}}>
+ {addItemLabel}
</SidebarMenuButton>
) : (
<Button variant="outline" className="w-full" onClick={onAddItemAction}>
+ {addItemLabel}
</Button>
)}
</>
)}
</PopoverContent>
</Popover>
</div>
);
}
@@ -0,0 +1,46 @@
import {cn} from "@/lib/utils";
export type ConnectionIndicatorProps = {
date?: Date | null;
};
export const ConnectionIndicator = ({date}: ConnectionIndicatorProps) => {
let style = "bg-gray-300";
if (date instanceof Date && !isNaN(date.getTime())) {
const intervalSeconds = (Date.now() - date.getTime()) / 1000;
if (intervalSeconds < 55) {
style = "bg-green-500";
} else if (intervalSeconds <= 60) {
style = "bg-orange-400";
} else {
style = "bg-red-500";
}
}
return (
<div className="relative w-3 h-3">
<span
className={cn(
"absolute -inset-0.25 rounded-full opacity-60 animate-ping",
style
)}
style={{
animationDuration: "2s",
}}
/>
<div
className={cn(
"relative w-3 h-3 rounded-full shadow-sm animate-pulse",
style
)}
style={{
animationDuration: "2s",
}}
/>
</div>
);
};
@@ -0,0 +1,15 @@
"use client";
import { useEffect } from "react";
export function ConsoleSilencer() {
useEffect(() => {
if (process.env.NODE_ENV === "production") {
for (const method of ["log", "debug", "info", "warn", "error"] as const) {
console[method] = () => {};
}
}
}, []);
return null;
}
+39
View File
@@ -0,0 +1,39 @@
"use client";
import { useEffect, useState } from "react";
import { CheckIcon, Copy } from "lucide-react";
import { Button } from "@/components/ui/button";
export async function copyToClipboardWithMeta(value: string) {
navigator.clipboard.writeText(value);
}
export type CopyButtonProps = {
value: string;
className?: string;
};
export const CopyButton = (props: CopyButtonProps) => {
const { value } = props;
const [hasCopied, setHasCopied] = useState(false);
useEffect(() => {
setTimeout(() => {
setHasCopied(false);
}, 2000);
}, [hasCopied]);
return (
<Button
onClick={() => {
copyToClipboardWithMeta(value);
setHasCopied(true);
}}
{...props}
>
<span className="mr-2">Copy</span>
{hasCopied ? <CheckIcon /> : <Copy size="18" />}
</Button>
);
};
+217
View File
@@ -0,0 +1,217 @@
"use client"
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
getPaginationRowModel,
getSortedRowModel,
SortingState,
ColumnFiltersState,
getFilteredRowModel,
} from "@tanstack/react-table";
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "@/components/ui/table";
import {Input} from "@/components/ui/input";
import {ReactNode, useMemo, useState} from "react";
import {TablePagination} from "./table-pagination";
import {Checkbox} from "@/components/ui/checkbox";
import {Button} from "@/components/ui/button";
import {useRouter} from "next/navigation";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
enableFilter?: boolean;
enableSelect?: boolean;
enablePagination?: boolean;
paginationOptions?: {
pageSize: number[];
pageVisible: number;
className?: string;
};
filterOptions?: {
title?: string;
key: string;
};
emptyButton?: {
text: string;
variant: "link" | "default" | "destructive" | "outline" | "secondary" | "ghost" | null | undefined;
path: string;
};
highlightRow?: (row: TData) => boolean;
selectedActions?: (rows: TData[]) => ReactNode;
}
export function DataTable<TData, TValue>({
columns,
data,
enableFilter = false,
enablePagination = true,
enableSelect = true,
paginationOptions = {pageSize: [10, 20, 30, 40, 50, 100], pageVisible: 3},
filterOptions = {key: "id", title: "Filter by ID"},
emptyButton,
highlightRow,
selectedActions,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const [rowSelection, setRowSelection] = useState({});
const finalColumns = useMemo(() => {
const selectColumnExists = columns.some((column) => column.id === "select");
if (enableSelect && data.length > 0 && !selectColumnExists) {
return [
{
id: "select",
header: ({table}: {table: any}) => (
<Checkbox
checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({row}: {row: any}) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
},
...columns,
];
}
return columns;
}, [columns, enableSelect, data.length]);
const table = useReactTable({
data,
columns: finalColumns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
onRowSelectionChange: setRowSelection,
getRowId: (row: any) => row.id || row.uuid,
autoResetPageIndex: false,
autoResetExpanded: false,
enableRowSelection: true,
state: {
sorting,
columnFilters,
rowSelection,
},
});
const router = useRouter();
return (
<div
className="flex flex-col h-full"
>
{enableFilter || selectedActions && (
<div className="flex items-center py-4">
{enableFilter && (
<Input
placeholder={`${filterOptions.title ?? `Filter by ${filterOptions.key}`}`}
value={(table.getColumn(filterOptions.key)?.getFilterValue() as string) ?? ""}
onChange={(event) => table.getColumn(filterOptions.key)?.setFilterValue(event.target.value)}
className="max-w-sm"
/>
)}
{/*{selectedActions && table.getSelectedRowModel().rows.length > 0 && (*/}
{selectedActions && (
selectedActions(table.getSelectedRowModel().rows.map(row => row.original))
)}
</div>
)}
<div className="flex flex-col justify-between h-full">
<div className="rounded-md border w-full">
<Table className="w-full">
<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}
className={highlightRow && highlightRow(row.original) ? "bg-gray-100 pointer-events-none" : ""}
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="p-0">
{emptyButton ? (
<Button
variant={emptyButton.variant}
className="btn btn-primary cursor-pointer w-full rounded-tr-none rounded-tl-none py-12 text-lg font-bold"
onClick={() => {
router.push(emptyButton.path)
}}
>
<span>{emptyButton.text}</span>
</Button>
) : (
<div className="flex items-center justify-center py-12 text-lg font-bold">
<span className="text-lg font-bold">No data available</span>
</div>
)}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-end space-x-2 py-4 mt-6">
{enableSelect && table.getFilteredRowModel().rows.length >= 1 && (
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length} of {table.getFilteredRowModel().rows.length} row(s)
selected.
</div>
)}
{enablePagination && table.getFilteredRowModel().rows.length >= 1 && (
<TablePagination
table={table}
maxVisiblePages={paginationOptions?.pageVisible}
pageSizeOptions={(() => {
const rowCount = table.getFilteredRowModel().rows.length;
const allSizes = paginationOptions.pageSize.sort((a, b) => a - b);
const validSizes = allSizes.filter((size) => size <= rowCount);
const nextSize = allSizes.find((size) => size > rowCount);
if (nextSize) validSizes.push(nextSize);
return validSizes;
})()}
className={paginationOptions.className}
/>
)}
</div>
</div>
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
"use client";
import Link from "next/link";
import Image from "next/image";
import {useState} from "react";
import {Card} from "@/components/ui/card";
import {ConnectionIndicator} from "@/components/common/connection-indicator";
import {formatDateLastContact} from "@/utils/date-formatting";
import {Database} from "@/db/schema/07_database";
import {ChevronRight, Activity, Fingerprint, Copy, Check} from "lucide-react";
export type DatabaseCardProps = {
data: Database;
withDetails?: boolean;
};
export const DatabaseCard = (props: DatabaseCardProps) => {
const {data: database, withDetails = true} = props;
const [isCopied, setIsCopied] = useState(false);
const handleCopy = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
navigator.clipboard.writeText(database.agentDatabaseId);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
};
return (
<Card
className="relative h-full flex flex-col p-4 transition-all border-border/50 bg-card hover:bg-accent/50 hover:border-primary/50 group-hover:shadow-lg overflow-hidden gap-0">
<div className="flex items-start justify-between mb-2">
<div
className="relative w-12 h-12 p-2 bg-background rounded-xl border border-border/50 shadow-sm flex items-center justify-center group-hover:border-primary/30 transition-all duration-300 group-hover:scale-105">
<Image
src={`/images/${database.dbms}.png`}
alt={`${database.dbms} icon`}
width={32}
height={32}
className="object-contain w-full h-full"
/>
</div>
<div className="flex flex-col items-end gap-3">
<div className="scale-100 origin-right">
<ConnectionIndicator date={database.lastContact}/>
</div>
</div>
</div>
<div className="flex flex-col gap-2 flex-1">
<h3 className="text-lg font-black text-foreground group-hover:text-primary transition-colors truncate tracking-tight">
{database.name}
</h3>
<div className="flex flex-col gap-2">
<div
className="flex items-center gap-2 text-muted-foreground group-hover:text-foreground transition-colors">
<div className="p-1 bg-muted/50 rounded-lg">
<Fingerprint className="w-3.5 h-3.5"/>
</div>
<span className="font-mono text-[10px] font-bold truncate">
{database.agentDatabaseId}
</span>
<button
onClick={handleCopy}
className="ml-1 p-0.5 hover:bg-muted rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 z-10"
title="Copy ID"
>
{isCopied ? <Check className="w-2.5 h-2.5 text-green-500"/> :
<Copy className="w-2.5 h-2.5"/>}
</button>
</div>
<div
className="flex items-center gap-2 text-muted-foreground group-hover:text-foreground transition-colors">
<div className="p-1 bg-muted/50 rounded-lg">
<Activity className="w-3.5 h-3.5"/>
</div>
<span className="text-[10px] font-bold uppercase tracking-tight">
{formatDateLastContact(database.lastContact)}
</span>
</div>
</div>
</div>
{withDetails && (
<div className="mt-4 flex items-center justify-between pt-3 border-t border-border/50">
<span
className="text-[10px] font-black uppercase tracking-widest text-primary opacity-0 group-hover:opacity-100 transition-all duration-300 transform translate-x-[-10px] group-hover:translate-x-0">Open</span>
<div
className="flex items-center gap-1 text-muted-foreground group-hover:text-primary transition-colors">
<span
className="text-[10px] font-bold uppercase tracking-widest group-hover:hidden">Details</span>
<ChevronRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform"/>
</div>
</div>
)}
</Card>
);
};
+129
View File
@@ -0,0 +1,129 @@
"use client";
import * as React from "react";
import { format } from "date-fns";
import { useFormContext } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { CalendarIcon } from "lucide-react";
import { cn } from "@/lib/utils";
interface DateTimePickerProps {
name: string;
label?: string;
}
export function DateTimePicker({ name }: DateTimePickerProps) {
const form = useFormContext();
const value: Date | null = form.watch(name);
const handleDateSelect = (date: Date | undefined) => {
if (date) {
const current = form.getValues(name) ?? new Date();
date.setHours(current.getHours());
date.setMinutes(current.getMinutes());
form.setValue(name, date);
}
};
const handleTimeChange = (type: "hour" | "minute" | "ampm", val: string) => {
const currentDate = form.getValues(name) ?? new Date();
const newDate = new Date(currentDate);
if (type === "hour") {
const hour = parseInt(val, 10);
const isPM = newDate.getHours() >= 12;
newDate.setHours((isPM ? 12 : 0) + (hour % 12));
} else if (type === "minute") {
newDate.setMinutes(parseInt(val, 10));
} else if (type === "ampm") {
const hours = newDate.getHours();
if (val === "AM" && hours >= 12) {
newDate.setHours(hours - 12);
} else if (val === "PM" && hours < 12) {
newDate.setHours(hours + 12);
}
}
form.setValue(name, newDate);
};
return (
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" className={cn("w-full pl-3 text-left font-normal", !value && "text-muted-foreground")}>
{value ? format(value, "MM/dd/yyyy hh:mm aa") : <span>MM/DD/YYYY hh:mm aa</span>}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<div className="sm:flex">
<Calendar mode="single" selected={value ?? undefined} onSelect={handleDateSelect} initialFocus />
<div className="flex flex-col sm:flex-row sm:h-[300px] divide-y sm:divide-y-0 sm:divide-x">
{/* Hours */}
<ScrollArea className="w-64 sm:w-auto">
<div className="flex sm:flex-col p-2">
{Array.from({ length: 12 }, (_, i) => i + 1)
.reverse()
.map((hour) => (
<Button
key={hour}
size="icon"
variant={value && value.getHours() % 12 === hour % 12 ? "default" : "ghost"}
className="sm:w-full shrink-0 aspect-square"
onClick={() => handleTimeChange("hour", hour.toString())}
>
{hour}
</Button>
))}
</div>
<ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea>
{/* Minutes */}
<ScrollArea className="w-64 sm:w-auto">
<div className="flex sm:flex-col p-2">
{Array.from({ length: 12 }, (_, i) => i * 5).map((minute) => (
<Button
key={minute}
size="icon"
variant={value && value.getMinutes() === minute ? "default" : "ghost"}
className="sm:w-full shrink-0 aspect-square"
onClick={() => handleTimeChange("minute", minute.toString())}
>
{minute.toString().padStart(2, "0")}
</Button>
))}
</div>
<ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea>
{/* AM/PM */}
<ScrollArea>
<div className="flex sm:flex-col p-2">
{["AM", "PM"].map((ampm) => (
<Button
key={ampm}
size="icon"
variant={
value && ((ampm === "AM" && value.getHours() < 12) || (ampm === "PM" && value.getHours() >= 12))
? "default"
: "ghost"
}
className="sm:w-full shrink-0 aspect-square"
onClick={() => handleTimeChange("ampm", ampm)}
>
{ampm}
</Button>
))}
</div>
</ScrollArea>
</div>
</div>
</PopoverContent>
</Popover>
);
}
+37
View File
@@ -0,0 +1,37 @@
"use client";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export type agentRegistrationDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
};
export const AgentRegistrationDialog = (props: agentRegistrationDialogProps) => {
const { open, setOpen } = props;
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>New agent registered!</DialogTitle>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="name" className="text-right">
CONNECTION KEY
</Label>
<Input id="name" value="Pedro Duarte" readOnly className="col-span-3" />
</div>
</div>
<DialogFooter>
<Button type="submit">Close</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
+137
View File
@@ -0,0 +1,137 @@
"use client";
import {
CircleCheck,
CircleX,
CloudUploadIcon,
Loader2,
Trash2Icon,
} from "lucide-react";
import {
DropZoneArea,
DropzoneDescription,
DropzoneFileList,
DropzoneFileListItem,
DropzoneMessage,
DropzoneRemoveFile,
DropzoneTrigger,
useDropzone,
Dropzone,
} from "@/components/ui/dropzone";
type DropZoneFileProps = {
onFileDropAction?: (file: File) => Promise<void> | void;
onFileRemoveAction?: (file: File) => void;
accept?: Record<string, string[]>;
maxSize?: number;
maxFiles?: number;
description?: string;
fileKind?: string;
dragMessage?: string;
fileList?: boolean;
};
export const DropZoneFile = ({
onFileDropAction,
onFileRemoveAction,
accept = {"application/pdf": [".pdf"]},
maxSize = 50 * 1024 * 1024,
maxFiles = 1,
description = "Please select a file",
fileKind = "Upload files (.pdf)",
dragMessage = "Click here or drag & drop to upload",
fileList = true
}: DropZoneFileProps) => {
const dropzone = useDropzone({
onDropFile: async (file: File) => {
onFileDropAction?.(file);
return {
status: "success",
result: URL.createObjectURL(file),
};
},
validation: {
accept,
maxSize,
maxFiles,
},
});
const handleRemove = (file: any) => {
dropzone.onRemoveFile(file.id);
onFileRemoveAction?.(file.file);
};
return (
<div className="not-prose flex flex-col gap-4 h-full">
<Dropzone {...dropzone}>
<div className="h-full">
{dropzone.fileStatuses.length < maxFiles && (
<div className="flex flex-col h-full">
<div className="flex justify-between">
<DropzoneDescription>{description}</DropzoneDescription>
<DropzoneMessage/>
</div>
<DropZoneArea className="flex-1 px-0 py-0 mt-2">
<DropzoneTrigger
className="flex h-full w-full flex-col items-center justify-center gap-4 bg-transparent p-10 text-center text-sm">
<CloudUploadIcon className="size-8"/>
<div>
<p className="font-semibold">{fileKind}</p>
<p className="text-sm text-muted-foreground">
{dragMessage}
</p>
</div>
</DropzoneTrigger>
</DropZoneArea>
</div>
)}
</div>
{fileList && (
<DropzoneFileList className="grid gap-3 p-0">
{dropzone.fileStatuses.map((file) => (
<DropzoneFileListItem
key={file.id}
file={file}
className="overflow-hidden rounded-md bg-secondary p-0 shadow-sm"
>
<div className="flex items-center justify-between p-2 pl-4">
<div className="flex overflow-hidden items-center gap-3">
<div>
{file.status === "pending" ? (
<Loader2 className="animate-spin" size={16}/>
) : file.status === "error" ? (
<CircleX className="text-red-600" size={16}/>
) : (
<CircleCheck className="text-green-700" size={16}/>
)}
</div>
<div className="min-w-0">
<div className="truncate text-sm flex">
<span>{file.fileName}</span>
</div>
<p className="text-xs text-muted-foreground">
{(file.file.size / (1024 * 1024)).toFixed(2)} MB
</p>
</div>
</div>
<DropzoneRemoveFile
variant="ghost"
className="shrink-0 hover:outline"
// @ts-ignore
onClick={() => handleRemove(file)}
>
<Trash2Icon className="size-4"/>
</DropzoneRemoveFile>
</div>
</DropzoneFileListItem>
))}
</DropzoneFileList>
)}
</Dropzone>
</div>
);
};
@@ -0,0 +1,52 @@
import Link from "next/link";
import {cn} from "@/lib/utils";
import {CircleSlash2, Plus} from "lucide-react";
import {forwardRef, HTMLAttributes} from "react";
type EmptyStatePlaceholderProps = {
url?: string;
onClick?: () => void;
text: string;
className?: string;
state?: string
} & HTMLAttributes<HTMLDivElement>;
export const EmptyStatePlaceholder = forwardRef<HTMLDivElement, EmptyStatePlaceholderProps>(({
url,
onClick,
text,
state,
className,
...props
}, ref) => {
const Container = (
<div
className={cn(
"flex h-full flex-col items-center justify-center w-full rounded-2xl border border-dashed border-muted p-6 lg:p-10",
"transition-colors text-muted-foreground text-center space-y-4",
state != "empty" && "hover:bg-muted/50 hover:text-primary",
(onClick || url) && "cursor-pointer"
)}
onClick={onClick}
>
{state == "empty" ?
<CircleSlash2 className="w-5 h-5 lg:w-6 lg:h-6"/>
:
<Plus className="w-5 h-5 lg:w-6 lg:h-6"/>
}
<p className="text-sm">{text}</p>
</div>
);
if (url) {
return (
<div className={cn(className)}>
<Link href={url}>{Container}</Link>
</div>
);
}
return <div className={cn(className)} ref={ref} {...props}>{Container}</div>;
});
EmptyStatePlaceholder.displayName = "EmptyStatePlaceholder";
+94
View File
@@ -0,0 +1,94 @@
"use client";
import { useSearchParams } from "next/navigation";
import type React from "react";
import { useEffect } from "react";
import { toast } from "sonner";
export const ErrorLayout = ({ children }: { children: React.ReactNode }) => {
const url = useSearchParams();
useEffect(() => {
const error = url.get("error");
if (!error) return;
const errorMessages: Record<string, string> = {
pending: "Your account is not active.",
invalid_or_expired_token: "Password reset invalid token.",
account_already_linked_to_different_user:
"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.",
USER_NOT_FOUND: "User not found",
FAILED_TO_CREATE_USER: "Failed to create user",
FAILED_TO_CREATE_SESSION: "Failed to create session",
FAILED_TO_UPDATE_USER: "Failed to update user",
FAILED_TO_GET_SESSION: "Failed to get session",
INVALID_PASSWORD: "Invalid password",
INVALID_EMAIL: "Invalid email",
INVALID_EMAIL_OR_PASSWORD: "Invalid email or password",
INVALID_USER: "Invalid user",
SOCIAL_ACCOUNT_ALREADY_LINKED: "Social account already linked",
PROVIDER_NOT_FOUND: "Provider not found",
INVALID_TOKEN: "Invalid token",
TOKEN_EXPIRED: "Token expired",
ID_TOKEN_NOT_SUPPORTED: "id_token not supported",
FAILED_TO_GET_USER_INFO: "Failed to get user info",
USER_EMAIL_NOT_FOUND: "User email not found",
EMAIL_NOT_VERIFIED: "Email not verified",
PASSWORD_TOO_SHORT: "Password too short",
PASSWORD_TOO_LONG: "Password too long",
USER_ALREADY_EXISTS: "User already exists.",
USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:
"User already exists. Use another email.",
EMAIL_CAN_NOT_BE_UPDATED: "Email can not be updated",
CREDENTIAL_ACCOUNT_NOT_FOUND: "Credential account not found",
SESSION_EXPIRED:
"Session expired. Re-authenticate to perform this action.",
FAILED_TO_UNLINK_LAST_ACCOUNT: "You can't unlink your last account",
ACCOUNT_NOT_FOUND: "Account not found",
USER_ALREADY_HAS_PASSWORD:
"User already has a password. Provide that to delete the account.",
CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:
"Cross-site navigation login blocked. This request appears to be a CSRF attack.",
VERIFICATION_EMAIL_NOT_ENABLED: "Verification email isn't enabled",
EMAIL_ALREADY_VERIFIED: "Email is already verified",
EMAIL_MISMATCH: "Email mismatch",
SESSION_NOT_FRESH: "Session is not fresh",
LINKED_ACCOUNT_ALREADY_EXISTS: "Linked account already exists",
INVALID_ORIGIN: "Invalid origin",
INVALID_CALLBACK_URL: "Invalid callbackURL",
INVALID_REDIRECT_URL: "Invalid redirectURL",
INVALID_ERROR_CALLBACK_URL: "Invalid errorCallbackURL",
INVALID_NEW_USER_CALLBACK_URL: "Invalid newUserCallbackURL",
MISSING_OR_NULL_ORIGIN: "Missing or null Origin",
CALLBACK_URL_REQUIRED: "callbackURL is required",
FAILED_TO_CREATE_VERIFICATION: "Unable to create verification",
FIELD_NOT_ALLOWED: "Field not allowed to be set",
ASYNC_VALIDATION_NOT_SUPPORTED: "Async validation is not supported",
VALIDATION_ERROR: "Validation Error",
MISSING_FIELD: "Field is required",
METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:
"POST method requires deferSessionRefresh to be enabled in session config",
BODY_MUST_BE_AN_OBJECT: "Body must be an object",
PASSWORD_ALREADY_SET: "User already has a password set",
Sign_up_is_disabled: "Sign up is disabled by the administrator",
};
const match = Object.entries(errorMessages).find(([key]) =>
error.includes(key),
);
if (!match) return;
toast.error(match[1]);
const params = new URLSearchParams(url.toString());
params.delete("error");
const newUrl =
window.location.pathname +
(params.toString() ? `?${params.toString()}` : "");
window.history.replaceState({}, document.title, newUrl);
}, [url]);
return <>{children}</>;
};
+272
View File
@@ -0,0 +1,272 @@
"use client";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { Dispatch, SetStateAction, createContext, forwardRef, useCallback, useContext, useEffect, useRef, useState } from "react";
import { useDropzone, DropzoneState, FileRejection, DropzoneOptions } from "react-dropzone";
import { toast } from "sonner";
import { Trash2 as RemoveIcon } from "lucide-react";
type DirectionOptions = "rtl" | "ltr" | undefined;
type FileUploaderContextType = {
dropzoneState: DropzoneState;
isLOF: boolean;
isFileTooBig: boolean;
removeFileFromSet: (index: number) => void;
activeIndex: number;
setActiveIndex: Dispatch<SetStateAction<number>>;
orientation: "horizontal" | "vertical";
direction: DirectionOptions;
};
const FileUploaderContext = createContext<FileUploaderContextType | null>(null);
export const useFileUpload = () => {
const context = useContext(FileUploaderContext);
if (!context) {
throw new Error("useFileUpload must be used within a FileUploaderProvider");
}
return context;
};
type FileUploaderProps = {
value: File[] | null;
reSelect?: boolean;
onValueChange: (value: File[] | null) => void;
dropzoneOptions: DropzoneOptions;
orientation?: "horizontal" | "vertical";
};
/**
* File upload Docs: {@link: https://localhost:3000/docs/file-upload}
*/
export const FileUploader = forwardRef<HTMLDivElement, FileUploaderProps & React.HTMLAttributes<HTMLDivElement>>(
({ className, dropzoneOptions, value, onValueChange, reSelect, orientation = "vertical", children, dir, ...props }, ref) => {
const [isFileTooBig, setIsFileTooBig] = useState(false);
const [isLOF, setIsLOF] = useState(false);
const [activeIndex, setActiveIndex] = useState(-1);
const {
accept = {
"image/*": [".jpg", ".jpeg", ".png", ".gif"],
},
maxFiles = 1,
maxSize = 4 * 1024 * 1024,
multiple = true,
} = dropzoneOptions;
const reSelectAll = maxFiles === 1 ? true : reSelect;
const direction: DirectionOptions = dir === "rtl" ? "rtl" : "ltr";
const removeFileFromSet = useCallback(
(i: number) => {
if (!value) return;
const newFiles = value.filter((_, index) => index !== i);
onValueChange(newFiles);
},
[value, onValueChange]
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
if (!value) return;
const moveNext = () => {
const nextIndex = activeIndex + 1;
setActiveIndex(nextIndex > value.length - 1 ? 0 : nextIndex);
};
const movePrev = () => {
const nextIndex = activeIndex - 1;
setActiveIndex(nextIndex < 0 ? value.length - 1 : nextIndex);
};
const prevKey = orientation === "horizontal" ? (direction === "ltr" ? "ArrowLeft" : "ArrowRight") : "ArrowUp";
const nextKey = orientation === "horizontal" ? (direction === "ltr" ? "ArrowRight" : "ArrowLeft") : "ArrowDown";
if (e.key === nextKey) {
moveNext();
} else if (e.key === prevKey) {
movePrev();
} else if (e.key === "Enter" || e.key === "Space") {
if (activeIndex === -1) {
dropzoneState.inputRef.current?.click();
}
} else if (e.key === "Delete" || e.key === "Backspace") {
if (activeIndex !== -1) {
removeFileFromSet(activeIndex);
if (value.length - 1 === 0) {
setActiveIndex(-1);
return;
}
movePrev();
}
} else if (e.key === "Escape") {
setActiveIndex(-1);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[value, activeIndex, removeFileFromSet]
);
const onDrop = useCallback(
(acceptedFiles: File[], rejectedFiles: FileRejection[]) => {
const files = acceptedFiles;
if (!files) {
toast.error("file error , probably too big");
return;
}
const newValues: File[] = value ? [...value] : [];
if (reSelectAll) {
newValues.splice(0, newValues.length);
}
files.forEach((file) => {
if (newValues.length < maxFiles) {
newValues.push(file);
}
});
onValueChange(newValues);
if (rejectedFiles.length > 0) {
for (let i = 0; i < rejectedFiles.length; i++) {
if (rejectedFiles[i].errors[0]?.code === "file-too-large") {
toast.error(`File is too large. Max size is ${maxSize / 1024 / 1024}MB`);
break;
}
if (rejectedFiles[i].errors[0]?.message) {
toast.error(rejectedFiles[i].errors[0].message);
break;
}
}
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[reSelectAll, value]
);
useEffect(() => {
if (!value) return;
if (value.length === maxFiles) {
setIsLOF(true);
return;
}
setIsLOF(false);
}, [value, maxFiles]);
const opts = dropzoneOptions ? dropzoneOptions : { accept, maxFiles, maxSize, multiple };
const dropzoneState = useDropzone({
...opts,
onDrop,
onDropRejected: () => setIsFileTooBig(true),
onDropAccepted: () => setIsFileTooBig(false),
});
return (
<FileUploaderContext.Provider
value={{
dropzoneState,
isLOF,
isFileTooBig,
removeFileFromSet,
activeIndex,
setActiveIndex,
orientation,
direction,
}}
>
<div
ref={ref}
tabIndex={0}
onKeyDownCapture={handleKeyDown}
className={cn("grid w-full focus:outline-none", className, {
"gap-2": value && value.length > 0,
})}
dir={dir}
{...props}
>
{children}
</div>
</FileUploaderContext.Provider>
);
}
);
FileUploader.displayName = "FileUploader";
export const FileUploaderContent = forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ children, className, ...props }, ref) => {
const { orientation } = useFileUpload();
const containerRef = useRef<HTMLDivElement>(null);
return (
<div ref={containerRef} aria-description="content file holder">
<div
{...props}
ref={ref}
className={cn(
"grid gap-4",
orientation === "horizontal" ? "grid-rows-1 sm:grid-rows-2 lg:grid-rows-3" : "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
className
)}
>
{children}
</div>
</div>
);
});
FileUploaderContent.displayName = "FileUploaderContent";
export const FileUploaderItem = forwardRef<HTMLDivElement, { index: number } & React.HTMLAttributes<HTMLDivElement>>(
({ className, index, children, ...props }, ref) => {
const { removeFileFromSet, activeIndex, direction } = useFileUpload();
const isSelected = index === activeIndex;
return (
<div ref={ref} className={cn("p-1 justify-between cursor-pointer relative", className, isSelected ? "bg-muted" : "")} {...props}>
<div className="font-medium leading-none tracking-tight flex items-center gap-1.5 h-full w-full">{children}</div>
<button
type="button"
className={cn("absolute", direction === "rtl" ? "top-1 left-1" : "top-1 right-1")}
onClick={() => removeFileFromSet(index)}
>
<span className="sr-only">remove item {index}</span>
<RemoveIcon className="w-4 h-4 hover:stroke-destructive duration-200 ease-in-out" />
</button>
</div>
);
}
);
FileUploaderItem.displayName = "FileUploaderItem";
export const FileInput = forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, children, ...props }, ref) => {
const { dropzoneState, isFileTooBig, isLOF } = useFileUpload();
const rootProps = isLOF ? {} : dropzoneState.getRootProps();
return (
<div ref={ref} {...props} className={`relative w-full ${isLOF ? "opacity-50 cursor-not-allowed " : "cursor-pointer "}`}>
<div
className={cn(
`w-full rounded-lg duration-300 ease-in-out
${dropzoneState.isDragAccept ? "border-green-500" : dropzoneState.isDragReject || isFileTooBig ? "border-red-500" : "border-gray-300"}`,
className
)}
{...rootProps}
>
{children}
</div>
<Input ref={dropzoneState.inputRef} disabled={isLOF} {...dropzoneState.getInputProps()} className={`${isLOF ? "cursor-not-allowed" : ""}`} />
</div>
);
});
FileInput.displayName = "FileInput";
+47
View File
@@ -0,0 +1,47 @@
'use client';
import {GithubButton} from "@/components/ui/github-button";
import * as React from "react";
import {useEffect} from "react";
export const GitHubStarsButtonCustom = () => {
const [stars, setStars] = React.useState(0);
const [isLoading, setIsLoading] = React.useState(true);
const username = "Portabase"
const repo = "portabase"
useEffect(() => {
fetch(`https://api.github.com/repos/${username}/${repo}`)
.then((response) => response.json())
.then((data) => {
if (data && typeof data.stargazers_count === 'number') {
setStars(data.stargazers_count);
}
})
.catch(console.error)
.finally(() => setIsLoading(false));
}, [username, repo]);
if (isLoading) return null;
return (
<div className=" gap-4 flex-wrap hidden md:block">
<GithubButton
initialStars={0}
targetStars={stars}
label=""
size="sm"
separator={true}
roundStars={true}
repoUrl={`https://github.com/${username}/${repo}`}
variant="outline"
/>
</div>
);
};
export default GitHubStarsButtonCustom;
+27
View File
@@ -0,0 +1,27 @@
import React from "react";
import { cn } from "@/lib/utils";
export interface ISVGProps extends React.SVGProps<SVGSVGElement> {
size?: number;
className?: string;
}
export const LoadingSpinner = ({ size = 24, className, ...props }: ISVGProps) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
{...props}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={cn("animate-spin", className)}
>
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
);
};
+333
View File
@@ -0,0 +1,333 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { CheckIcon, XCircle, ChevronDown, XIcon, WandSparkles } from "lucide-react";
import { cn } from "@/lib/utils";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from "@/components/ui/command";
/**
* Variants for the multi-select component to handle different styles.
* Uses class-variance-authority (cva) to define different styles based on "variant" prop.
*/
const multiSelectVariants = cva("m-1 transition ease-in-out duration-300", {
variants: {
variant: {
default: "border-foreground/10 text-foreground bg-card hover:bg-card/80",
secondary: "border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
inverted: "inverted",
},
},
defaultVariants: {
variant: "default",
},
});
/**
* Props for MultiSelect component
*/
interface MultiSelectProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof multiSelectVariants> {
/**
* An array of option objects to be displayed in the multi-select component.
* Each option object has a label, value, and an optional icon.
*/
options: {
/** The text to display for the option. */
label: string;
/** The unique value associated with the option. */
value: string;
/** Optional icon component to display alongside the option. */
icon?: React.ComponentType<{ className?: string }>;
}[];
/**
* Callback function triggered when the selected values change.
* Receives an array of the new selected values.
*/
onValueChange: (value: string[]) => void;
/** The default selected values when the component mounts. */
defaultValue?: string[];
/**
* Placeholder text to be displayed when no values are selected.
* Optional, defaults to "Select options".
*/
placeholder?: string;
/**
* Animation duration in seconds for the visual effects (e.g., bouncing badges).
* Optional, defaults to 0 (no animation).
*/
animation?: number;
/**
* Maximum number of items to display. Extra selected items will be summarized.
* Optional, defaults to 3.
*/
maxCount?: number;
/**
* The modality of the popover. When set to true, interaction with outside elements
* will be disabled and only popover content will be visible to screen readers.
* Optional, defaults to false.
*/
modalPopover?: boolean;
/**
* If true, renders the multi-select component as a child of another component.
* Optional, defaults to false.
*/
asChild?: boolean;
/**
* Additional class names to apply custom styles to the multi-select component.
* Optional, can be used to add custom styles.
*/
className?: string;
}
export const MultiSelect = React.forwardRef<HTMLButtonElement, MultiSelectProps>(
(
{
options,
onValueChange,
variant,
defaultValue = [],
placeholder = "Select options",
animation = 0,
maxCount = 3,
modalPopover = false,
asChild = false,
className,
...props
},
ref
) => {
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue);
const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
const [isAnimating, setIsAnimating] = React.useState(false);
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
setIsPopoverOpen(true);
} else if (event.key === "Backspace" && !event.currentTarget.value) {
const newSelectedValues = [...selectedValues];
newSelectedValues.pop();
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
}
};
const toggleOption = (option: string) => {
const newSelectedValues = selectedValues.includes(option) ? selectedValues.filter((value) => value !== option) : [...selectedValues, option];
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
};
const handleClear = () => {
setSelectedValues([]);
onValueChange([]);
};
const handleTogglePopover = () => {
setIsPopoverOpen((prev) => !prev);
};
const clearExtraOptions = () => {
const newSelectedValues = selectedValues.slice(0, maxCount);
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
};
const toggleAll = () => {
if (selectedValues.length === options.length) {
handleClear();
} else {
const allValues = options.map((option) => option.value);
setSelectedValues(allValues);
onValueChange(allValues);
}
};
return (
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen} modal={modalPopover}>
<PopoverTrigger asChild>
<Button
ref={ref}
{...props}
onClick={handleTogglePopover}
className={cn(
"flex w-full p-1 rounded-md border min-h-10 h-auto items-center justify-between bg-inherit hover:bg-inherit [&_svg]:pointer-events-auto",
className
)}
>
{selectedValues.length > 0 ? (
<div className="flex justify-between items-center w-full">
<div className="flex flex-wrap items-center">
{selectedValues.slice(0, maxCount).map((value) => {
const option = options.find((o) => o.value === value);
const IconComponent = option?.icon;
return (
<Badge
key={value}
className={cn(isAnimating ? "animate-bounce" : "", "max-w-full", multiSelectVariants({ variant }))}
style={{ animationDuration: `${animation}s` }}
>
{IconComponent && <IconComponent className="h-4 w-4 mr-2" />}
<span className="truncate">{option?.label}</span>
<XCircle
className="ml-2 h-4 w-4 cursor-pointer shrink-0"
onClick={(event) => {
event.stopPropagation();
toggleOption(value);
}}
/>
</Badge>
);
})}
{selectedValues.length > maxCount && (
<Badge
className={cn(
"bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
"max-w-full",
isAnimating ? "animate-bounce" : "",
multiSelectVariants({ variant })
)}
style={{ animationDuration: `${animation}s` }}
>
{`+ ${selectedValues.length - maxCount} more`}
<XCircle
className="ml-2 h-4 w-4 cursor-pointer shrink-0"
onClick={(event) => {
event.stopPropagation();
clearExtraOptions();
}}
/>
</Badge>
)}
</div>
<div className="flex items-center justify-between">
<XIcon
className="h-4 mx-2 cursor-pointer text-muted-foreground"
onClick={(event) => {
event.stopPropagation();
handleClear();
}}
/>
<Separator orientation="vertical" className="flex min-h-6 h-full" />
<ChevronDown className="h-4 mx-2 cursor-pointer text-muted-foreground" />
</div>
</div>
) : (
<div className="flex items-center justify-between w-full mx-auto">
<span className="text-sm text-muted-foreground mx-3">{placeholder}</span>
<ChevronDown className="h-4 cursor-pointer text-muted-foreground mx-2" />
</div>
)}
</Button>
</PopoverTrigger>
<PopoverContent
className="w-auto p-0"
align="start"
onEscapeKeyDown={() => setIsPopoverOpen(false)}
>
<Command>
<CommandInput placeholder="Search..." onKeyDown={handleInputKeyDown} />
<CommandList className="max-h-none overflow-visible">
<CommandEmpty>No results found.</CommandEmpty>
<div
className="max-h-[18rem] overflow-y-auto overflow-x-hidden overscroll-contain touch-pan-y pr-1"
style={{ WebkitOverflowScrolling: "touch" }}
onWheelCapture={(event) => event.stopPropagation()}
onTouchMoveCapture={(event) => event.stopPropagation()}
>
<CommandGroup>
<CommandItem key="all" onSelect={toggleAll} className="cursor-pointer">
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
selectedValues.length === options.length
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
>
<CheckIcon className="h-4 w-4" />
</div>
<span>(Select All)</span>
</CommandItem>
{options.map((option) => {
const isSelected = selectedValues.includes(option.value);
return (
<CommandItem
key={option.value}
onSelect={() => toggleOption(option.value)}
className="cursor-pointer"
>
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
isSelected
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
>
<CheckIcon className="h-4 w-4" />
</div>
{option.icon && (
<option.icon className="mr-2 h-4 w-4 text-muted-foreground" />
)}
<span>{option.label}</span>
</CommandItem>
);
})}
</CommandGroup>
</div>
<CommandSeparator />
<CommandGroup>
<div className="flex items-center justify-between">
{selectedValues.length > 0 && (
<>
<CommandItem
onSelect={handleClear}
className="flex-1 justify-center cursor-pointer"
>
Clear
</CommandItem>
<Separator orientation="vertical" className="flex min-h-6 h-full" />
</>
)}
<CommandItem
onSelect={() => setIsPopoverOpen(false)}
className="flex-1 justify-center cursor-pointer max-w-full"
>
Close
</CommandItem>
</div>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
{animation > 0 && selectedValues.length > 0 && (
<WandSparkles
className={cn("cursor-pointer my-2 text-foreground bg-background w-3 h-3", isAnimating ? "" : "text-muted-foreground")}
onClick={() => setIsAnimating(!isAnimating)}
/>
)}
</Popover>
);
}
);
MultiSelect.displayName = "MultiSelect";
@@ -0,0 +1,80 @@
import { PaginationEllipsis, PaginationItem, PaginationLink } from "@/components/ui/pagination";
export type paginationItemsProps = {
totalPages: number;
currentPage: number;
handlePageChange: (page: number) => void;
maxVisiblePages?: number;
};
export const PaginationIndexes = (props: paginationItemsProps) => {
const { totalPages, currentPage, handlePageChange, maxVisiblePages = 3 } = props;
const items = [];
if (totalPages <= maxVisiblePages) {
for (let i = 1; i <= totalPages; i++) {
items.push(
<PaginationItem key={i}>
<PaginationLink onClick={() => handlePageChange(i)} isActive={currentPage === i}>
{i}
</PaginationLink>
</PaginationItem>
);
}
} else {
if (currentPage <= 2) {
for (let i = 1; i <= maxVisiblePages; i++) {
items.push(
<PaginationItem key={i}>
<PaginationLink onClick={() => handlePageChange(i)} isActive={currentPage === i}>
{i}
</PaginationLink>
</PaginationItem>
);
}
items.push(
<PaginationItem key="ellipsis1">
<PaginationEllipsis />
</PaginationItem>
);
} else if (currentPage >= totalPages - 1) {
items.push(
<PaginationItem key="ellipsis2">
<PaginationEllipsis />
</PaginationItem>
);
for (let i = totalPages - 2; i <= totalPages; i++) {
items.push(
<PaginationItem key={i}>
<PaginationLink onClick={() => handlePageChange(i)} isActive={currentPage === i}>
{i}
</PaginationLink>
</PaginationItem>
);
}
} else {
items.push(
<PaginationItem key="ellipsis3">
<PaginationEllipsis />
</PaginationItem>
);
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
items.push(
<PaginationItem key={i}>
<PaginationLink onClick={() => handlePageChange(i)} isActive={currentPage === i}>
{i}
</PaginationLink>
</PaginationItem>
);
}
items.push(
<PaginationItem key="ellipsis4">
<PaginationEllipsis />
</PaginationItem>
);
}
}
return items;
};
@@ -0,0 +1,33 @@
import { Pagination, PaginationContent, PaginationItem, PaginationNext, PaginationPrevious } from "@/components/ui/pagination";
import { PaginationIndexes } from "@/components/common/pagination-indexes";
import { cn } from "@/lib/utils";
export type paginationNavigationProps = {
className?: string;
totalPages: number;
currentPage: number;
goToPage: (page: number) => void;
goToPrevPage: () => void;
goToNextPage: () => void;
maxVisiblePages?: number;
};
export const PaginationNavigation = (props: paginationNavigationProps) => {
const { className, totalPages, currentPage, goToPage, goToPrevPage, goToNextPage, maxVisiblePages = 3 } = props;
if (totalPages <= 1) return null;
return (
<Pagination className={cn("", className)}>
<PaginationContent>
<PaginationItem>
<PaginationPrevious onClick={goToPrevPage} />
</PaginationItem>
<PaginationIndexes totalPages={totalPages} currentPage={currentPage} handlePageChange={goToPage} maxVisiblePages={maxVisiblePages} />
<PaginationItem>
<PaginationNext onClick={goToNextPage} />
</PaginationItem>
</PaginationContent>
</Pagination>
);
};
+35
View File
@@ -0,0 +1,35 @@
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { cn } from "@/lib/utils";
export type PaginationSizeProps = {
className?: string;
pageSize: number;
onPageSizeChange: (size: number) => void;
pageSizeOptions?: number[];
};
export const PaginationSize = (props: PaginationSizeProps) => {
const { className, onPageSizeChange, pageSizeOptions = [10, 20, 30, 40, 50] } = props;
const effectivePageSize = pageSizeOptions.includes(props.pageSize) ? props.pageSize : pageSizeOptions[0];
return (
<div className={cn("flex items-center justify-end sm:justify-center space-x-2", className)}>
<p className="whitespace-nowrap text-sm font-medium hidden md:block">Cards per page</p>
<Select
value={`${effectivePageSize}`}
onValueChange={(value) => onPageSizeChange(Number(value))}
>
<SelectTrigger className="h-8 w-[4.5rem]" aria-label="Cards per page">
<SelectValue placeholder={effectivePageSize} />
</SelectTrigger>
<SelectContent side="top">
{pageSizeOptions.map((size) => (
<SelectItem key={size} value={`${size}`}>
{size}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
};
+36
View File
@@ -0,0 +1,36 @@
import {Icon} from "@iconify/react";
import {CircleHelp, KeyRound} from "lucide-react";
import {cn} from "@/lib/utils";
export const providerSwitch = (provider: string, small?: boolean) => {
switch (provider) {
case "google":
return (
<div className={cn(small ? "p-0" : "p-4")}>
{small ?
<Icon icon={"flat-color-icons:google"} height="24"/>
:
<Icon icon={"logos:google"} height="24"/>
}
</div>
);
case "credential":
return (
<div className={cn("flex flex-row gap-x-2 items-center", small ? "p-0" : "p-4")}>
<KeyRound height="24"/>
{!small && (<span>Email and Password</span>)}
</div>
);
default:
return (
<div className={cn("flex flex-row gap-x-2 items-center", small ? "p-0" : "p-4")}>
<CircleHelp height="24"/>
{!small && (<span>No credentials</span>)}
</div>
);
}
}
+33
View File
@@ -0,0 +1,33 @@
import {Badge} from "@/components/ui/badge";
import {cn} from "@/lib/utils";
export type statusBadgeProps = {
status: "pending" | "ongoing" | "success" | "failed"
}
export const StatusBadge = ({status}: statusBadgeProps) => {
let style = "";
switch (status) {
case 'pending':
style = "text-yellow-500 border-yellow-500"
break
case 'ongoing':
style = "text-orange-500 border-orange-500"
break
case 'failed':
style = "text-red-500 border-red-500"
break
case 'success':
style = "text-green-500 border-green-500"
break
default:
style = "text-yellow-500 border-yellow-500"
}
return (
<Badge variant="outline" className={cn("w-20 border-2 justify-center")}>{status}</Badge>
)
}
+66
View File
@@ -0,0 +1,66 @@
import {DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger} from "@/components/ui/dropdown-menu";
import {Toggle} from "@/components/ui/toggle";
import {CheckIcon, Filter, RefreshCcw} from "lucide-react";
import {Badge} from "@/components/ui/badge";
export type FilterItem = {
label: string,
value: string
}
type FiltersDropdownProps = {
items: FilterItem[];
selectedItems: FilterItem[];
onSelect: (item: FilterItem) => void;
clearFilters: () => void;
}
export const FiltersDropdown = ({items, selectedItems, onSelect, clearFilters}: FiltersDropdownProps) => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="relative">
<Toggle variant="outline" size="sm" className="cursor-pointer w-fit">
<Filter className="h-4 w-4"/>
</Toggle>
{selectedItems.length > 0 && (
<Badge className="absolute -top-2 -right-2 h-4 w-4 rounded-full p-0 flex items-center justify-center text-[10px]">
{selectedItems.length}
</Badge>
)}
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[150px]">
{items.map((item, index) => {
const isSelected = selectedItems.some(f => f.value === item.value);
return (
<DropdownMenuItem
key={index}
className="flex items-center justify-between cursor-pointer"
onClick={(e) => {
e.preventDefault();
onSelect(item);
}}
>
<span>{item.label}</span>
{isSelected && <CheckIcon className="h-4 w-4 text-blue-500"/>}
</DropdownMenuItem>
)
})}
<DropdownMenuItem
disabled={selectedItems.length === 0}
className="flex gap-2 cursor-pointer"
onClick={(e) => {
e.preventDefault();
clearFilters();
}}
>
<RefreshCcw className='h-4 w-4'/>
Clear filters
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,38 @@
import { PaginationNavigation } from "@/components/common/pagination-navigation";
export type paginationNavigationProps = {
className?: string;
table: any;
maxVisiblePages?: number;
};
export const TablePaginationNavigation = (props: paginationNavigationProps) => {
const { className, table, maxVisiblePages = 3 } = props;
const totalPages = table.getPageCount();
const currentPage = table.getState().pagination.pageIndex + 1;
const goToPage = (page: number) => {
table.setPageIndex(page - 1);
};
const goToPrevPage = () => {
if (table.getCanPreviousPage()) table.previousPage();
};
const goToNextPage = () => {
if (table.getCanNextPage()) table.nextPage();
};
return (
<PaginationNavigation
className={className}
totalPages={totalPages}
currentPage={currentPage}
goToPage={goToPage}
goToPrevPage={goToPrevPage}
goToNextPage={goToNextPage}
maxVisiblePages={maxVisiblePages}
/>
);
};
@@ -0,0 +1,40 @@
import { useEffect } from "react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { cn } from "@/lib/utils";
export type tablePaginationSizeProps = {
className?: string;
table: any;
pageSizeOptions?: number[];
};
export const TablePaginationSize = (props: tablePaginationSizeProps) => {
const { className, table, pageSizeOptions = [10, 20, 30, 40, 50] } = props;
useEffect(() => {
table.setPageSize(Number(pageSizeOptions[0]));
}, []);
return (
<div className={cn("flex items-center justify-end sm:justify-center space-x-2", className)}>
<p className="whitespace-nowrap text-sm font-medium hidden md:block">Rows per page</p>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger className="h-8 w-[4.5rem]">
<SelectValue placeholder={table.getState().pagination.pageSize} />
</SelectTrigger>
<SelectContent side="top">
{pageSizeOptions.map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
};
@@ -0,0 +1,29 @@
"use client";
import {TablePaginationNavigation} from "@/components/common/table-pagination-navigation";
import {TablePaginationSize} from "@/components/common/table-pagination-size";
import {cn} from "@/lib/utils";
interface tablePaginationProps {
className?: string;
table: any;
maxVisiblePages?: number;
pageSizeOptions?: number[];
}
export function TablePagination(props: tablePaginationProps) {
const {className, table, maxVisiblePages = 3, pageSizeOptions = [10, 20, 30, 40, 50]} = props;
const totalPages = table.getPageCount();
if (totalPages <= 1) return null;
return (
<div
className={cn("flex gap-x-4", className)}
>
<TablePaginationSize table={table} pageSizeOptions={pageSizeOptions}/>
<TablePaginationNavigation table={table} maxVisiblePages={maxVisiblePages} className="justify-end mt-0"/>
</div>
);
}
@@ -0,0 +1,18 @@
import { Button } from "@/components/ui/button";
import { Column } from "@tanstack/react-table";
import { ArrowDown, ArrowUp } from "lucide-react";
interface tableSortButtonProps<TData, TValue> {
title?: string;
defaultOrder: "asc" | "desc";
column: Column<TData, TValue>;
}
export default function TableSortButton<TData, TValue>(props: tableSortButtonProps<TData, TValue>) {
return (
<Button variant="ghost" onClick={() => props.column.toggleSorting(props.column.getIsSorted() === "asc")}>
{props.title ?? "Please define a title"}
{props.column.getIsSorted() === props.defaultOrder ? <ArrowUp className="ml-2 h-4 w-4" /> : <ArrowDown className="ml-2 h-4 w-4" />}
</Button>
);
}
+26
View File
@@ -0,0 +1,26 @@
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { PropsWithChildren } from "react";
export type TooltipCustomProps = PropsWithChildren<{
text: string;
disabled?: any;
}>;
export function TooltipCustom(props: TooltipCustomProps) {
return (
<>
{props.disabled ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger className="w-full">{props.children}</TooltipTrigger>
<TooltipContent>
<p>{props.text}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
props.children
)}
</>
);
}