text
stringlengths 21
253k
| id
stringlengths 25
123
| metadata
dict | __index_level_0__
int64 0
181
|
---|---|---|---|
import { useCallback, useEffect, useState } from "react";
export default function useScroll(threshold: number) {
const [scrolled, setScrolled] = useState(false);
const onScroll = useCallback(() => {
setScrolled(window.scrollY > threshold);
}, [threshold]);
useEffect(() => {
onScroll();
}, [onScroll]);
useEffect(() => {
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, [onScroll]);
return scrolled;
}
| moinulmoin/chadnext/src/hooks/use-scroll.ts | {
"file_path": "moinulmoin/chadnext/src/hooks/use-scroll.ts",
"repo_id": "moinulmoin/chadnext",
"token_count": 159
} | 81 |
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ArrowRight } from "lucide-react";
import { useTheme } from "next-themes";
import Image from "next/image";
import Link from "next/link";
export const HeroSection = () => {
const { theme } = useTheme();
return (
<section className="container w-full">
<div className="grid place-items-center lg:max-w-screen-xl gap-8 mx-auto py-20 md:py-32">
<div className="text-center space-y-8">
<Badge variant="outline" className="text-sm py-2">
<span className="mr-2 text-primary">
<Badge>New</Badge>
</span>
<span> Design is out now! </span>
</Badge>
<div className="max-w-screen-md mx-auto text-center text-4xl md:text-6xl font-bold">
<h1>
Experience the
<span className="text-transparent px-2 bg-gradient-to-r from-[#D247BF] to-primary bg-clip-text">
Shadcn
</span>
landing page
</h1>
</div>
<p className="max-w-screen-sm mx-auto text-xl text-muted-foreground">
{`We're more than just a tool, we're a community of passionate
creators. Get access to exclusive resources, tutorials, and support.`}
</p>
<div className="space-y-4 md:space-y-0 md:space-x-4">
<Button className="w-5/6 md:w-1/4 font-bold group/arrow">
Get Started
<ArrowRight className="size-5 ml-2 group-hover/arrow:translate-x-1 transition-transform" />
</Button>
<Button
asChild
variant="secondary"
className="w-5/6 md:w-1/4 font-bold"
>
<Link
href="https://github.com/nobruf/shadcn-landing-page.git"
target="_blank"
>
Github respository
</Link>
</Button>
</div>
</div>
<div className="relative group mt-14">
<div className="absolute top-2 lg:-top-8 left-1/2 transform -translate-x-1/2 w-[90%] mx-auto h-24 lg:h-80 bg-primary/50 rounded-full blur-3xl"></div>
<Image
width={1200}
height={1200}
className="w-full md:w-[1200px] mx-auto rounded-lg relative rouded-lg leading-none flex items-center border border-t-2 border-secondary border-t-primary/30"
src={
theme === "light"
? "/hero-image-light.jpeg"
: "/hero-image-dark.jpeg"
}
alt="dashboard"
/>
<div className="absolute bottom-0 left-0 w-full h-20 md:h-28 bg-gradient-to-b from-background/0 via-background/50 to-background rounded-lg"></div>
</div>
</div>
</section>
);
};
| nobruf/shadcn-landing-page/components/layout/sections/hero.tsx | {
"file_path": "nobruf/shadcn-landing-page/components/layout/sections/hero.tsx",
"repo_id": "nobruf/shadcn-landing-page",
"token_count": 1456
} | 82 |
import { icons } from "lucide-react";
export const Icon = ({
name,
color,
size,
className,
}: {
name: keyof typeof icons;
color: string;
size: number;
className?: string;
}) => {
const LucideIcon = icons[name as keyof typeof icons];
return <LucideIcon color={color} size={size} className={className} />;
};
| nobruf/shadcn-landing-page/components/ui/icon.tsx | {
"file_path": "nobruf/shadcn-landing-page/components/ui/icon.tsx",
"repo_id": "nobruf/shadcn-landing-page",
"token_count": 115
} | 83 |
import { Card } from "@/components/ui/card"
import { CardSkeleton } from "@/components/card-skeleton"
import { DashboardHeader } from "@/components/header"
import { DashboardShell } from "@/components/shell"
export default function DashboardSettingsLoading() {
return (
<DashboardShell>
<DashboardHeader
heading="Settings"
text="Manage account and website settings."
/>
<div className="grid gap-10">
<CardSkeleton />
</div>
</DashboardShell>
)
}
| shadcn-ui/taxonomy/app/(dashboard)/dashboard/settings/loading.tsx | {
"file_path": "shadcn-ui/taxonomy/app/(dashboard)/dashboard/settings/loading.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 185
} | 84 |
import Link from "next/link"
import { Doc } from "contentlayer/generated"
import { docsConfig } from "@/config/docs"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
import { Icons } from "@/components/icons"
interface DocsPagerProps {
doc: Doc
}
export function DocsPager({ doc }: DocsPagerProps) {
const pager = getPagerForDoc(doc)
if (!pager) {
return null
}
return (
<div className="flex flex-row items-center justify-between">
{pager?.prev && (
<Link
href={pager.prev.href}
className={cn(buttonVariants({ variant: "ghost" }))}
>
<Icons.chevronLeft className="mr-2 h-4 w-4" />
{pager.prev.title}
</Link>
)}
{pager?.next && (
<Link
href={pager.next.href}
className={cn(buttonVariants({ variant: "ghost" }), "ml-auto")}
>
{pager.next.title}
<Icons.chevronRight className="ml-2 h-4 w-4" />
</Link>
)}
</div>
)
}
export function getPagerForDoc(doc: Doc) {
const flattenedLinks = [null, ...flatten(docsConfig.sidebarNav), null]
const activeIndex = flattenedLinks.findIndex(
(link) => doc.slug === link?.href
)
const prev = activeIndex !== 0 ? flattenedLinks[activeIndex - 1] : null
const next =
activeIndex !== flattenedLinks.length - 1
? flattenedLinks[activeIndex + 1]
: null
return {
prev,
next,
}
}
export function flatten(links: { items? }[]) {
return links.reduce((flat, link) => {
return flat.concat(link.items ? flatten(link.items) : link)
}, [])
}
| shadcn-ui/taxonomy/components/pager.tsx | {
"file_path": "shadcn-ui/taxonomy/components/pager.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 696
} | 85 |
import * as React from "react"
import { VariantProps, cva } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center border rounded-full px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"bg-primary hover:bg-primary/80 border-transparent text-primary-foreground",
secondary:
"bg-secondary hover:bg-secondary/80 border-transparent text-secondary-foreground",
destructive:
"bg-destructive hover:bg-destructive/80 border-transparent text-destructive-foreground",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
| shadcn-ui/taxonomy/components/ui/badge.tsx | {
"file_path": "shadcn-ui/taxonomy/components/ui/badge.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 420
} | 86 |
"use client"
import Link from "next/link"
import { User } from "next-auth"
import { signOut } from "next-auth/react"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { UserAvatar } from "@/components/user-avatar"
interface UserAccountNavProps extends React.HTMLAttributes<HTMLDivElement> {
user: Pick<User, "name" | "image" | "email">
}
export function UserAccountNav({ user }: UserAccountNavProps) {
return (
<DropdownMenu>
<DropdownMenuTrigger>
<UserAvatar
user={{ name: user.name || null, image: user.image || null }}
className="h-8 w-8"
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<div className="flex items-center justify-start gap-2 p-2">
<div className="flex flex-col space-y-1 leading-none">
{user.name && <p className="font-medium">{user.name}</p>}
{user.email && (
<p className="w-[200px] truncate text-sm text-muted-foreground">
{user.email}
</p>
)}
</div>
</div>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href="/dashboard">Dashboard</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/dashboard/billing">Billing</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/dashboard/settings">Settings</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="cursor-pointer"
onSelect={(event) => {
event.preventDefault()
signOut({
callbackUrl: `${window.location.origin}/login`,
})
}}
>
Sign out
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
| shadcn-ui/taxonomy/components/user-account-nav.tsx | {
"file_path": "shadcn-ui/taxonomy/components/user-account-nav.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 901
} | 87 |
import Stripe from "stripe"
import { env } from "@/env.mjs"
export const stripe = new Stripe(env.STRIPE_API_KEY, {
apiVersion: "2022-11-15",
typescript: true,
})
| shadcn-ui/taxonomy/lib/stripe.ts | {
"file_path": "shadcn-ui/taxonomy/lib/stripe.ts",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 67
} | 88 |
/*
Warnings:
- A unique constraint covering the columns `[stripe_customer_id]` on the table `users` will be added. If there are existing duplicate values, this will fail.
- A unique constraint covering the columns `[stripe_subscription_id]` on the table `users` will be added. If there are existing duplicate values, this will fail.
*/
-- DropForeignKey
ALTER TABLE `accounts` DROP FOREIGN KEY `accounts_userId_fkey`;
-- DropForeignKey
ALTER TABLE `posts` DROP FOREIGN KEY `posts_authorId_fkey`;
-- DropForeignKey
ALTER TABLE `sessions` DROP FOREIGN KEY `sessions_userId_fkey`;
-- AlterTable
ALTER TABLE `users` ADD COLUMN `stripe_current_period_end` DATETIME(3) NULL,
ADD COLUMN `stripe_customer_id` VARCHAR(191) NULL,
ADD COLUMN `stripe_price_id` VARCHAR(191) NULL,
ADD COLUMN `stripe_subscription_id` VARCHAR(191) NULL;
-- CreateIndex
CREATE UNIQUE INDEX `users_stripe_customer_id_key` ON `users`(`stripe_customer_id`);
-- CreateIndex
CREATE UNIQUE INDEX `users_stripe_subscription_id_key` ON `users`(`stripe_subscription_id`);
| shadcn-ui/taxonomy/prisma/migrations/20221118173244_add_stripe_columns/migration.sql | {
"file_path": "shadcn-ui/taxonomy/prisma/migrations/20221118173244_add_stripe_columns/migration.sql",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 373
} | 89 |
{
"name": "Taxonomy",
"short_name": "Taxonomy",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
| shadcn-ui/taxonomy/public/site.webmanifest | {
"file_path": "shadcn-ui/taxonomy/public/site.webmanifest",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 182
} | 90 |
import {
ChevronDownIcon,
CircleIcon,
PlusIcon,
StarIcon,
} from "@radix-ui/react-icons"
import { Button } from "@/registry/new-york/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/registry/new-york/ui/card"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/registry/new-york/ui/dropdown-menu"
import { Separator } from "@/registry/new-york/ui/separator"
export function DemoGithub() {
return (
<Card>
<CardHeader className="grid grid-cols-[1fr_110px] items-start gap-4 space-y-0">
<div className="space-y-1">
<CardTitle>shadcn/ui</CardTitle>
<CardDescription>
Beautifully designed components that you can copy and paste into
your apps. Accessible. Customizable. Open Source.
</CardDescription>
</div>
<div className="flex items-center space-x-1 rounded-md bg-secondary text-secondary-foreground">
<Button variant="secondary" className="px-3 shadow-none">
<StarIcon className="mr-2 h-4 w-4" />
Star
</Button>
<Separator orientation="vertical" className="h-[20px]" />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" className="px-2 shadow-none">
<ChevronDownIcon className="h-4 w-4 text-secondary-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
alignOffset={-5}
className="w-[200px]"
forceMount
>
<DropdownMenuLabel>Suggested Lists</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuCheckboxItem checked>
Future Ideas
</DropdownMenuCheckboxItem>
<DropdownMenuCheckboxItem>My Stack</DropdownMenuCheckboxItem>
<DropdownMenuCheckboxItem>Inspiration</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuItem>
<PlusIcon className="mr-2 h-4 w-4" /> Create List
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</CardHeader>
<CardContent>
<div className="flex space-x-4 text-sm text-muted-foreground">
<div className="flex items-center">
<CircleIcon className="mr-1 h-3 w-3 fill-sky-400 text-sky-400" />
TypeScript
</div>
<div className="flex items-center">
<StarIcon className="mr-1 h-3 w-3" />
20k
</div>
<div>Updated April 2023</div>
</div>
</CardContent>
</Card>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/cards/components/github-card.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/cards/components/github-card.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1359
} | 91 |
import { Separator } from "@/registry/new-york/ui/separator"
import { AccountForm } from "@/app/(app)/examples/forms/account/account-form"
export default function SettingsAccountPage() {
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-medium">Account</h3>
<p className="text-sm text-muted-foreground">
Update your account settings. Set your preferred language and
timezone.
</p>
</div>
<Separator />
<AccountForm />
</div>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/forms/account/page.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/forms/account/page.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 222
} | 92 |
"use client"
import Link from "next/link"
import { LucideIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/registry/default/ui/button"
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/registry/new-york/ui/tooltip"
interface NavProps {
isCollapsed: boolean
links: {
title: string
label?: string
icon: LucideIcon
variant: "default" | "ghost"
}[]
}
export function Nav({ links, isCollapsed }: NavProps) {
return (
<div
data-collapsed={isCollapsed}
className="group flex flex-col gap-4 py-2 data-[collapsed=true]:py-2"
>
<nav className="grid gap-1 px-2 group-[[data-collapsed=true]]:justify-center group-[[data-collapsed=true]]:px-2">
{links.map((link, index) =>
isCollapsed ? (
<Tooltip key={index} delayDuration={0}>
<TooltipTrigger asChild>
<Link
href="#"
className={cn(
buttonVariants({ variant: link.variant, size: "icon" }),
"h-9 w-9",
link.variant === "default" &&
"dark:bg-muted dark:text-muted-foreground dark:hover:bg-muted dark:hover:text-white"
)}
>
<link.icon className="h-4 w-4" />
<span className="sr-only">{link.title}</span>
</Link>
</TooltipTrigger>
<TooltipContent side="right" className="flex items-center gap-4">
{link.title}
{link.label && (
<span className="ml-auto text-muted-foreground">
{link.label}
</span>
)}
</TooltipContent>
</Tooltip>
) : (
<Link
key={index}
href="#"
className={cn(
buttonVariants({ variant: link.variant, size: "sm" }),
link.variant === "default" &&
"dark:bg-muted dark:text-white dark:hover:bg-muted dark:hover:text-white",
"justify-start"
)}
>
<link.icon className="mr-2 h-4 w-4" />
{link.title}
{link.label && (
<span
className={cn(
"ml-auto",
link.variant === "default" &&
"text-background dark:text-white"
)}
>
{link.label}
</span>
)}
</Link>
)
)}
</nav>
</div>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/mail/components/nav.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/mail/components/nav.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1519
} | 93 |
"use client"
import * as React from "react"
import { useRouter } from "next/navigation"
import { CaretSortIcon, CheckIcon } from "@radix-ui/react-icons"
import { PopoverProps } from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
import { Button } from "@/registry/new-york/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/registry/new-york/ui/command"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/registry/new-york/ui/popover"
import { Preset } from "../data/presets"
interface PresetSelectorProps extends PopoverProps {
presets: Preset[]
}
export function PresetSelector({ presets, ...props }: PresetSelectorProps) {
const [open, setOpen] = React.useState(false)
const [selectedPreset, setSelectedPreset] = React.useState<Preset>()
const router = useRouter()
return (
<Popover open={open} onOpenChange={setOpen} {...props}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-label="Load a preset..."
aria-expanded={open}
className="flex-1 justify-between md:max-w-[200px] lg:max-w-[300px]"
>
{selectedPreset ? selectedPreset.name : "Load a preset..."}
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput placeholder="Search presets..." />
<CommandList>
<CommandEmpty>No presets found.</CommandEmpty>
<CommandGroup heading="Examples">
{presets.map((preset) => (
<CommandItem
key={preset.id}
onSelect={() => {
setSelectedPreset(preset)
setOpen(false)
}}
>
{preset.name}
<CheckIcon
className={cn(
"ml-auto h-4 w-4",
selectedPreset?.id === preset.id
? "opacity-100"
: "opacity-0"
)}
/>
</CommandItem>
))}
</CommandGroup>
<CommandGroup className="pt-0">
<CommandItem onSelect={() => router.push("/examples")}>
More examples
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/playground/components/preset-selector.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/playground/components/preset-selector.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1291
} | 94 |
import {
ArrowDownIcon,
ArrowRightIcon,
ArrowUpIcon,
CheckCircledIcon,
CircleIcon,
CrossCircledIcon,
QuestionMarkCircledIcon,
StopwatchIcon,
} from "@radix-ui/react-icons"
export const labels = [
{
value: "bug",
label: "Bug",
},
{
value: "feature",
label: "Feature",
},
{
value: "documentation",
label: "Documentation",
},
]
export const statuses = [
{
value: "backlog",
label: "Backlog",
icon: QuestionMarkCircledIcon,
},
{
value: "todo",
label: "Todo",
icon: CircleIcon,
},
{
value: "in progress",
label: "In Progress",
icon: StopwatchIcon,
},
{
value: "done",
label: "Done",
icon: CheckCircledIcon,
},
{
value: "canceled",
label: "Canceled",
icon: CrossCircledIcon,
},
]
export const priorities = [
{
label: "Low",
value: "low",
icon: ArrowDownIcon,
},
{
label: "Medium",
value: "medium",
icon: ArrowRightIcon,
},
{
label: "High",
value: "high",
icon: ArrowUpIcon,
},
]
| shadcn-ui/ui/apps/www/app/(app)/examples/tasks/data/data.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/tasks/data/data.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 460
} | 95 |
"use client"
import { Analytics as VercelAnalytics } from "@vercel/analytics/react"
export function Analytics() {
return <VercelAnalytics />
}
| shadcn-ui/ui/apps/www/components/analytics.tsx | {
"file_path": "shadcn-ui/ui/apps/www/components/analytics.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 44
} | 96 |
"use client"
import { Check, Clipboard } from "lucide-react"
import { toast } from "sonner"
import { type Color } from "@/lib/colors"
import { trackEvent } from "@/lib/events"
import { useColors } from "@/hooks/use-colors"
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"
import { copyToClipboardWithMeta } from "@/components/copy-button"
export function Color({ color }: { color: Color }) {
const { format } = useColors()
const { isCopied, copyToClipboard } = useCopyToClipboard()
return (
<button
key={color.hex}
className="group relative flex aspect-[3/1] w-full flex-1 flex-col gap-2 text-[--text] sm:aspect-[2/3] sm:h-auto sm:w-auto [&>svg]:absolute [&>svg]:right-4 [&>svg]:top-4 [&>svg]:h-3.5 [&>svg]:w-3.5 [&>svg]:opacity-0 [&>svg]:transition-opacity"
style={
{
"--bg": `hsl(${color.hsl})`,
"--text": color.foreground,
} as React.CSSProperties
}
onClick={() => {
copyToClipboard(color[format])
trackEvent({
name: "copy_color",
properties: {
color: color.id,
value: color[format],
format,
},
})
toast.success(`Copied ${color[format]} to clipboard.`)
}}
>
{isCopied ? (
<Check className="group-hover:opacity-100" />
) : (
<Clipboard className="group-hover:opacity-100" />
)}
<div className="w-full flex-1 rounded-md bg-[--bg] md:rounded-lg" />
<div className="flex w-full flex-col items-center justify-center gap-1">
<span className="hidden font-mono text-xs tabular-nums text-muted-foreground transition-colors group-hover:text-foreground lg:flex">
{color.className}
</span>
<span className="font-mono text-xs tabular-nums text-muted-foreground transition-colors group-hover:text-foreground lg:hidden">
{color.scale}
</span>
</div>
</button>
)
}
| shadcn-ui/ui/apps/www/components/color.tsx | {
"file_path": "shadcn-ui/ui/apps/www/components/color.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 883
} | 97 |
import { cn } from "@/lib/utils"
function PageHeader({
className,
children,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<section
className={cn(
"mx-auto flex flex-col items-start gap-2 px-4 py-8 md:py-12 md:pb-8 lg:py-12 lg:pb-10",
className
)}
{...props}
>
{children}
</section>
)
}
function PageHeaderHeading({
className,
...props
}: React.HTMLAttributes<HTMLHeadingElement>) {
return (
<h1
className={cn(
"text-3xl font-bold leading-tight tracking-tighter md:text-4xl lg:leading-[1.1]",
className
)}
{...props}
/>
)
}
function PageHeaderDescription({
className,
...props
}: React.HTMLAttributes<HTMLParagraphElement>) {
return (
<p
className={cn(
"text-balance max-w-2xl text-lg font-light text-foreground",
className
)}
{...props}
/>
)
}
function PageActions({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn(
"flex w-full items-center justify-start gap-2 py-2",
className
)}
{...props}
/>
)
}
export { PageActions, PageHeader, PageHeaderDescription, PageHeaderHeading }
| shadcn-ui/ui/apps/www/components/page-header.tsx | {
"file_path": "shadcn-ui/ui/apps/www/components/page-header.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 562
} | 98 |
// @ts-nocheck
"use client"
import * as React from "react"
import { TableOfContents } from "@/lib/toc"
import { cn } from "@/lib/utils"
import { useMounted } from "@/hooks/use-mounted"
interface TocProps {
toc: TableOfContents
}
export function DashboardTableOfContents({ toc }: TocProps) {
const itemIds = React.useMemo(
() =>
toc.items
? toc.items
.flatMap((item) => [item.url, item?.items?.map((item) => item.url)])
.flat()
.filter(Boolean)
.map((id) => id?.split("#")[1])
: [],
[toc]
)
const activeHeading = useActiveItem(itemIds)
const mounted = useMounted()
if (!toc?.items?.length) {
return null
}
return (
<div className="space-y-2">
<p className="font-medium">On This Page</p>
<Tree tree={toc} activeItem={activeHeading} />
</div>
)
}
function useActiveItem(itemIds: string[]) {
const [activeId, setActiveId] = React.useState(null)
React.useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setActiveId(entry.target.id)
}
})
},
{ rootMargin: `0% 0% -80% 0%` }
)
itemIds?.forEach((id) => {
const element = document.getElementById(id)
if (element) {
observer.observe(element)
}
})
return () => {
itemIds?.forEach((id) => {
const element = document.getElementById(id)
if (element) {
observer.unobserve(element)
}
})
}
}, [itemIds])
return activeId
}
interface TreeProps {
tree: TableOfContents
level?: number
activeItem?: string
}
function Tree({ tree, level = 1, activeItem }: TreeProps) {
return tree?.items?.length && level < 3 ? (
<ul className={cn("m-0 list-none", { "pl-4": level !== 1 })}>
{tree.items.map((item, index) => {
return (
<li key={index} className={cn("mt-0 pt-2")}>
<a
href={item.url}
className={cn(
"inline-block no-underline transition-colors hover:text-foreground",
item.url === `#${activeItem}`
? "font-medium text-foreground"
: "text-muted-foreground"
)}
>
{item.title}
</a>
{item.items?.length ? (
<Tree tree={item} level={level + 1} activeItem={activeItem} />
) : null}
</li>
)
})}
</ul>
) : null
}
| shadcn-ui/ui/apps/www/components/toc.tsx | {
"file_path": "shadcn-ui/ui/apps/www/components/toc.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1257
} | 99 |
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatDate(input: string | number): string {
const date = new Date(input)
return date.toLocaleDateString("en-US", {
month: "long",
day: "numeric",
year: "numeric",
})
}
export function absoluteUrl(path: string) {
return `${process.env.NEXT_PUBLIC_APP_URL}${path}`
}
| shadcn-ui/ui/apps/www/lib/utils.ts | {
"file_path": "shadcn-ui/ui/apps/www/lib/utils.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 176
} | 100 |
import * as React from "react"
import { Button } from "@/registry/default/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/registry/default/ui/card"
import { Input } from "@/registry/default/ui/input"
import { Label } from "@/registry/default/ui/label"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/registry/default/ui/select"
export default function CardWithForm() {
return (
<Card className="w-[350px]">
<CardHeader>
<CardTitle>Create project</CardTitle>
<CardDescription>Deploy your new project in one-click.</CardDescription>
</CardHeader>
<CardContent>
<form>
<div className="grid w-full items-center gap-4">
<div className="flex flex-col space-y-1.5">
<Label htmlFor="name">Name</Label>
<Input id="name" placeholder="Name of your project" />
</div>
<div className="flex flex-col space-y-1.5">
<Label htmlFor="framework">Framework</Label>
<Select>
<SelectTrigger id="framework">
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent position="popper">
<SelectItem value="next">Next.js</SelectItem>
<SelectItem value="sveltekit">SvelteKit</SelectItem>
<SelectItem value="astro">Astro</SelectItem>
<SelectItem value="nuxt">Nuxt.js</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</form>
</CardContent>
<CardFooter className="flex justify-between">
<Button variant="outline">Cancel</Button>
<Button>Deploy</Button>
</CardFooter>
</Card>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/card-with-form.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/card-with-form.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 846
} | 101 |
"use client"
import * as React from "react"
import { Check, ChevronsUpDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/registry/default/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/registry/default/ui/command"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/registry/default/ui/popover"
const frameworks = [
{
value: "next.js",
label: "Next.js",
},
{
value: "sveltekit",
label: "SvelteKit",
},
{
value: "nuxt.js",
label: "Nuxt.js",
},
{
value: "remix",
label: "Remix",
},
{
value: "astro",
label: "Astro",
},
]
export default function ComboboxDemo() {
const [open, setOpen] = React.useState(false)
const [value, setValue] = React.useState("")
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-[200px] justify-between"
>
{value
? frameworks.find((framework) => framework.value === value)?.label
: "Select framework..."}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0">
<Command>
<CommandInput placeholder="Search framework..." />
<CommandList>
<CommandEmpty>No framework found.</CommandEmpty>
<CommandGroup>
{frameworks.map((framework) => (
<CommandItem
key={framework.value}
value={framework.value}
onSelect={(currentValue) => {
setValue(currentValue === value ? "" : currentValue)
setOpen(false)
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === framework.value ? "opacity-100" : "opacity-0"
)}
/>
{framework.label}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/combobox-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/combobox-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1182
} | 102 |
import { Input } from "@/registry/default/ui/input"
import { Label } from "@/registry/default/ui/label"
export default function InputWithText() {
return (
<div className="grid w-full max-w-sm items-center gap-1.5">
<Label htmlFor="email-2">Email</Label>
<Input type="email" id="email-2" placeholder="Email" />
<p className="text-sm text-muted-foreground">Enter your email address.</p>
</div>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/input-with-text.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/input-with-text.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 158
} | 103 |
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { toast } from "@/registry/default/hooks/use-toast"
import { Button } from "@/registry/default/ui/button"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/registry/default/ui/form"
import { Textarea } from "@/registry/default/ui/textarea"
const FormSchema = z.object({
bio: z
.string()
.min(10, {
message: "Bio must be at least 10 characters.",
})
.max(160, {
message: "Bio must not be longer than 30 characters.",
}),
})
export default function TextareaForm() {
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
})
function onSubmit(data: z.infer<typeof FormSchema>) {
toast({
title: "You submitted the following values:",
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(data, null, 2)}</code>
</pre>
),
})
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
<FormField
control={form.control}
name="bio"
render={({ field }) => (
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea
placeholder="Tell us a little bit about yourself"
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
You can <span>@mention</span> other users and organizations.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/textarea-form.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/textarea-form.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 901
} | 104 |
import { Badge } from "@/registry/new-york/ui/badge"
export default function BadgeOutline() {
return <Badge variant="outline">Outline</Badge>
}
| shadcn-ui/ui/apps/www/registry/new-york/example/badge-outline.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/badge-outline.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 50
} | 105 |
import { Button } from "@/registry/new-york/ui/button"
export default function ButtonSecondary() {
return <Button variant="secondary">Secondary</Button>
}
| shadcn-ui/ui/apps/www/registry/new-york/example/button-secondary.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/button-secondary.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 46
} | 106 |
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { toast } from "@/registry/new-york/hooks/use-toast"
import { Button } from "@/registry/new-york/ui/button"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/registry/new-york/ui/form"
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@/registry/new-york/ui/input-otp"
const FormSchema = z.object({
pin: z.string().min(6, {
message: "Your one-time password must be 6 characters.",
}),
})
export default function InputOTPForm() {
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
pin: "",
},
})
function onSubmit(data: z.infer<typeof FormSchema>) {
toast({
title: "You submitted the following values:",
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(data, null, 2)}</code>
</pre>
),
})
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
<FormField
control={form.control}
name="pin"
render={({ field }) => (
<FormItem>
<FormLabel>One-Time Password</FormLabel>
<FormControl>
<InputOTP maxLength={6} {...field}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
</FormControl>
<FormDescription>
Please enter the one-time password sent to your phone.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
)
}
| shadcn-ui/ui/apps/www/registry/new-york/example/input-otp-form.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/input-otp-form.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1079
} | 107 |
"use client"
import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"
import { cn } from "@/lib/utils"
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
"relative flex w-full touch-none select-none items-center",
className
)}
{...props}
>
<SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
export { Slider }
| shadcn-ui/ui/apps/www/registry/new-york/ui/slider.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/ui/slider.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 370
} | 108 |
import { Registry } from "@/registry/schema"
export const hooks: Registry = [
{
name: "use-mobile",
type: "registry:hook",
files: [
{
path: "hooks/use-mobile.tsx",
type: "registry:hook",
},
],
},
{
name: "use-toast",
type: "registry:hook",
files: [
{
path: "hooks/use-toast.ts",
type: "registry:hook",
},
],
},
]
| shadcn-ui/ui/apps/www/registry/registry-hooks.ts | {
"file_path": "shadcn-ui/ui/apps/www/registry/registry-hooks.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 210
} | 109 |
import { z } from "zod"
// TODO: Extract this to a shared package.
export const registryItemSchema = z.object({
name: z.string(),
dependencies: z.array(z.string()).optional(),
devDependencies: z.array(z.string()).optional(),
registryDependencies: z.array(z.string()).optional(),
files: z.array(z.string()),
type: z.enum(["components:ui", "components:component", "components:example"]),
})
export const registryIndexSchema = z.array(registryItemSchema)
export const registryItemWithContentSchema = registryItemSchema.extend({
files: z.array(
z.object({
name: z.string(),
content: z.string(),
})
),
})
export const registryWithContentSchema = z.array(registryItemWithContentSchema)
export const stylesSchema = z.array(
z.object({
name: z.string(),
label: z.string(),
})
)
export const registryBaseColorSchema = z.object({
inlineColors: z.object({
light: z.record(z.string(), z.string()),
dark: z.record(z.string(), z.string()),
}),
cssVars: z.object({
light: z.record(z.string(), z.string()),
dark: z.record(z.string(), z.string()),
}),
inlineColorsTemplate: z.string(),
cssVarsTemplate: z.string(),
})
| shadcn-ui/ui/packages/cli/src/utils/registry/schema.ts | {
"file_path": "shadcn-ui/ui/packages/cli/src/utils/registry/schema.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 433
} | 110 |
import path from "path"
import { describe, expect, test } from "vitest"
import { isTypeScriptProject } from "../../src/utils/get-project-info"
describe("is TypeScript project", async () => {
test.each([
{
name: "next-app",
result: true,
},
{
name: "next-app-src",
result: true,
},
{
name: "next-pages",
result: true,
},
{
name: "next-pages-src",
result: true,
},
{
name: "t3-app",
result: true,
},
{
name: "next-app-js",
result: false,
},
])(`isTypeScriptProject($name) -> $result`, async ({ name, result }) => {
expect(
await isTypeScriptProject(path.resolve(__dirname, `../fixtures/${name}`))
).toBe(result)
})
})
| shadcn-ui/ui/packages/cli/test/utils/is-typescript-project.test.ts | {
"file_path": "shadcn-ui/ui/packages/cli/test/utils/is-typescript-project.test.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 346
} | 111 |
import { promises as fs } from "fs"
import path from "path"
import { preFlightInit } from "@/src/preflights/preflight-init"
import { addComponents } from "@/src/utils/add-components"
import { createProject } from "@/src/utils/create-project"
import * as ERRORS from "@/src/utils/errors"
import {
DEFAULT_COMPONENTS,
DEFAULT_TAILWIND_CONFIG,
DEFAULT_TAILWIND_CSS,
DEFAULT_UTILS,
getConfig,
rawConfigSchema,
resolveConfigPaths,
type Config,
} from "@/src/utils/get-config"
import { getProjectConfig, getProjectInfo } from "@/src/utils/get-project-info"
import { handleError } from "@/src/utils/handle-error"
import { highlighter } from "@/src/utils/highlighter"
import { logger } from "@/src/utils/logger"
import { getRegistryBaseColors, getRegistryStyles } from "@/src/utils/registry"
import { spinner } from "@/src/utils/spinner"
import { updateTailwindContent } from "@/src/utils/updaters/update-tailwind-content"
import { Command } from "commander"
import prompts from "prompts"
import { z } from "zod"
export const initOptionsSchema = z.object({
cwd: z.string(),
components: z.array(z.string()).optional(),
yes: z.boolean(),
defaults: z.boolean(),
force: z.boolean(),
silent: z.boolean(),
isNewProject: z.boolean(),
srcDir: z.boolean().optional(),
})
export const init = new Command()
.name("init")
.description("initialize your project and install dependencies")
.argument(
"[components...]",
"the components to add or a url to the component."
)
.option("-y, --yes", "skip confirmation prompt.", true)
.option("-d, --defaults,", "use default configuration.", false)
.option("-f, --force", "force overwrite of existing configuration.", false)
.option(
"-c, --cwd <cwd>",
"the working directory. defaults to the current directory.",
process.cwd()
)
.option("-s, --silent", "mute output.", false)
.option(
"--src-dir",
"use the src directory when creating a new project.",
false
)
.action(async (components, opts) => {
try {
const options = initOptionsSchema.parse({
cwd: path.resolve(opts.cwd),
isNewProject: false,
components,
...opts,
})
await runInit(options)
logger.log(
`${highlighter.success(
"Success!"
)} Project initialization completed.\nYou may now add components.`
)
logger.break()
} catch (error) {
logger.break()
handleError(error)
}
})
export async function runInit(
options: z.infer<typeof initOptionsSchema> & {
skipPreflight?: boolean
}
) {
let projectInfo
if (!options.skipPreflight) {
const preflight = await preFlightInit(options)
if (preflight.errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]) {
const { projectPath } = await createProject(options)
if (!projectPath) {
process.exit(1)
}
options.cwd = projectPath
options.isNewProject = true
}
projectInfo = preflight.projectInfo
} else {
projectInfo = await getProjectInfo(options.cwd)
}
const projectConfig = await getProjectConfig(options.cwd, projectInfo)
const config = projectConfig
? await promptForMinimalConfig(projectConfig, options)
: await promptForConfig(await getConfig(options.cwd))
if (!options.yes) {
const { proceed } = await prompts({
type: "confirm",
name: "proceed",
message: `Write configuration to ${highlighter.info(
"components.json"
)}. Proceed?`,
initial: true,
})
if (!proceed) {
process.exit(0)
}
}
// Write components.json.
const componentSpinner = spinner(`Writing components.json.`).start()
const targetPath = path.resolve(options.cwd, "components.json")
await fs.writeFile(targetPath, JSON.stringify(config, null, 2), "utf8")
componentSpinner.succeed()
// Add components.
const fullConfig = await resolveConfigPaths(options.cwd, config)
const components = ["index", ...(options.components || [])]
await addComponents(components, fullConfig, {
// Init will always overwrite files.
overwrite: true,
silent: options.silent,
isNewProject:
options.isNewProject || projectInfo?.framework.name === "next-app",
})
// If a new project is using src dir, let's update the tailwind content config.
// TODO: Handle this per framework.
if (options.isNewProject && options.srcDir) {
await updateTailwindContent(
["./src/**/*.{js,ts,jsx,tsx,mdx}"],
fullConfig,
{
silent: options.silent,
}
)
}
return fullConfig
}
async function promptForConfig(defaultConfig: Config | null = null) {
const [styles, baseColors] = await Promise.all([
getRegistryStyles(),
getRegistryBaseColors(),
])
logger.info("")
const options = await prompts([
{
type: "toggle",
name: "typescript",
message: `Would you like to use ${highlighter.info(
"TypeScript"
)} (recommended)?`,
initial: defaultConfig?.tsx ?? true,
active: "yes",
inactive: "no",
},
{
type: "select",
name: "style",
message: `Which ${highlighter.info("style")} would you like to use?`,
choices: styles.map((style) => ({
title: style.label,
value: style.name,
})),
},
{
type: "select",
name: "tailwindBaseColor",
message: `Which color would you like to use as the ${highlighter.info(
"base color"
)}?`,
choices: baseColors.map((color) => ({
title: color.label,
value: color.name,
})),
},
{
type: "text",
name: "tailwindCss",
message: `Where is your ${highlighter.info("global CSS")} file?`,
initial: defaultConfig?.tailwind.css ?? DEFAULT_TAILWIND_CSS,
},
{
type: "toggle",
name: "tailwindCssVariables",
message: `Would you like to use ${highlighter.info(
"CSS variables"
)} for theming?`,
initial: defaultConfig?.tailwind.cssVariables ?? true,
active: "yes",
inactive: "no",
},
{
type: "text",
name: "tailwindPrefix",
message: `Are you using a custom ${highlighter.info(
"tailwind prefix eg. tw-"
)}? (Leave blank if not)`,
initial: "",
},
{
type: "text",
name: "tailwindConfig",
message: `Where is your ${highlighter.info(
"tailwind.config.js"
)} located?`,
initial: defaultConfig?.tailwind.config ?? DEFAULT_TAILWIND_CONFIG,
},
{
type: "text",
name: "components",
message: `Configure the import alias for ${highlighter.info(
"components"
)}:`,
initial: defaultConfig?.aliases["components"] ?? DEFAULT_COMPONENTS,
},
{
type: "text",
name: "utils",
message: `Configure the import alias for ${highlighter.info("utils")}:`,
initial: defaultConfig?.aliases["utils"] ?? DEFAULT_UTILS,
},
{
type: "toggle",
name: "rsc",
message: `Are you using ${highlighter.info("React Server Components")}?`,
initial: defaultConfig?.rsc ?? true,
active: "yes",
inactive: "no",
},
])
return rawConfigSchema.parse({
$schema: "https://ui.shadcn.com/schema.json",
style: options.style,
tailwind: {
config: options.tailwindConfig,
css: options.tailwindCss,
baseColor: options.tailwindBaseColor,
cssVariables: options.tailwindCssVariables,
prefix: options.tailwindPrefix,
},
rsc: options.rsc,
tsx: options.typescript,
aliases: {
utils: options.utils,
components: options.components,
// TODO: fix this.
lib: options.components.replace(/\/components$/, "lib"),
hooks: options.components.replace(/\/components$/, "hooks"),
},
})
}
async function promptForMinimalConfig(
defaultConfig: Config,
opts: z.infer<typeof initOptionsSchema>
) {
let style = defaultConfig.style
let baseColor = defaultConfig.tailwind.baseColor
let cssVariables = defaultConfig.tailwind.cssVariables
if (!opts.defaults) {
const [styles, baseColors] = await Promise.all([
getRegistryStyles(),
getRegistryBaseColors(),
])
const options = await prompts([
{
type: "select",
name: "style",
message: `Which ${highlighter.info("style")} would you like to use?`,
choices: styles.map((style) => ({
title: style.label,
value: style.name,
})),
initial: styles.findIndex((s) => s.name === style),
},
{
type: "select",
name: "tailwindBaseColor",
message: `Which color would you like to use as the ${highlighter.info(
"base color"
)}?`,
choices: baseColors.map((color) => ({
title: color.label,
value: color.name,
})),
},
{
type: "toggle",
name: "tailwindCssVariables",
message: `Would you like to use ${highlighter.info(
"CSS variables"
)} for theming?`,
initial: defaultConfig?.tailwind.cssVariables,
active: "yes",
inactive: "no",
},
])
style = options.style
baseColor = options.tailwindBaseColor
cssVariables = options.tailwindCssVariables
}
return rawConfigSchema.parse({
$schema: defaultConfig?.$schema,
style,
tailwind: {
...defaultConfig?.tailwind,
baseColor,
cssVariables,
},
rsc: defaultConfig?.rsc,
tsx: defaultConfig?.tsx,
aliases: defaultConfig?.aliases,
})
}
| shadcn-ui/ui/packages/shadcn/src/commands/init.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/src/commands/init.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 3850
} | 112 |
import { z } from "zod"
// TODO: Extract this to a shared package.
export const registryItemTypeSchema = z.enum([
"registry:style",
"registry:lib",
"registry:example",
"registry:block",
"registry:component",
"registry:ui",
"registry:hook",
"registry:theme",
"registry:page",
])
export const registryItemFileSchema = z.object({
path: z.string(),
content: z.string().optional(),
type: registryItemTypeSchema,
target: z.string().optional(),
})
export const registryItemTailwindSchema = z.object({
config: z
.object({
content: z.array(z.string()).optional(),
theme: z.record(z.string(), z.any()).optional(),
plugins: z.array(z.string()).optional(),
})
.optional(),
})
export const registryItemCssVarsSchema = z.object({
light: z.record(z.string(), z.string()).optional(),
dark: z.record(z.string(), z.string()).optional(),
})
export const registryItemSchema = z.object({
name: z.string(),
type: registryItemTypeSchema,
description: z.string().optional(),
dependencies: z.array(z.string()).optional(),
devDependencies: z.array(z.string()).optional(),
registryDependencies: z.array(z.string()).optional(),
files: z.array(registryItemFileSchema).optional(),
tailwind: registryItemTailwindSchema.optional(),
cssVars: registryItemCssVarsSchema.optional(),
meta: z.record(z.string(), z.any()).optional(),
docs: z.string().optional(),
})
export type RegistryItem = z.infer<typeof registryItemSchema>
export const registryIndexSchema = z.array(
registryItemSchema.extend({
files: z.array(z.union([z.string(), registryItemFileSchema])).optional(),
})
)
export const stylesSchema = z.array(
z.object({
name: z.string(),
label: z.string(),
})
)
export const registryBaseColorSchema = z.object({
inlineColors: z.object({
light: z.record(z.string(), z.string()),
dark: z.record(z.string(), z.string()),
}),
cssVars: z.object({
light: z.record(z.string(), z.string()),
dark: z.record(z.string(), z.string()),
}),
inlineColorsTemplate: z.string(),
cssVarsTemplate: z.string(),
})
export const registryResolvedItemsTreeSchema = registryItemSchema.pick({
dependencies: true,
devDependencies: true,
files: true,
tailwind: true,
cssVars: true,
docs: true,
})
| shadcn-ui/ui/packages/shadcn/src/utils/registry/schema.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/src/utils/registry/schema.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 822
} | 113 |
import fs from "fs"
import path from "path"
import { execa } from "execa"
import { afterEach, expect, test, vi } from "vitest"
import { runInit } from "../../src/commands/init"
import { getConfig } from "../../src/utils/get-config"
import * as getPackageManger from "../../src/utils/get-package-manager"
import * as registry from "../../src/utils/registry"
vi.mock("execa")
vi.mock("fs/promises", () => ({
writeFile: vi.fn(),
mkdir: vi.fn(),
}))
vi.mock("ora")
test.skip("init config-full", async () => {
vi.spyOn(getPackageManger, "getPackageManager").mockResolvedValue("pnpm")
vi.spyOn(registry, "getRegistryBaseColor").mockResolvedValue({
inlineColors: {},
cssVars: {},
inlineColorsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
cssVarsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
})
vi.spyOn(registry, "getRegistryItem").mockResolvedValue({
name: "new-york",
dependencies: [
"tailwindcss-animate",
"class-variance-authority",
"clsx",
"tailwind-merge",
"lucide-react",
"@radix-ui/react-icons",
],
registryDependencies: [],
tailwind: {
config: {
theme: {
extend: {
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
},
},
plugins: ['require("tailwindcss-animate")'],
},
},
files: [],
cssVariables: {
light: {
"--radius": "0.5rem",
},
},
})
const mockMkdir = vi.spyOn(fs.promises, "mkdir").mockResolvedValue(undefined)
const mockWriteFile = vi.spyOn(fs.promises, "writeFile").mockResolvedValue()
const targetDir = path.resolve(__dirname, "../fixtures/config-full")
const config = await getConfig(targetDir)
await runInit(config)
expect(mockMkdir).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/src\/lib$/),
expect.anything()
)
expect(mockMkdir).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/src\/components$/),
expect.anything()
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/src\/app\/globals.css$/),
expect.stringContaining(`@tailwind base`),
"utf8"
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
3,
expect.stringMatching(/src\/lib\/utils.ts$/),
expect.stringContaining(`import { type ClassValue, clsx } from "clsx"`),
"utf8"
)
expect(execa).toHaveBeenCalledWith(
"pnpm",
[
"add",
"tailwindcss-animate",
"class-variance-authority",
"clsx",
"tailwind-merge",
"lucide-react",
"@radix-ui/react-icons",
],
{
cwd: targetDir,
}
)
mockMkdir.mockRestore()
mockWriteFile.mockRestore()
})
test.skip("init config-partial", async () => {
vi.spyOn(getPackageManger, "getPackageManager").mockResolvedValue("npm")
vi.spyOn(registry, "getRegistryBaseColor").mockResolvedValue({
inlineColors: {},
cssVars: {},
inlineColorsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
cssVarsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
})
vi.spyOn(registry, "getRegistryItem").mockResolvedValue({
name: "new-york",
dependencies: [
"tailwindcss-animate",
"class-variance-authority",
"clsx",
"tailwind-merge",
"lucide-react",
],
registryDependencies: [],
tailwind: {
config: {
theme: {
extend: {
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
},
},
plugins: ['require("tailwindcss-animate")'],
},
},
files: [],
cssVariables: {
light: {
"--radius": "0.5rem",
},
},
})
const mockMkdir = vi.spyOn(fs.promises, "mkdir").mockResolvedValue(undefined)
const mockWriteFile = vi.spyOn(fs.promises, "writeFile").mockResolvedValue()
const targetDir = path.resolve(__dirname, "../fixtures/config-partial")
const config = await getConfig(targetDir)
await runInit(config)
expect(mockMkdir).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/src\/assets\/css$/),
expect.anything()
)
expect(mockMkdir).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/lib$/),
expect.anything()
)
expect(mockMkdir).toHaveBeenNthCalledWith(
3,
expect.stringMatching(/components$/),
expect.anything()
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/utils.ts$/),
expect.stringContaining(`import { type ClassValue, clsx } from "clsx"`),
"utf8"
)
expect(execa).toHaveBeenCalledWith(
"npm",
[
"install",
"tailwindcss-animate",
"class-variance-authority",
"clsx",
"tailwind-merge",
"lucide-react",
],
{
cwd: targetDir,
}
)
mockMkdir.mockRestore()
mockWriteFile.mockRestore()
})
afterEach(() => {
vi.resetAllMocks()
})
| shadcn-ui/ui/packages/shadcn/test/commands/init.test.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/commands/init.test.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 2363
} | 114 |
import type { User, Note } from "@prisma/client";
import { prisma } from "~/db.server";
export function getNote({
id,
userId,
}: Pick<Note, "id"> & {
userId: User["id"];
}) {
return prisma.note.findFirst({
select: { id: true, body: true, title: true },
where: { id, userId },
});
}
export function getNoteListItems({ userId }: { userId: User["id"] }) {
return prisma.note.findMany({
where: { userId },
select: { id: true, title: true },
orderBy: { updatedAt: "desc" },
});
}
export function createNote({
body,
title,
userId,
}: Pick<Note, "body" | "title"> & {
userId: User["id"];
}) {
return prisma.note.create({
data: {
title,
body,
user: {
connect: {
id: userId,
},
},
},
});
}
export function deleteNote({
id,
userId,
}: Pick<Note, "id"> & { userId: User["id"] }) {
return prisma.note.deleteMany({
where: { id, userId },
});
}
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/models/note.server.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/models/note.server.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 402
} | 115 |
import { useMatches } from "@remix-run/react";
import { useMemo } from "react";
import type { User } from "~/models/user.server";
const DEFAULT_REDIRECT = "/";
/**
* This should be used any time the redirect path is user-provided
* (Like the query string on our login/signup pages). This avoids
* open-redirect vulnerabilities.
* @param {string} to The redirect destination
* @param {string} defaultRedirect The redirect to use if the to is unsafe.
*/
export function safeRedirect(
to: FormDataEntryValue | string | null | undefined,
defaultRedirect: string = DEFAULT_REDIRECT,
) {
if (!to || typeof to !== "string") {
return defaultRedirect;
}
if (!to.startsWith("/") || to.startsWith("//")) {
return defaultRedirect;
}
return to;
}
/**
* This base hook is used in other hooks to quickly search for specific data
* across all loader data using useMatches.
* @param {string} id The route id
* @returns {JSON|undefined} The router data or undefined if not found
*/
export function useMatchesData(
id: string,
): Record<string, unknown> | undefined {
const matchingRoutes = useMatches();
const route = useMemo(
() => matchingRoutes.find((route) => route.id === id),
[matchingRoutes, id],
);
return route?.data as Record<string, unknown>;
}
function isUser(user: unknown): user is User {
return (
user != null &&
typeof user === "object" &&
"email" in user &&
typeof user.email === "string"
);
}
export function useOptionalUser(): User | undefined {
const data = useMatchesData("root");
if (!data || !isUser(data.user)) {
return undefined;
}
return data.user;
}
export function useUser(): User {
const maybeUser = useOptionalUser();
if (!maybeUser) {
throw new Error(
"No user found in root loader, but user is required by useUser. If user is optional, try useOptionalUser instead.",
);
}
return maybeUser;
}
export function validateEmail(email: unknown): email is string {
return typeof email === "string" && email.length > 3 && email.includes("@");
}
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/utils.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/utils.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 651
} | 116 |
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL PRIMARY KEY,
"email" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
-- CreateTable
CREATE TABLE "Password" (
"hash" TEXT NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "Password_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "Note" (
"id" TEXT NOT NULL PRIMARY KEY,
"title" TEXT NOT NULL,
"body" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "Note_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Password_userId_key" ON "Password"("userId");
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/prisma/migrations/20220713162558_init/migration.sql | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/prisma/migrations/20220713162558_init/migration.sql",
"repo_id": "shadcn-ui/ui",
"token_count": 369
} | 117 |
/**
* By default, Remix will handle generating the HTTP Response for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal`
* For more information, see https://remix.run/file-conventions/entry.server
*/
import { PassThrough } from "node:stream";
import type { AppLoadContext, EntryContext } from "@remix-run/node";
import { createReadableStreamFromReadable } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";
const ABORT_DELAY = 5_000;
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// This is ignored so we can keep it in the template for visibility. Feel
// free to delete this parameter in your app if you're not using it!
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext
) {
return isbot(request.headers.get("user-agent") || "")
? handleBotRequest(
request,
responseStatusCode,
responseHeaders,
remixContext
)
: handleBrowserRequest(
request,
responseStatusCode,
responseHeaders,
remixContext
);
}
function handleBotRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onAllReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);
responseHeaders.set("Content-Type", "text/html");
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);
pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
}
);
setTimeout(abort, ABORT_DELAY);
});
}
function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onShellReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);
responseHeaders.set("Content-Type", "text/html");
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);
pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
}
);
setTimeout(abort, ABORT_DELAY);
});
}
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix/app/entry.server.tsx | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix/app/entry.server.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1623
} | 118 |
import { describe, expect, test } from "vitest"
import { transformTailwindContent } from "../../../src/utils/updaters/update-tailwind-content"
const SHARED_CONFIG = {
$schema: "https://ui.shadcn.com/schema.json",
style: "new-york",
rsc: true,
tsx: true,
tailwind: {
config: "tailwind.config.ts",
css: "app/globals.css",
baseColor: "slate",
cssVariables: true,
},
aliases: {
components: "@/components",
utils: "@/lib/utils",
},
resolvedPaths: {
cwd: ".",
tailwindConfig: "tailwind.config.ts",
tailwindCss: "app/globals.css",
components: "./components",
utils: "./lib/utils",
ui: "./components/ui",
},
}
describe("transformTailwindContent -> content property", () => {
test("should add content property if not in config", async () => {
expect(
await transformTailwindContent(
`import type { Config } from 'tailwindcss'
const config: Config = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [],
}
export default config
`,
["./foo/**/*.{js,ts,jsx,tsx,mdx}", "./bar/**/*.{js,ts,jsx,tsx,mdx}"],
{
config: SHARED_CONFIG,
}
)
).toMatchSnapshot()
})
test("should NOT add content property if already in config", async () => {
expect(
await transformTailwindContent(
`import type { Config } from 'tailwindcss'
const config: Config = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [],
}
export default config
`,
["./app/**/*.{js,ts,jsx,tsx,mdx}", "./bar/**/*.{js,ts,jsx,tsx,mdx}"],
{
config: SHARED_CONFIG,
}
)
).toMatchSnapshot()
})
})
| shadcn-ui/ui/packages/shadcn/test/utils/updaters/update-tailwind-content.test.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/utils/updaters/update-tailwind-content.test.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 1083
} | 119 |
import "@/styles/globals.css"
import { Metadata } from "next"
import { siteConfig } from "@/config/site"
import { fontSans } from "@/lib/fonts"
import { cn } from "@/lib/utils"
import { SiteHeader } from "@/components/site-header"
import { TailwindIndicator } from "@/components/tailwind-indicator"
import { ThemeProvider } from "@/components/theme-provider"
export const metadata: Metadata = {
title: {
default: siteConfig.name,
template: `%s - ${siteConfig.name}`,
},
description: siteConfig.description,
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "white" },
{ media: "(prefers-color-scheme: dark)", color: "black" },
],
icons: {
icon: "/favicon.ico",
shortcut: "/favicon-16x16.png",
apple: "/apple-touch-icon.png",
},
}
interface RootLayoutProps {
children: React.ReactNode
}
export default function RootLayout({ children }: RootLayoutProps) {
return (
<>
<html lang="en" suppressHydrationWarning>
<head />
<body
className={cn(
"min-h-screen bg-background font-sans antialiased",
fontSans.variable
)}
>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<div className="relative flex min-h-screen flex-col">
<SiteHeader />
<div className="flex-1">{children}</div>
</div>
<TailwindIndicator />
</ThemeProvider>
</body>
</html>
</>
)
}
| shadcn-ui/ui/templates/next-template/app/layout.tsx | {
"file_path": "shadcn-ui/ui/templates/next-template/app/layout.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 633
} | 120 |
import "@/styles/globals.css"
import { Metadata } from "next"
import Head from "next/head"
import Script from 'next/script'
import { siteConfig } from "@/config/site"
import { fontSans } from "@/lib/fonts"
import { cn } from "@/lib/utils"
import { SiteFooter } from "@/components/site-footer"
import { SiteHeader } from "@/components/site-header"
import { TailwindIndicator } from "@/components/tailwind-indicator"
import { ThemeProvider } from "@/components/theme-provider"
import { Analytics } from "@vercel/analytics/react"
import { SiteBanner } from "@/components/site-banner"
import { GoogleAnalytics } from '@next/third-parties/google'
export const metadata: Metadata = {
metadataBase: new URL("https://www.easyui.pro/"), // Change this line
title: {
default: siteConfig.name,
template: `%s - ${siteConfig.name}`,
},
description: siteConfig.description,
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "white" },
{ media: "(prefers-color-scheme: dark)", color: "black" },
],
icons: {
icon: "/favicon-32x32.ico",
shortcut: "/favicon-16x16.png",
apple: "/apple-touch-icon.png",
},
openGraph: {
url: "https://www.easyui.pro/",
title: siteConfig.name,
description: siteConfig.description,
images: [{ url: "https://pub-0cd6f9d4131f4f79ac40219248ae64db.r2.dev/og.png", width: 800, height: 600, alt: siteConfig.name }],
siteName: siteConfig.name,
},
twitter: {
card: "summary_large_image",
},
}
interface RootLayoutProps {
children: React.ReactNode
}
export default function RootLayout({ children }: RootLayoutProps) {
return (
<>
<html lang="en" suppressHydrationWarning>
<Head>
<title>${siteConfig.name}</title>
<meta property="og:url" content="https://www.easyui.pro/" />
<meta property="og:image" content="https://pub-0cd6f9d4131f4f79ac40219248ae64db.r2.dev/og.png" />
<meta
property="twitter:url"
content="https://www.easyui.pro/"
/>
<meta property="twitter:image" content="https://pub-0cd6f9d4131f4f79ac40219248ae64db.r2.dev/og.png" />
<script defer src="https://cloud.umami.is/script.js" data-website-id="7ad28072-1308-433d-abce-2e92a70ab64d"></script>
<link rel="alternate" href="https://www.easyui.pro/templates" title="Easy UI Templates" />
<link rel="alternate" href="https://premium.easyui.pro/" title="Easy UI Premium" />
<link rel="alternate" href="https://premium.easyui.pro/docs/sections/bento-grid" title="Easy UI Components" />
</Head>
<body
className={cn(
"min-h-screen bg-background font-sans antialiased",
fontSans.variable
)}
>
<Analytics/>
<GoogleAnalytics gaId="G-0RXSHN6M9R" />
<SiteBanner />
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<SiteHeader />
{children}
<SiteFooter />
<TailwindIndicator />
<Script
src="https://cloud.umami.is/script.js"
strategy="afterInteractive"
data-website-id="7ad28072-1308-433d-abce-2e92a70ab64d"
defer
/>
</ThemeProvider>
</body>
</html>
</>
)
}
| DarkInventor/easy-ui/app/layout.tsx | {
"file_path": "DarkInventor/easy-ui/app/layout.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 1445
} | 0 |
"use client";
import { cn } from "@/lib/utils";
import AnimatedGradientText from "@/components/magicui/animated-gradient-text";
import { ChevronRight } from "lucide-react";
export function Announcement() {
return (
<a className="z-10 flex min-h-[4rem] items-center justify-center mx-auto" href="/templates">
<AnimatedGradientText>
<hr className="mx-2 h-4 w-[1px] shrink-0 bg-gray-300" />{" "}
<a
className={cn(
`inline animate-gradient bg-gradient-to-r from-[#ffaa40] via-[#9c40ff] to-[#ffaa40] bg-[length:var(--bg-size)_100%] bg-clip-text text-transparent`,
)}
href="/templates"
>
Introducing Easy-UI
</a>
<ChevronRight className="ml-1 size-3 transition-transform duration-300 ease-in-out group-hover:translate-x-0.5" />
</AnimatedGradientText>
</a>
);
}
| DarkInventor/easy-ui/components/announcement.tsx | {
"file_path": "DarkInventor/easy-ui/components/announcement.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 387
} | 1 |
"use client";
import { cn } from "@/lib/utils";
import React from "react";
interface AvatarCirclesProps {
className?: string;
numPeople?: number;
avatarUrls: string[];
}
const AvatarCircles = ({ numPeople, className, avatarUrls }: AvatarCirclesProps) => {
return (
<div className={cn("z-10 flex -space-x-4 rtl:space-x-reverse", className)}>
{avatarUrls.map((url, index) => (
<img
key={index}
className="h-10 w-10 rounded-full border-2 border-white dark:border-gray-800"
src={url}
width={40}
height={40}
alt={`Avatar ${index + 1}`}
/>
))}
<a
className="flex h-10 w-10 items-center justify-center rounded-full border-2 border-white bg-black text-center text-xs font-medium text-white hover:bg-gray-600 dark:border-gray-800 dark:bg-white dark:text-black"
href=""
>
+{numPeople}
</a>
</div>
);
};
export default AvatarCircles;
| DarkInventor/easy-ui/components/magicui/avatar-circles.tsx | {
"file_path": "DarkInventor/easy-ui/components/magicui/avatar-circles.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 431
} | 2 |
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"bg-muted text-muted-foreground inline-flex h-10 items-center justify-center rounded-md p-1",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"ring-offset-background focus-visible:ring-ring data-[state=active]:bg-background data-[state=active]:text-foreground inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"ring-offset-background focus-visible:ring-ring mt-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
| DarkInventor/easy-ui/components/ui/tabs.tsx | {
"file_path": "DarkInventor/easy-ui/components/ui/tabs.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 674
} | 3 |
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--primary: 240 5.9% 10%;
--primary-foreground: 0 0% 98%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--ring: 240 5% 64.9%;
--radius: 0.5rem;
}
.dark {
--background: 0 0% 0%;
--foreground: 0 0% 98%;
--card: 0 0% 0%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 0%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 240 5.9% 10%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 240 3.7% 15.9%;
--muted-foreground: 240 5% 64.9%;
--accent: 240 3.7% 15.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 85.7% 97.3%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 240 4.9% 83.9%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
font-feature-settings: "rlig" 1, "calt" 1;
}
}
@layer utilities {
.step {
counter-increment: step;
}
.step:before {
@apply absolute inline-flex h-9 w-9 items-center justify-center rounded-full border-4 border-background bg-muted text-center -indent-px font-mono text-base font-medium;
@apply ml-[-50px] mt-[-4px];
content: counter(step);
}
}
@media (max-width: 640px) {
.container {
@apply px-4;
}
}
.lab-bg {
--mask-offset: 100px;
-webkit-mask: linear-gradient(
to bottom,
transparent,
#fff var(--mask-offset) calc(100% - var(--mask-offset)),
transparent
),
linear-gradient(
to right,
transparent,
#fff var(--mask-offset) calc(100% - var(--mask-offset)),
transparent
);
mask: linear-gradient(
to bottom,
transparent,
#fff var(--mask-offset) calc(100% - var(--mask-offset)),
transparent
),
linear-gradient(
to right,
transparent,
#fff var(--mask-offset) calc(100% - var(--mask-offset)),
transparent
);
/* -webkit-mask: radial-gradient(circle at 50% 50%,transparent 0,#fff calc(100% - var(--mask-offset)),transparent 100%); */
-webkit-mask-composite: source-in, xor;
mask-composite: intersect;
}
| DarkInventor/easy-ui/styles/globals.css | {
"file_path": "DarkInventor/easy-ui/styles/globals.css",
"repo_id": "DarkInventor/easy-ui",
"token_count": 1214
} | 4 |
const { resolve } = require("node:path");
const project = resolve(process.cwd(), "tsconfig.json");
/*
* This is a custom ESLint configuration for use with
* internal (bundled by their consumer) libraries
* that utilize React.
*
* This config extends the Vercel Engineering Style Guide.
* For more information, see https://github.com/vercel/style-guide
*
*/
/** @type {import("eslint").Linter.Config} */
module.exports = {
extends: [
"eslint:recommended",
"prettier",
"eslint-config-turbo",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
],
plugins: ["only-warn"],
globals: {
React: true,
JSX: true,
},
env: {
browser: true,
},
settings: {
react: {
version: "detect",
},
},
rules: {
"react/prop-types": "off",
},
settings: {
"import/resolver": {
typescript: {
project,
},
},
},
ignorePatterns: [
// Ignore dotfiles
".*.js",
"node_modules/",
"dist/",
],
overrides: [
// Force ESLint to detect .tsx files
{ files: ["*.js?(x)", "*.ts?(x)"] },
],
};
| alifarooq9/rapidlaunch/packages/eslint-config/react-internal.js | {
"file_path": "alifarooq9/rapidlaunch/packages/eslint-config/react-internal.js",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 602
} | 5 |
export const orgBillingPageConfig = {
title: "Billing",
description: "Manage your billing settings and subscription.",
} as const;
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/billing/_constants/page-config.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/billing/_constants/page-config.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 40
} | 6 |
"use client";
import { Button } from "@/components/ui/button";
// import { Input } from "@/components/ui/input";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { Icons } from "@/components/ui/icons";
import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useMutation } from "@tanstack/react-query";
import { useAwaitableTransition } from "@/hooks/use-awaitable-transition";
import { deleteOrgMutation } from "@/server/actions/organization/mutations";
import { setOrgCookie } from "@/lib/utils";
import { siteUrls } from "@/config/urls";
const confirmationText = "DELETE MY ORG";
const deleteOrgFormSchema = z.object({
confirmation: z
.string({ required_error: `Type "${confirmationText}" to confirms` })
.min(1, `Type "${confirmationText}" to confirms`),
});
export type DeleteOrgFormSchema = z.infer<typeof deleteOrgFormSchema>;
type DeleteYourOrgFormProps = {
fallbackOrgId: string;
};
export function DeleteYourOrgForm({ fallbackOrgId }: DeleteYourOrgFormProps) {
const router = useRouter();
const form = useForm<DeleteOrgFormSchema>({
resolver: zodResolver(deleteOrgFormSchema),
});
const { isPending: isMutatePending, mutateAsync } = useMutation({
mutationFn: () => deleteOrgMutation(),
});
const [isPending, startAwaitableTransition] = useAwaitableTransition();
async function onSubmit(data: DeleteOrgFormSchema) {
if (data.confirmation !== confirmationText) {
return form.setError("confirmation", {
message: `Type "${confirmationText}" to confirms`,
});
}
try {
await mutateAsync();
await startAwaitableTransition(() => {
setOrgCookie(fallbackOrgId);
router.refresh();
form.reset();
});
router.push(siteUrls.dashboard.home);
toast.success("Org deleted successfully");
} catch (error: unknown) {
toast.error(
(error as { message?: string })?.message ??
"Could not delete the org",
);
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle>Delete Org</CardTitle>
<CardDescription>
Type{" "}
<span className="font-bold">
{confirmationText}
</span>{" "}
to permanently delete your account.
</CardDescription>
</CardHeader>
<CardContent>
<FormField
control={form.control}
name="confirmation"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
placeholder={confirmationText}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
<CardFooter>
<Button
disabled={isMutatePending || isPending}
variant="destructive"
type="submit"
className="gap-2"
>
{isPending || isMutatePending ? (
<Icons.loader className="h-4 w-4" />
) : null}
<span>Delete My Org</span>
</Button>
</CardFooter>
</Card>
</form>
</Form>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/settings/_components/org-delete-form.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/settings/_components/org-delete-form.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 2484
} | 7 |
import * as React from "react";
import { CheckIcon, PlusCircledIcon } from "@radix-ui/react-icons";
import { type Column } from "@tanstack/react-table";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Separator } from "@/components/ui/separator";
import type { Option } from "@/types/data-table";
interface DataTableFacetedFilterProps<TData, TValue> {
column?: Column<TData, TValue>;
title?: string;
options: Option[];
}
export function DataTableFacetedFilter<TData, TValue>({
column,
title,
options,
}: DataTableFacetedFilterProps<TData, TValue>) {
const selectedValues = new Set(column?.getFilterValue() as string[]);
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
size="sm"
className="h-8 border-dashed"
>
<PlusCircledIcon className="mr-2 h-4 w-4" />
{title}
{selectedValues?.size > 0 && (
<>
<Separator
orientation="vertical"
className="mx-2 h-4"
/>
<Badge
variant="secondary"
className="rounded-sm px-1 font-normal lg:hidden"
>
{selectedValues.size}
</Badge>
<div className="hidden space-x-1 lg:flex">
{selectedValues.size > 2 ? (
<Badge
variant="secondary"
className="rounded-sm px-1 font-normal"
>
{selectedValues.size} selected
</Badge>
) : (
options
.filter((option) =>
selectedValues.has(option.value),
)
.map((option) => (
<Badge
variant="secondary"
key={option.value}
className="rounded-sm px-1 font-normal"
>
{option.label}
</Badge>
))
)}
</div>
</>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0" align="start">
<Command>
<CommandInput placeholder={title} />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup>
{options.map((option) => {
const isSelected = selectedValues.has(
option.value,
);
return (
<CommandItem
key={option.value}
onSelect={() => {
if (isSelected) {
selectedValues.delete(
option.value,
);
} else {
selectedValues.add(
option.value,
);
}
const filterValues =
Array.from(selectedValues);
column?.setFilterValue(
filterValues.length
? filterValues
: undefined,
);
}}
>
<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={cn("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>
{selectedValues.size > 0 && (
<>
<CommandSeparator />
<CommandGroup>
<CommandItem
onSelect={() =>
column?.setFilterValue(undefined)
}
className="justify-center text-center"
>
Clear filters
</CommandItem>
</CommandGroup>
</>
)}
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/_components/data-table-faceted-filter.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/_components/data-table-faceted-filter.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 5149
} | 8 |
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { siteUrls } from "@/config/urls";
import {
type UserDropdownNavItems,
userDropdownConfig,
} from "@/config/user-dropdown";
import { cn } from "@/lib/utils";
import { usersRoleEnum } from "@/server/db/schema";
import { LogOutIcon } from "lucide-react";
import { type User } from "next-auth";
import Link from "next/link";
import { Fragment } from "react";
import { z } from "zod";
import { SignoutTrigger } from "@/components/signout-trigger";
/**
* to @add more navigation items to the user dropdown, you can add more items to the `userDropdownConfig` object in the
* @see /src/config/user-dropdown.ts file
*/
type UserDropdownProps = {
user: User | null;
};
const userRoles = z.enum(usersRoleEnum.enumValues);
export async function UserDropdown({ user }: UserDropdownProps) {
const navItems =
user?.role === userRoles.Values.Admin ||
user?.role === userRoles.Values["Super Admin"]
? userDropdownConfig.navigation
: userDropdownConfig.filterNavItems({
removeIds: [userDropdownConfig.navIds.admin],
});
return <UserDropdownContent user={user} navItems={navItems} />;
}
type UserDropdownContentProps = {
user: User | null;
navItems: UserDropdownNavItems[];
};
function UserDropdownContent({ user, navItems }: UserDropdownContentProps) {
const isCollapsed = false;
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className={cn(
"flex w-full justify-start gap-2 overflow-hidden p-2",
)}
aria-label="user dropdown"
>
<Avatar className="h-6 w-6">
<AvatarImage src={user!.image ?? ""} />
<AvatarFallback className="text-xs">
{user?.email?.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
{!isCollapsed && (
<span className="truncate">{user?.email}</span>
)}
<span className="sr-only">user menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-60" align="start">
<DropdownMenuLabel className="flex w-56 flex-col items-start gap-2">
<Avatar className="h-9 w-9">
<AvatarImage src={user!.image ?? ""} />
<AvatarFallback>
{user?.email?.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex w-full flex-col">
<p className="truncate text-sm">
{user?.name ?? "Name not found"}
</p>
<p className="w-full truncate text-sm font-light text-muted-foreground">
{user?.email}
</p>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
{/**
* to @add more navigation items to the user dropdown, you can add more items to the `userDropdownConfig` object in the
* @see /src/config/user-dropdown.ts file
*/}
{navItems.map((nav) => (
<Fragment key={nav.id}>
<DropdownMenuLabel>{nav.label}</DropdownMenuLabel>
{nav.items.map((item) => (
<DropdownMenuItem key={item.label} asChild>
<Link
href={item.href}
className="flex w-full cursor-pointer items-center gap-2"
>
<item.icon className="h-4 w-4" />
<span>{item.label}</span>
</Link>
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
</Fragment>
))}
<SignoutTrigger callbackUrl={siteUrls.home} asChild>
<DropdownMenuItem asChild>
<button className="flex w-full cursor-pointer items-center gap-2 text-red-500 ">
<LogOutIcon className="h-4 w-4" />
<span>Logout</span>
</button>
</DropdownMenuItem>
</SignoutTrigger>
</DropdownMenuContent>
</DropdownMenu>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/_components/user-dropdown.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/_components/user-dropdown.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 2800
} | 9 |
"use client";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { MoreHorizontalIcon } from "lucide-react";
import { toast } from "sonner";
import { type OrganizationsData } from "./columns";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { deleteOrgAdminMutation } from "@/server/actions/organization/mutations";
export function ColumnDropdown({ id }: OrganizationsData) {
const router = useRouter();
const { mutateAsync: deleteUserMutate, isPending: deleteUserIsPending } =
useMutation({
mutationFn: () => deleteOrgAdminMutation({ id }),
onSettled: () => {
router.refresh();
},
});
const deleteUser = () => {
toast.promise(async () => await deleteUserMutate(), {
loading: "Deleting user...",
success: "User deleted!",
error: (e) => {
console.log(e);
return "Failed to delete user.";
},
});
};
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-screen max-w-[12rem]">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={async () => {
await navigator.clipboard.writeText(id);
toast("User ID copied to clipboard");
}}
>
Copy org ID
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
disabled={deleteUserIsPending}
onClick={deleteUser}
className="text-red-600"
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/organizations/_components/column-dropdown.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/organizations/_components/column-dropdown.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 1207
} | 10 |
"use client";
import { DataTable } from "@/app/(app)/_components/data-table";
import { type ColumnDef } from "@tanstack/react-table";
import React, { useMemo } from "react";
import { getColumns, type WaitlistData } from "./columns";
import { useDataTable } from "@/hooks/use-data-table";
import type { DataTableSearchableColumn } from "@/types/data-table";
import { type getPaginatedWaitlistQuery } from "@/server/actions/waitlist/query";
/** @learn more about data-table at shadcn ui website @see https://ui.shadcn.com/docs/components/data-table */
type WaitlistTableProps = {
waitlistPromise: ReturnType<typeof getPaginatedWaitlistQuery>;
};
const searchableColumns: DataTableSearchableColumn<WaitlistData>[] = [
{ id: "email", placeholder: "Search email..." },
];
export function WaitlistTable({ waitlistPromise }: WaitlistTableProps) {
const { data, pageCount, total } = React.use(waitlistPromise);
const columns = useMemo<ColumnDef<WaitlistData, unknown>[]>(
() => getColumns(),
[],
);
const waitlistData: WaitlistData[] = data.map((user) => {
return {
id: user.id,
name: user.name,
email: user.email,
createdAt: user.createdAt,
};
});
const { table } = useDataTable({
data: waitlistData,
columns,
pageCount,
searchableColumns,
});
return (
<DataTable
table={table}
columns={columns}
searchableColumns={searchableColumns}
totalRows={total}
/>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/waitlist/_components/waitlist-table.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/waitlist/_components/waitlist-table.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 636
} | 11 |
export const blogPageConfig = {
title: "Blog",
} as const;
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(web)/blogs/_constants/page-config.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(web)/blogs/_constants/page-config.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 22
} | 12 |
"use client";
import { Button } from "@/components/ui/button";
import { Icons } from "@/components/ui/icons";
import { siteUrls } from "@/config/urls";
import { signIn } from "next-auth/react";
import { useState } from "react";
import { toast } from "sonner";
/**
For additional social logins:
- Create a new button for each additional social login. Ensure to use the `variant="outline"` property and set the icon to represent the respective social platform.
- Add the corresponding configuration for each new social login in the `next-auth` configuration file located at /server/auth.ts
For more information on providers, refer to the `next-auth` documentation: @see https://next-auth.js.org/providers
*/
export function SocialLogins() {
const [isLoading, setIsLoading] = useState(false);
const githubLogin = async () => {
setIsLoading(true);
try {
await signIn("github", {
callbackUrl: siteUrls.dashboard.home,
redirect: true,
});
} catch (error) {
toast.error("An error occurred. Please try again later.");
} finally {
setIsLoading(false);
}
};
const googleLogin = async () => {
setIsLoading(true);
try {
await signIn("google", {
callbackUrl: siteUrls.dashboard.home,
redirect: true,
});
} catch (error) {
toast.error("An error occurred. Please try again later.");
} finally {
setIsLoading(false);
}
};
return (
<div className="flex flex-col space-y-2">
<Button
onClick={githubLogin}
variant="outline"
className="w-full gap-2"
disabled={isLoading}
>
<Icons.gitHub className="h-3.5 w-3.5 fill-foreground" />
<span>Continue with Github</span>
</Button>
<Button
onClick={googleLogin}
variant="outline"
className="w-full gap-2"
disabled={isLoading}
>
<Icons.google className="h-3.5 w-3.5 fill-foreground" />
<span>Continue with Google</span>
</Button>
</div>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/auth/_components/social-logins.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/auth/_components/social-logins.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 1075
} | 13 |
import { siteConfig } from "@/config/site";
import { siteUrls } from "@/config/urls";
import type { Metadata } from "next";
export const defaultMetadata: Metadata = {
title: {
template: `%s | ${siteConfig.name}`,
default: siteConfig.name,
},
description: siteConfig.description,
metadataBase: new URL(siteUrls.publicUrl),
keywords: [
"Next.js",
"React",
"Next.js Starter kit",
"SaaS Starter Kit",
"Shadcn UI",
],
authors: [{ name: "Ali Farooq", url: "https://twitter.com/alifarooqdev" }],
creator: "AliFarooqDev",
};
export const twitterMetadata: Metadata["twitter"] = {
title: siteConfig.name,
description: siteConfig.description,
card: "summary_large_image",
images: [siteConfig.orgImage],
creator: "@alifarooqdev",
};
export const ogMetadata: Metadata["openGraph"] = {
title: siteConfig.name,
description: siteConfig.description,
type: "website",
images: [{ url: siteConfig.orgImage, alt: siteConfig.name }],
locale: "en_US",
url: siteUrls.publicUrl,
siteName: siteConfig.name,
};
| alifarooq9/rapidlaunch/starterkits/saas/src/app/shared-metadata.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/shared-metadata.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 445
} | 14 |
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-12 rounded-md px-8",
icon: "h-9 w-9",
iconSmall: "h-8 w-8",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
},
);
Button.displayName = "Button";
export { Button, buttonVariants };
| alifarooq9/rapidlaunch/starterkits/saas/src/components/ui/button.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/components/ui/button.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 1002
} | 15 |
/**
* @purpose This file contains all the site urls
*
* To add a new URL:
* 1. Add a new property to the siteUrls object with the URL path.
* 2. Import the siteUrls object from "@/config/urls" in the file where you want to use the URL.
* 3. Use the URL in the file.
*/
export const siteUrls = {
publicUrl: "https://saasdemo.rapidlaunch.xyz",
github: "https://github.com/alifarooq9/rapidlaunch",
home: "/",
pricing: "/pricing",
features: "/features",
support: "/support",
blogs: "/blogs",
docs: "/docs",
changelogs: "/changelogs",
maintenance: "/maintenance",
waitlist: "/waitlist",
rapidlaunch: "https://www.rapidlaunch.xyz",
dashboard: {
home: "/dashboard",
},
feedback: "/feedback",
organization: {
members: {
home: "/org/members",
invite: "/org/members/invite",
},
settings: "/org/settings",
plansAndBilling: "/org/billing",
},
auth: {
login: "/auth/login",
signup: "/auth/signup",
},
admin: {
dashboard: "/admin/dashboard",
users: "/admin/users",
organizations: "/admin/organizations",
settings: "/admin/settings",
waitlist: "/admin/waitlist",
feedbacks: "/admin/feedbacks",
analytics: "https://us.posthog.com/project/12312/dashboard",
},
profile: {
settings: "/profile/settings",
billing: "/profile/billing",
},
} as const;
export const publicRoutes: string[] = [
siteUrls.publicUrl,
siteUrls.home,
siteUrls.pricing,
siteUrls.features,
siteUrls.support,
siteUrls.blogs,
siteUrls.docs,
siteUrls.changelogs,
siteUrls.maintenance,
siteUrls.waitlist,
siteUrls.rapidlaunch,
];
export const protectedRoutes: string[] = [
siteUrls.dashboard.home,
siteUrls.feedback,
siteUrls.organization.members.home,
siteUrls.organization.members.invite,
siteUrls.organization.settings,
siteUrls.organization.plansAndBilling,
siteUrls.auth.login,
siteUrls.auth.signup,
siteUrls.admin.dashboard,
siteUrls.admin.users,
siteUrls.admin.organizations,
siteUrls.admin.settings,
siteUrls.admin.waitlist,
siteUrls.admin.feedbacks,
siteUrls.admin.analytics,
siteUrls.profile.settings,
siteUrls.profile.billing,
];
| alifarooq9/rapidlaunch/starterkits/saas/src/config/urls.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/config/urls.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 989
} | 16 |
"use server";
import { pricingPlans } from "@/config/pricing";
import { siteUrls } from "@/config/urls";
import { env } from "@/env";
import { getAbsoluteUrl } from "@/lib/utils";
import { getOrganizations } from "@/server/actions/organization/queries";
import { getUser } from "@/server/auth";
import { db } from "@/server/db";
import { subscriptions } from "@/server/db/schema";
import { configureLemonSqueezy } from "@/server/lemonsqueezy";
import { protectedProcedure } from "@/server/procedures";
import {
createCheckout,
getSubscription,
listSubscriptions,
listOrders,
type Subscription,
} from "@lemonsqueezy/lemonsqueezy.js";
import { eq } from "drizzle-orm";
import { redirect } from "next/navigation";
import { eachMonthOfInterval, format, startOfMonth, subMonths } from "date-fns";
export async function getCheckoutURL(variantId?: number, embed = false) {
await protectedProcedure();
configureLemonSqueezy();
const user = await getUser();
const { currentOrg } = await getOrganizations();
if (!user || !currentOrg) {
return redirect(siteUrls.auth.login);
}
if (!variantId) {
return redirect(siteUrls.dashboard.home);
}
const checkout = await createCheckout(
env.LEMONSQUEEZY_STORE_ID,
variantId,
{
checkoutOptions: {
embed,
media: false,
logo: !embed,
dark: true,
},
checkoutData: {
email: currentOrg.email ?? undefined,
custom: {
user_id: user.id,
org_id: currentOrg.id,
},
},
productOptions: {
redirectUrl: getAbsoluteUrl(
siteUrls.organization.plansAndBilling,
),
receiptButtonText: "Go to Dashboard",
receiptThankYouNote: "Thank you for signing up to RapidLaunch!",
},
testMode: true,
},
);
return checkout.data?.data.attributes.url;
}
export async function getOrgSubscription() {
try {
await protectedProcedure();
configureLemonSqueezy();
const { currentOrg } = await getOrganizations();
const orgSubscription = await db.query.subscriptions.findFirst({
where: eq(subscriptions.orgId, currentOrg.id),
});
if (!orgSubscription) {
return null;
}
const lemonSubscription = await getSubscription(
orgSubscription?.lemonSqueezyId,
);
if (!lemonSubscription.data?.data) {
return null;
}
const customerPortalUrl =
lemonSubscription.data.data.attributes.urls.customer_portal;
// add plan details to the subscription
const plan = pricingPlans.find(
(p) =>
p.variantId?.monthly === orgSubscription?.variantId ||
p.variantId?.yearly === orgSubscription?.variantId,
);
return {
...lemonSubscription.data.data.attributes,
lemonSqueezyId: lemonSubscription.data.data.id,
customerPortalUrl,
id: orgSubscription.id,
plan,
};
} catch (error) {
return null;
}
}
type SubscriptionCountByMonth = {
status?: Subscription["data"]["attributes"]["status"];
};
export async function getSubscriptionsCount({
status,
}: SubscriptionCountByMonth) {
await protectedProcedure();
configureLemonSqueezy();
const dateBeforeMonths = subMonths(new Date(), 6);
const startDateOfTheMonth = startOfMonth(dateBeforeMonths);
const subscriptions = await listSubscriptions({
filter: {
storeId: env.LEMONSQUEEZY_STORE_ID,
status,
},
});
const months = eachMonthOfInterval({
start: startDateOfTheMonth,
end: new Date(),
});
const subscriptionsCountByMonth = months.map((month) => {
const monthStr = format(month, "MMM-yyy");
const count =
subscriptions.data?.data.filter(
(subscription) =>
format(
new Date(subscription.attributes.created_at),
"MMM-yyy",
) === monthStr,
)?.length ?? 0;
return { Date: monthStr, SubsCount: count };
});
return {
totalCount: subscriptions.data?.data.length ?? 0,
subscriptionsCountByMonth,
};
}
export async function getRevenueCount() {
await protectedProcedure();
configureLemonSqueezy();
const dateBeforeMonths = subMonths(new Date(), 6);
const startDateOfTheMonth = startOfMonth(dateBeforeMonths);
const orders = await listOrders({
filter: {
storeId: env.LEMONSQUEEZY_STORE_ID,
},
});
const totalRevenue =
orders.data?.data.reduce(
(acc, order) => acc + order.attributes.total,
0,
) ?? 0;
const months = eachMonthOfInterval({
start: startDateOfTheMonth,
end: new Date(),
});
const revenueCountByMonth = months.map((month) => {
const monthStr = format(month, "MMM-yyy");
const revenueCount =
orders.data?.data
.filter(
(order) =>
format(
new Date(order.attributes.created_at),
"MMM-yyy",
) === monthStr,
)
?.reduce((acc, order) => acc + order.attributes.total, 0) ?? 0;
const count = revenueCount / 100;
return { Date: monthStr, RevenueCount: count };
});
return {
totalRevenue: totalRevenue / 100,
revenueCountByMonth,
};
}
| alifarooq9/rapidlaunch/starterkits/saas/src/server/actions/subscription/query.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/server/actions/subscription/query.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 2719
} | 17 |
#!/bin/bash
# Use this script to start a docker container for a local development database
# TO RUN ON WINDOWS:
# 1. Install WSL (Windows Subsystem for Linux) - https://learn.microsoft.com/en-us/windows/wsl/install
# 2. Install Docker Desktop for Windows - https://docs.docker.com/docker-for-windows/install/
# 3. Open WSL - `wsl`
# 4. Run this script - `./start-database.sh`
# On Lunux and macOS you can run this script directly - `./start-database.sh`
DB_CONTAINER_NAME="demo-postgres"
if ! [ -x "$(command -v docker)" ]; then
echo "Docker is not installed. Please install docker and try again.\nDocker install guide: https://docs.docker.com/engine/install/"
exit 1
fi
if [ "$(docker ps -q -f name=$DB_CONTAINER_NAME)" ]; then
docker start $DB_CONTAINER_NAME
echo "Database container started"
exit 0
fi
# import env variables from .env
set -a
source .env
DB_PASSWORD=$(echo $DATABASE_URL | awk -F':' '{print $3}' | awk -F'@' '{print $1}')
if [ "$DB_PASSWORD" = "password" ]; then
echo "You are using the default database password"
read -p "Should we generate a random password for you? [y/N]: " -r REPLY
if ! [[ $REPLY =~ ^[Yy]$ ]]; then
echo "Please set a password in the .env file and try again"
exit 1
fi
DB_PASSWORD=$(openssl rand -base64 12)
sed -i -e "s/:password@/:$DB_PASSWORD@/" .env
fi
docker run --name $DB_CONTAINER_NAME -e POSTGRES_PASSWORD=$DB_PASSWORD -e POSTGRES_DB=demo -d -p 5432:5432 docker.io/postgres
echo "Database container was succesfuly created"
| alifarooq9/rapidlaunch/starterkits/saas/start-database.sh | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/start-database.sh",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 542
} | 18 |
'use client';
import { Button } from '@/components/ui/button';
import { signInWithPassword } from '@/utils/auth-helpers/server';
import { handleRequest } from '@/utils/auth-helpers/client';
import { useRouter } from 'next/navigation';
import React, { useState } from 'react';
import { Input } from '../ui/input';
// Define prop type with allowEmail boolean
interface PasswordSignInProps {
allowEmail: boolean;
redirectMethod: string;
}
export default function PasswordSignIn({
allowEmail,
redirectMethod
}: PasswordSignInProps) {
const router = redirectMethod === 'client' ? useRouter() : null;
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
setIsSubmitting(true); // Disable the button while the request is being handled
await handleRequest(e, signInWithPassword, router);
setIsSubmitting(false);
};
return (
<div>
<form
noValidate={true}
className="mb-4"
onSubmit={(e) => handleSubmit(e)}
>
<div className="grid gap-2">
<div className="grid gap-1">
<label className="text-zinc-950 dark:text-white" htmlFor="email">
Email
</label>
<Input
className="mr-2.5 mb-2 h-full min-h-[44px] w-full px-4 py-3 focus:outline-0 dark:placeholder:text-zinc-400"
id="email"
placeholder="[email protected]"
type="email"
name="email"
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
/>
<label
className="text-zinc-950 mt-2 dark:text-white"
htmlFor="password"
>
Password
</label>
<Input
id="password"
placeholder="Password"
type="password"
name="password"
autoComplete="current-password"
className="mr-2.5 mb-2 h-full min-h-[44px] w-full px-4 py-3 focus:outline-0 dark:placeholder:text-zinc-400"
/>
</div>
<Button
type="submit"
className="mt-2 flex h-[unset] w-full items-center justify-center rounded-lg px-4 py-4 text-sm font-medium"
>
{isSubmitting ? (
<svg
aria-hidden="true"
role="status"
className="mr-2 inline h-4 w-4 animate-spin text-zinc-200 duration-500 dark:text-zinc-950"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
></path>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="white"
></path>
</svg>
) : (
'Sign in'
)}
</Button>
</div>
</form>
<p>
<a
href="/dashboard/signin/forgot_password"
className="font-medium text-zinc-950 dark:text-white text-sm"
>
Forgot your password?
</a>
</p>
{allowEmail && (
<p>
<a
href="/dashboard/signin/email_signin"
className="font-medium text-zinc-950 dark:text-white text-sm"
>
Sign in via magic link
</a>
</p>
)}
<p>
<a
href="/dashboard/signin/signup"
className="font-medium text-zinc-950 dark:text-white text-sm"
>
Don't have an account? Sign up
</a>
</p>
</div>
);
}
| horizon-ui/shadcn-nextjs-boilerplate/components/auth-ui/PasswordSignIn.tsx | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/components/auth-ui/PasswordSignIn.tsx",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 2446
} | 19 |
import { type NextRequest } from 'next/server';
import { updateSession } from '@/utils/supabase/middleware';
export async function middleware(request: NextRequest) {
return await updateSession(request);
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - images - .svg, .png, .jpg, .jpeg, .gif, .webp
* Feel free to modify this pattern to include more paths.
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'
]
}; | horizon-ui/shadcn-nextjs-boilerplate/middleware.ts | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/middleware.ts",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 239
} | 20 |
# A string used to distinguish different Supabase projects on the same host. Defaults to the working
# directory name when running `supabase init`.
project_id = "horizon-ui-shadcn"
[api]
# Port to use for the API URL.
port = 54321
# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
# endpoints. public and storage are always included.
schemas = ["public", "graphql_public"]
# Extra schemas to add to the search_path of every request. public is always included.
extra_search_path = ["public", "extensions"]
# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
# for accidental or malicious requests.
max_rows = 1000
[db]
# Port to use for the local database URL.
port = 54322
# The database major version to use. This has to be the same as your remote database's. Run `SHOW
# server_version;` on the remote database to check.
major_version = 15
[studio]
# Port to use for Supabase Studio.
port = 54323
# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
# are monitored, and you can view the emails that would have been sent from the web interface.
[inbucket]
# Port to use for the email testing server web interface.
port = 54324
smtp_port = 54325
pop3_port = 54326
[storage]
# The maximum file size allowed (e.g. "5MB", "500KB").
file_size_limit = "50MiB"
[auth]
# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
# in emails.
site_url = "http://localhost:3000"
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
additional_redirect_urls = ["https://localhost:3000"]
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one
# week).
jwt_expiry = 3600
# Allow/disallow new user signups to your project.
enable_signup = true
[auth.email]
# Allow/disallow new user signups via email to your project.
enable_signup = true
# If enabled, a user will be required to confirm any email change on both the old, and new email
# addresses. If disabled, only the new email is required to confirm.
double_confirm_changes = true
# If enabled, users need to confirm their email address before signing in.
enable_confirmations = true
# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin`, `notion`, `twitch`,
# `twitter`, `slack`, `spotify`, `workos`, `zoom`.
[auth.external.google]
enabled = true
client_id = "************************************************"
secret = "***********************************************"
# Overrides the default auth redirectUrl.
redirect_uri = "http://127.0.0.1:54321/auth/v1/callback"
# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
# or any other third-party OIDC providers.
url = ""
[analytics]
enabled = false
port = 54327
vector_port = 54328
# Setup BigQuery project to enable log viewer on local development stack.
# See: https://supabase.com/docs/guides/getting-started/local-development#enabling-local-logging
gcp_project_id = ""
gcp_project_number = ""
gcp_jwt_path = "supabase/gcloud.json"
| horizon-ui/shadcn-nextjs-boilerplate/supabase/config.toml.example | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/supabase/config.toml.example",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 951
} | 21 |
import { loadStripe, Stripe } from '@stripe/stripe-js';
let stripePromise: Promise<Stripe | null>;
export const getStripe = () => {
if (!stripePromise) {
stripePromise = loadStripe(
process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY_LIVE ??
process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ??
''
);
}
return stripePromise;
};
| horizon-ui/shadcn-nextjs-boilerplate/utils/stripe/client.ts | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/utils/stripe/client.ts",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 158
} | 22 |
import type { StorybookConfig } from '@storybook/nextjs';
const config: StorybookConfig = {
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: [
'@storybook/addon-onboarding',
'@storybook/addon-links',
'@storybook/addon-essentials',
'@storybook/addon-interactions',
],
framework: {
name: '@storybook/nextjs',
options: {},
},
staticDirs: ['../public'],
core: {
disableTelemetry: true,
},
};
export default config;
| ixartz/SaaS-Boilerplate/.storybook/main.ts | {
"file_path": "ixartz/SaaS-Boilerplate/.storybook/main.ts",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 195
} | 23 |
import antfu from '@antfu/eslint-config';
import nextPlugin from '@next/eslint-plugin-next';
import jestDom from 'eslint-plugin-jest-dom';
import jsxA11y from 'eslint-plugin-jsx-a11y';
import playwright from 'eslint-plugin-playwright';
import simpleImportSort from 'eslint-plugin-simple-import-sort';
import tailwind from 'eslint-plugin-tailwindcss';
import testingLibrary from 'eslint-plugin-testing-library';
export default antfu({
react: true,
typescript: true,
lessOpinionated: true,
isInEditor: false,
stylistic: {
semi: true,
},
formatters: {
css: true,
},
ignores: [
'migrations/**/*',
'next-env.d.ts',
],
}, ...tailwind.configs['flat/recommended'], jsxA11y.flatConfigs.recommended, {
plugins: {
'@next/next': nextPlugin,
},
rules: {
...nextPlugin.configs.recommended.rules,
...nextPlugin.configs['core-web-vitals'].rules,
},
}, {
plugins: {
'simple-import-sort': simpleImportSort,
},
rules: {
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error',
},
}, {
files: [
'**/*.test.ts?(x)',
],
...testingLibrary.configs['flat/react'],
...jestDom.configs['flat/recommended'],
}, {
files: [
'**/*.spec.ts',
'**/*.e2e.ts',
],
...playwright.configs['flat/recommended'],
}, {
rules: {
'import/order': 'off', // Avoid conflicts with `simple-import-sort` plugin
'sort-imports': 'off', // Avoid conflicts with `simple-import-sort` plugin
'style/brace-style': ['error', '1tbs'], // Use the default brace style
'ts/consistent-type-definitions': ['error', 'type'], // Use `type` instead of `interface`
'react/prefer-destructuring-assignment': 'off', // Vscode doesn't support automatically destructuring, it's a pain to add a new variable
'node/prefer-global/process': 'off', // Allow using `process.env`
'test/padding-around-all': 'error', // Add padding in test files
'test/prefer-lowercase-title': 'off', // Allow using uppercase titles in test titles
},
});
| ixartz/SaaS-Boilerplate/eslint.config.mjs | {
"file_path": "ixartz/SaaS-Boilerplate/eslint.config.mjs",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 751
} | 24 |
import type { MetadataRoute } from 'next';
import { getBaseUrl } from '@/utils/Helpers';
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: `${getBaseUrl()}/`,
lastModified: new Date(),
changeFrequency: 'daily',
priority: 0.7,
},
// Add more URLs here
];
}
| ixartz/SaaS-Boilerplate/src/app/sitemap.ts | {
"file_path": "ixartz/SaaS-Boilerplate/src/app/sitemap.ts",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 129
} | 25 |
import { badgeVariants } from '@/components/ui/badgeVariants';
export const CenteredHero = (props: {
banner: {
href: string;
text: React.ReactNode;
};
title: React.ReactNode;
description: string;
buttons: React.ReactNode;
}) => (
<>
<div className="text-center">
<a
className={badgeVariants()}
href={props.banner.href}
target="_blank"
rel="noopener"
>
{props.banner.text}
</a>
</div>
<div className="mt-3 text-center text-5xl font-bold tracking-tight">
{props.title}
</div>
<div className="mx-auto mt-5 max-w-screen-md text-center text-xl text-muted-foreground">
{props.description}
</div>
<div className="mt-8 flex justify-center gap-x-5 gap-y-3 max-sm:flex-col">
{props.buttons}
</div>
</>
);
| ixartz/SaaS-Boilerplate/src/features/landing/CenteredHero.tsx | {
"file_path": "ixartz/SaaS-Boilerplate/src/features/landing/CenteredHero.tsx",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 381
} | 26 |
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
import {
type NextFetchEvent,
type NextRequest,
NextResponse,
} from 'next/server';
import createMiddleware from 'next-intl/middleware';
import { AllLocales, AppConfig } from './utils/AppConfig';
const intlMiddleware = createMiddleware({
locales: AllLocales,
localePrefix: AppConfig.localePrefix,
defaultLocale: AppConfig.defaultLocale,
});
const isProtectedRoute = createRouteMatcher([
'/dashboard(.*)',
'/:locale/dashboard(.*)',
'/onboarding(.*)',
'/:locale/onboarding(.*)',
'/api(.*)',
'/:locale/api(.*)',
]);
export default function middleware(
request: NextRequest,
event: NextFetchEvent,
) {
if (
request.nextUrl.pathname.includes('/sign-in')
|| request.nextUrl.pathname.includes('/sign-up')
|| isProtectedRoute(request)
) {
return clerkMiddleware((auth, req) => {
const authObj = auth();
if (isProtectedRoute(req)) {
const locale
= req.nextUrl.pathname.match(/(\/.*)\/dashboard/)?.at(1) ?? '';
const signInUrl = new URL(`${locale}/sign-in`, req.url);
authObj.protect({
// `unauthenticatedUrl` is needed to avoid error: "Unable to find `next-intl` locale because the middleware didn't run on this request"
unauthenticatedUrl: signInUrl.toString(),
});
}
if (
authObj.userId
&& !authObj.orgId
&& req.nextUrl.pathname.includes('/dashboard')
&& !req.nextUrl.pathname.endsWith('/organization-selection')
) {
const orgSelection = new URL(
'/onboarding/organization-selection',
req.url,
);
return NextResponse.redirect(orgSelection);
}
return intlMiddleware(req);
})(request, event);
}
return intlMiddleware(request);
}
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next|monitoring).*)', '/', '/(api|trpc)(.*)'], // Also exclude tunnelRoute used in Sentry from the matcher
};
| ixartz/SaaS-Boilerplate/src/middleware.ts | {
"file_path": "ixartz/SaaS-Boilerplate/src/middleware.ts",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 797
} | 27 |
import type { OrgPermission, OrgRole } from '@/types/Auth';
// Use type safe message keys with `next-intl`
type Messages = typeof import('../locales/en.json');
// eslint-disable-next-line ts/consistent-type-definitions
declare interface IntlMessages extends Messages {}
declare global {
// eslint-disable-next-line ts/consistent-type-definitions
interface ClerkAuthorization {
permission: OrgPermission;
role: OrgRole;
}
}
| ixartz/SaaS-Boilerplate/src/types/global.d.ts | {
"file_path": "ixartz/SaaS-Boilerplate/src/types/global.d.ts",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 144
} | 28 |
ISC License
Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
| lucide-icons/lucide/LICENSE | {
"file_path": "lucide-icons/lucide/LICENSE",
"repo_id": "lucide-icons/lucide",
"token_count": 241
} | 29 |
import { createLucideIcon } from 'lucide-react/src/lucide-react';
import { type LucideProps, type IconNode } from 'lucide-react/src/createLucideIcon';
import { IconEntity } from '../theme/types';
import { renderToStaticMarkup } from 'react-dom/server';
import { IconContent } from './generateZip';
const getFallbackZip = (icons: IconEntity[], params: LucideProps) => {
return icons.map<IconContent>((icon) => {
const Icon = createLucideIcon(icon.name, icon.iconNode as IconNode);
const src = renderToStaticMarkup(<Icon {...params} />);
return [icon.name, src];
});
};
export default getFallbackZip;
| lucide-icons/lucide/docs/.vitepress/lib/getFallbackZip.tsx | {
"file_path": "lucide-icons/lucide/docs/.vitepress/lib/getFallbackZip.tsx",
"repo_id": "lucide-icons/lucide",
"token_count": 205
} | 30 |
export default {
async load() {
return {
packages: [
{
name: 'lucide',
logo: '/framework-logos/js.svg',
label: 'Lucide documentation for JavaScript',
},
{
name: 'lucide-react',
logo: '/framework-logos/react.svg',
label: 'Lucide documentation for React',
},
{
name: 'lucide-vue-next',
logo: '/framework-logos/vue.svg',
label: 'Lucide documentation for Vue 3',
},
{
name: 'lucide-svelte',
logo: '/framework-logos/svelte.svg',
label: 'Lucide documentation for Svelte',
},
{
name: 'lucide-preact',
logo: '/framework-logos/preact.svg',
label: 'Lucide documentation for Preact',
},
{
name: 'lucide-solid',
logo: '/framework-logos/solid.svg',
label: 'Lucide documentation for Solid',
},
{
name: 'lucide-angular',
logo: '/framework-logos/angular.svg',
label: 'Lucide documentation for Angular',
},
{
name: 'lucide-react-native',
logo: '/framework-logos/react-native.svg',
label: 'Lucide documentation for React Native',
},
{
name: 'lucide-flutter',
logo: '/framework-logos/flutter.svg',
label: 'Lucide documentation for Flutter',
},
],
};
},
};
| lucide-icons/lucide/docs/.vitepress/theme/components/home/HomePackagesSection.data.ts | {
"file_path": "lucide-icons/lucide/docs/.vitepress/theme/components/home/HomePackagesSection.data.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 774
} | 31 |
import { useDebounce } from '@vueuse/core';
import { nextTick, onMounted, ref, watch } from 'vue';
const useSearchInput = () => {
const searchInput = ref();
const searchQuery = ref<string>('');
const searchQueryDebounced = useDebounce<string>(searchQuery, 200);
watch(searchQueryDebounced, (searchString) => {
const newUrl = new URL(window.location.href);
if (searchString === '') {
newUrl.searchParams.delete('search');
} else {
newUrl.searchParams.set('search', searchString);
}
nextTick(() => {
window.history.replaceState({}, '', newUrl);
});
});
onMounted(() => {
const searchParams = new URLSearchParams(window.location.search);
if (searchParams.has('search')) {
searchQuery.value = searchParams.get('search');
}
if (searchParams.has('focus')) {
searchInput.value.focus();
}
});
return {
searchInput,
searchQuery,
searchQueryDebounced,
};
};
export default useSearchInput;
| lucide-icons/lucide/docs/.vitepress/theme/composables/useSearchInput.ts | {
"file_path": "lucide-icons/lucide/docs/.vitepress/theme/composables/useSearchInput.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 364
} | 32 |
.star-rating {
position: relative;
}
.stars {
display: flex;
gap: 4px;
}
.rating {
position: absolute;
top: 0;
}
| lucide-icons/lucide/docs/guide/advanced/examples/filled-icon-example/icon.css | {
"file_path": "lucide-icons/lucide/docs/guide/advanced/examples/filled-icon-example/icon.css",
"repo_id": "lucide-icons/lucide",
"token_count": 53
} | 33 |
/* eslint-disable global-require, func-names */
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma'),
],
client: {
jasmine: {
// you can add configuration options for Jasmine here
// the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false, // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true, // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, '../../coverage/lucide-angular'),
subdir: '.',
reporters: [{ type: 'html' }, { type: 'text-summary' }],
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessCI'],
customLaunchers: {
ChromeHeadlessCI: {
base: 'ChromeHeadless',
flags: ['--no-sandbox'],
},
},
singleRun: false,
restartOnFileChange: true,
});
};
| lucide-icons/lucide/packages/lucide-angular/karma.conf.js | {
"file_path": "lucide-icons/lucide/packages/lucide-angular/karma.conf.js",
"repo_id": "lucide-icons/lucide",
"token_count": 619
} | 34 |
import { createElement, forwardRef } from 'react';
import defaultAttributes from './defaultAttributes';
import { IconNode, LucideProps } from './types';
import { mergeClasses } from '@lucide/shared';
interface IconComponentProps extends LucideProps {
iconNode: IconNode;
}
/**
* Lucide icon component
*
* @component Icon
* @param {object} props
* @param {string} props.color - The color of the icon
* @param {number} props.size - The size of the icon
* @param {number} props.strokeWidth - The stroke width of the icon
* @param {boolean} props.absoluteStrokeWidth - Whether to use absolute stroke width
* @param {string} props.className - The class name of the icon
* @param {IconNode} props.children - The children of the icon
* @param {IconNode} props.iconNode - The icon node of the icon
*
* @returns {ForwardRefExoticComponent} LucideIcon
*/
const Icon = forwardRef<SVGSVGElement, IconComponentProps>(
(
{
color = 'currentColor',
size = 24,
strokeWidth = 2,
absoluteStrokeWidth,
className = '',
children,
iconNode,
...rest
},
ref,
) => {
return createElement(
'svg',
{
ref,
...defaultAttributes,
width: size,
height: size,
stroke: color,
strokeWidth: absoluteStrokeWidth ? (Number(strokeWidth) * 24) / Number(size) : strokeWidth,
className: mergeClasses('lucide', className),
...rest,
},
[
...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),
...(Array.isArray(children) ? children : [children]),
],
);
},
);
export default Icon;
| lucide-icons/lucide/packages/lucide-react/src/Icon.ts | {
"file_path": "lucide-icons/lucide/packages/lucide-react/src/Icon.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 611
} | 35 |
import { describe, it, expect, afterEach } from 'vitest';
import { render, cleanup } from '@testing-library/svelte';
import { Smile, Pen, Edit2 } from '../src/lucide-svelte';
import TestSlots from './TestSlots.svelte';
describe('Using lucide icon components', () => {
afterEach(() => cleanup());
it('should render an component', () => {
const { container } = render(Smile);
expect(container).toMatchSnapshot();
});
it('should adjust the size, stroke color and stroke width', () => {
const { container } = render(Smile, {
props: {
size: 48,
color: 'red',
strokeWidth: 4,
},
});
expect(container).toMatchSnapshot();
});
it('should add a class to the element', () => {
const testClass = 'my-icon';
render(Smile, {
props: {
class: testClass,
},
});
const [icon] = document.getElementsByClassName(testClass);
expect(icon).toBeInTheDocument();
expect(icon).toMatchSnapshot();
expect(icon).toHaveClass(testClass);
expect(icon).toHaveClass('lucide');
expect(icon).toHaveClass('lucide-smile');
});
it('should add a style attribute to the element', () => {
render(Smile, {
props: {
style: 'position: absolute;',
},
});
const [icon] = document.getElementsByClassName('lucide');
expect(icon.getAttribute('style')).toContain('position: absolute');
});
it('should render an icon slot', () => {
const { container, getByText } = render(TestSlots);
const textElement = getByText('Test');
expect(textElement).toBeInTheDocument();
expect(container).toMatchSnapshot();
});
it('should render the alias icon', () => {
const { container } = render(Pen);
const PenIconRenderedHTML = container.innerHTML;
cleanup();
const { container: Edit2Container } = render(Edit2);
expect(PenIconRenderedHTML).toBe(Edit2Container.innerHTML);
});
it('should not scale the strokeWidth when absoluteStrokeWidth is set', () => {
const testId = 'smile-icon';
const { container, getByTestId } = render(Smile, {
'data-testid': testId,
color: 'red',
size: 48,
absoluteStrokeWidth: true,
});
const { attributes } = getByTestId(testId) as unknown as {
attributes: Record<string, { value: string }>;
};
expect(attributes.stroke.value).toBe('red');
expect(attributes.width.value).toBe('48');
expect(attributes.height.value).toBe('48');
expect(attributes['stroke-width'].value).toBe('1');
expect(container.innerHTML).toMatchSnapshot();
});
});
| lucide-icons/lucide/packages/lucide-svelte/tests/lucide-svelte.spec.ts | {
"file_path": "lucide-icons/lucide/packages/lucide-svelte/tests/lucide-svelte.spec.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 951
} | 36 |
import replaceElement from './replaceElement';
import * as iconAndAliases from './iconsAndAliases';
/**
* Replaces all elements with matching nameAttr with the defined icons
* @param {{ icons?: object, nameAttr?: string, attrs?: object }} options
*/
const createIcons = ({ icons = {}, nameAttr = 'data-lucide', attrs = {} } = {}) => {
if (!Object.values(icons).length) {
throw new Error(
"Please provide an icons object.\nIf you want to use all the icons you can import it like:\n `import { createIcons, icons } from 'lucide';\nlucide.createIcons({icons});`",
);
}
if (typeof document === 'undefined') {
throw new Error('`createIcons()` only works in a browser environment.');
}
const elementsToReplace = document.querySelectorAll(`[${nameAttr}]`);
Array.from(elementsToReplace).forEach((element) =>
replaceElement(element, { nameAttr, icons, attrs }),
);
/** @todo: remove this block in v1.0 */
if (nameAttr === 'data-lucide') {
const deprecatedElements = document.querySelectorAll('[icon-name]');
if (deprecatedElements.length > 0) {
console.warn(
'[Lucide] Some icons were found with the now deprecated icon-name attribute. These will still be replaced for backwards compatibility, but will no longer be supported in v1.0 and you should switch to data-lucide',
);
Array.from(deprecatedElements).forEach((element) =>
replaceElement(element, { nameAttr: 'icon-name', icons, attrs }),
);
}
}
};
export { createIcons };
/*
Create Element function export.
*/
export { default as createElement } from './createElement';
/*
Icons exports.
*/
export { iconAndAliases as icons };
export * from './icons';
export * from './aliases';
/*
Types exports.
*/
export * from './types';
| lucide-icons/lucide/packages/lucide/src/lucide.ts | {
"file_path": "lucide-icons/lucide/packages/lucide/src/lucide.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 588
} | 37 |
import path from 'path';
import fs from 'fs';
import { promisify } from 'util';
import simpleGit from 'simple-git';
/**
* Renames an icon and adds the old name as an alias.
* @param {string} ICONS_DIR
* @param {string} oldName
* @param {string} newName
* @param {boolean} logInfo
* @param {boolean} addAlias
*/
export async function renameIcon(ICONS_DIR, oldName, newName, logInfo = true, addAlias = true) {
const git = simpleGit();
async function fileExists(filePath) {
try {
await promisify(fs.access)(filePath);
return true;
} catch {
return false;
}
}
const oldSvgPath = path.join(ICONS_DIR, `${oldName}.svg`);
const newSvgPath = path.join(ICONS_DIR, `${newName}.svg`);
const oldJsonPath = path.join(ICONS_DIR, `${oldName}.json`);
const newJsonPath = path.join(ICONS_DIR, `${newName}.json`);
if (await fileExists(newSvgPath)) {
throw new Error(`ERROR: Icon icons/${newName}.svg already exists`);
}
if (await fileExists(newJsonPath)) {
throw new Error(`ERROR: Metadata file icons/${newName}.json already exists`);
}
if (!(await fileExists(oldSvgPath))) {
throw new Error(`ERROR: Icon icons/${oldName}.svg doesn't exist`);
}
if (!(await fileExists(oldJsonPath))) {
throw new Error(`ERROR: Metadata file icons/${oldName}.json doesn't exist`);
}
await git.mv(oldSvgPath, newSvgPath);
await git.mv(oldJsonPath, newJsonPath);
if (addAlias) {
const json = fs.readFileSync(newJsonPath, 'utf8');
const jsonData = JSON.parse(json);
if (Array.isArray(jsonData.aliases)) {
jsonData.aliases = jsonData.aliases.filter(
(alias) => (typeof alias === 'string' ? alias : alias.name) !== newName,
);
jsonData.aliases.push(oldName);
} else {
jsonData.aliases = [oldName];
}
fs.writeFileSync(newJsonPath, JSON.stringify(jsonData, null, 2));
await git.add(newJsonPath);
}
if (logInfo) {
console.log('SUCCESS: Next steps:');
console.log(`git checkout -b rename/${oldName}-to-${newName};`);
console.log(`git commit -m 'Renamed ${oldName} to ${newName}';`);
console.log(`gh pr create --title 'Renamed ${oldName} to ${newName}';`);
console.log('git checkout main;');
}
}
| lucide-icons/lucide/scripts/rename/renameIcon.function.mjs | {
"file_path": "lucide-icons/lucide/scripts/rename/renameIcon.function.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 866
} | 38 |
/* eslint-disable import/prefer-default-export */
/**
* Merge two arrays and remove duplicates
*
* @param {array} a
* @param {array} b
* @returns {array}
*/
export const mergeArrays = (a, b) => {
a = a.concat(b);
a = a.filter((i, p) => a.indexOf(i) === p);
return a;
};
| lucide-icons/lucide/tools/build-helpers/src/mergeArrays.mjs | {
"file_path": "lucide-icons/lucide/tools/build-helpers/src/mergeArrays.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 110
} | 39 |
import path from 'path';
import fs from 'fs';
// eslint-disable-next-line import/no-extraneous-dependencies
import { toPascalCase, resetFile, appendFile } from '@lucide/helpers';
import { deprecationReasonTemplate } from '../utils/deprecationReasonTemplate.mjs';
const getImportString = (
componentName,
iconName,
aliasImportFileExtension,
deprecated,
deprecationReason = '',
) =>
deprecated
? `export {\n` +
` /** @deprecated ${deprecationReason} */\n` +
` default as ${componentName}\n` +
`} from './icons/${iconName}${aliasImportFileExtension}';\n`
: `export { default as ${componentName} } from './icons/${iconName}${aliasImportFileExtension}';\n`;
export default async function generateAliasesFile({
iconNodes,
outputDirectory,
fileExtension,
iconFileExtension = '.js',
iconMetaData,
aliasImportFileExtension,
aliasNamesOnly = false,
separateAliasesFile = false,
showLog = true,
}) {
const iconsDistDirectory = path.join(outputDirectory, `icons`);
const fileName = path.basename(`aliases${fileExtension}`);
const icons = Object.keys(iconNodes);
// Reset file
resetFile(fileName, outputDirectory);
// Generate Import for Icon VNodes
await Promise.all(
icons.map(async (iconName, index) => {
const componentName = toPascalCase(iconName);
const iconAliases = iconMetaData[iconName]?.aliases?.map((alias) => {
if (typeof alias === 'string') {
return {
name: alias,
deprecated: false,
};
}
return alias;
});
let importString = '';
if ((iconAliases != null && Array.isArray(iconAliases)) || !aliasNamesOnly) {
if (index > 0) {
importString += '\n';
}
importString += `// ${componentName} aliases\n`;
}
if (!aliasNamesOnly) {
importString += getImportString(`${componentName}Icon`, iconName, aliasImportFileExtension);
importString += getImportString(
`Lucide${componentName}`,
iconName,
aliasImportFileExtension,
);
}
if (iconAliases != null && Array.isArray(iconAliases)) {
await Promise.all(
iconAliases.map(async (alias) => {
const componentNameAlias = toPascalCase(alias.name);
const deprecationReason = alias.deprecated
? deprecationReasonTemplate(alias.deprecationReason, {
componentName: toPascalCase(iconName),
iconName,
toBeRemovedInVersion: alias.toBeRemovedInVersion,
})
: '';
if (separateAliasesFile) {
const output = `export { default } from "./${iconName}"`;
const location = path.join(iconsDistDirectory, `${alias.name}${iconFileExtension}`);
await fs.promises.writeFile(location, output, 'utf-8');
}
// Don't import the same icon twice
if (componentName === componentNameAlias) {
return;
}
const exportFileIcon = separateAliasesFile ? alias.name : iconName;
importString += getImportString(
componentNameAlias,
exportFileIcon,
aliasImportFileExtension,
alias.deprecated,
deprecationReason,
);
if (!aliasNamesOnly) {
importString += getImportString(
`${componentNameAlias}Icon`,
exportFileIcon,
aliasImportFileExtension,
alias.deprecated,
deprecationReason,
);
importString += getImportString(
`Lucide${componentNameAlias}`,
exportFileIcon,
aliasImportFileExtension,
alias.deprecated,
deprecationReason,
);
}
}),
);
}
appendFile(importString, fileName, outputDirectory);
}),
);
appendFile('\n', fileName, outputDirectory);
if (showLog) {
console.log(`Successfully generated ${fileName} file`);
}
}
| lucide-icons/lucide/tools/build-icons/building/generateAliasesFile.mjs | {
"file_path": "lucide-icons/lucide/tools/build-icons/building/generateAliasesFile.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 1844
} | 40 |
import { Skeleton } from "~/components/ui/skeleton";
export default function Loading() {
return (
<div className=" space-y-8">
<Skeleton className=" h-[75px] rounded-md" />
<Skeleton className=" h-[200px] rounded-md" />
</div>
);
}
| moinulmoin/chadnext/src/app/[locale]/dashboard/billing/loading.tsx | {
"file_path": "moinulmoin/chadnext/src/app/[locale]/dashboard/billing/loading.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 101
} | 41 |
import { type User } from "lucia";
import { type Metadata } from "next";
import { validateRequest } from "~/actions/auth";
import SettingsForm from "./settings-form";
export const metadata: Metadata = {
title: "Settings",
};
export default async function Settings() {
const { user } = await validateRequest();
return <SettingsForm currentUser={user as User} />;
}
| moinulmoin/chadnext/src/app/[locale]/dashboard/settings/page.tsx | {
"file_path": "moinulmoin/chadnext/src/app/[locale]/dashboard/settings/page.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 104
} | 42 |
import { Inter } from "next/font/google";
import localFont from "next/font/local";
import { cookies } from "next/headers";
import Script from "next/script";
import { cn } from "~/lib/utils";
import "./globals.css";
const fontSans = Inter({
subsets: ["latin"],
variable: "--font-sans",
});
const fontHeading = localFont({
src: "../assets/fonts/CalSans-SemiBold.woff2",
variable: "--font-heading",
});
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const locale = cookies().get("Next-Locale")?.value || "en";
return (
<html lang={locale}>
<body
className={cn(
"font-sans antialiased",
fontSans.variable,
fontHeading.variable
)}
>
{children}
</body>
{process.env.NODE_ENV === "production" && (
<Script
src="https://umami.moinulmoin.com/script.js"
data-website-id="bc66d96a-fc75-4ecd-b0ef-fdd25de8113c"
/>
)}
</html>
);
}
| moinulmoin/chadnext/src/app/layout.tsx | {
"file_path": "moinulmoin/chadnext/src/app/layout.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 451
} | 43 |
import { validateRequest } from "~/actions/auth";
import { getScopedI18n } from "~/locales/server";
import Navbar from "./navbar";
export default async function Header() {
const { session } = await validateRequest();
const scopedT = await getScopedI18n("header");
const headerText = {
changelog: scopedT("changelog"),
about: scopedT("about"),
login: scopedT("login"),
dashboard: scopedT("dashboard"),
};
return (
<header className="h-20 w-full">
<div className="container h-full">
<Navbar headerText={headerText} session={session!} />
</div>
</header>
);
}
| moinulmoin/chadnext/src/components/layout/header/index.tsx | {
"file_path": "moinulmoin/chadnext/src/components/layout/header/index.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 223
} | 44 |
import * as React from "react";
import { cn } from "~/lib/utils";
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background 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}
{...props}
/>
);
}
);
Textarea.displayName = "Textarea";
export { Textarea };
| moinulmoin/chadnext/src/components/ui/textarea.tsx | {
"file_path": "moinulmoin/chadnext/src/components/ui/textarea.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 295
} | 45 |
import { GitHub } from "arctic";
export const github = new GitHub(
process.env.GITHUB_CLIENT_ID!,
process.env.GITHUB_CLIENT_SECRET!
);
| moinulmoin/chadnext/src/lib/github.ts | {
"file_path": "moinulmoin/chadnext/src/lib/github.ts",
"repo_id": "moinulmoin/chadnext",
"token_count": 52
} | 46 |
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Check } from "lucide-react";
enum PopularPlan {
NO = 0,
YES = 1,
}
interface PlanProps {
title: string;
popular: PopularPlan;
price: number;
description: string;
buttonText: string;
benefitList: string[];
}
const plans: PlanProps[] = [
{
title: "Free",
popular: 0,
price: 0,
description:
"Lorem ipsum dolor sit, amet ipsum consectetur adipisicing elit.",
buttonText: "Start Free Trial",
benefitList: [
"1 team member",
"1 GB storage",
"Upto 2 pages",
"Community support",
"AI assistance",
],
},
{
title: "Premium",
popular: 1,
price: 45,
description:
"Lorem ipsum dolor sit, amet ipsum consectetur adipisicing elit.",
buttonText: "Get starterd",
benefitList: [
"4 team member",
"8 GB storage",
"Upto 6 pages",
"Priority support",
"AI assistance",
],
},
{
title: "Enterprise",
popular: 0,
price: 120,
description:
"Lorem ipsum dolor sit, amet ipsum consectetur adipisicing elit.",
buttonText: "Contact US",
benefitList: [
"10 team member",
"20 GB storage",
"Upto 10 pages",
"Phone & email support",
"AI assistance",
],
},
];
export const PricingSection = () => {
return (
<section className="container py-24 sm:py-32">
<h2 className="text-lg text-primary text-center mb-2 tracking-wider">
Pricing
</h2>
<h2 className="text-3xl md:text-4xl text-center font-bold mb-4">
Get unlimitted access
</h2>
<h3 className="md:w-1/2 mx-auto text-xl text-center text-muted-foreground pb-14">
Lorem ipsum dolor sit amet consectetur adipisicing reiciendis.
</h3>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8 lg:gap-4">
{plans.map(
({ title, popular, price, description, buttonText, benefitList }) => (
<Card
key={title}
className={
popular === PopularPlan?.YES
? "drop-shadow-xl shadow-black/10 dark:shadow-white/10 border-[1.5px] border-primary lg:scale-[1.1]"
: ""
}
>
<CardHeader>
<CardTitle className="pb-2">{title}</CardTitle>
<CardDescription className="pb-4">
{description}
</CardDescription>
<div>
<span className="text-3xl font-bold">${price}</span>
<span className="text-muted-foreground"> /month</span>
</div>
</CardHeader>
<CardContent className="flex">
<div className="space-y-4">
{benefitList.map((benefit) => (
<span key={benefit} className="flex">
<Check className="text-primary mr-2" />
<h3>{benefit}</h3>
</span>
))}
</div>
</CardContent>
<CardFooter>
<Button
variant={
popular === PopularPlan?.YES ? "default" : "secondary"
}
className="w-full"
>
{buttonText}
</Button>
</CardFooter>
</Card>
)
)}
</div>
</section>
);
};
| nobruf/shadcn-landing-page/components/layout/sections/pricing.tsx | {
"file_path": "nobruf/shadcn-landing-page/components/layout/sections/pricing.tsx",
"repo_id": "nobruf/shadcn-landing-page",
"token_count": 1857
} | 47 |
const animate = require("tailwindcss-animate");
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
safelist: ["dark"],
prefix: "",
content: [
"./components/**/*.{ts,tsx}",
"./app/**/*.{ts,tsx}",
"./src/**/*.{ts,tsx}",
],
theme: {
container: {
center: true,
padding: "1.5rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
xl: "calc(var(--radius) + 4px)",
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: 0 },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: 0 },
},
"collapsible-down": {
from: { height: 0 },
to: { height: "var(--radix-collapsible-content-height)" },
},
"collapsible-up": {
from: { height: "var(--radix-collapsible-content-height)" },
to: { height: 0 },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
"collapsible-down": "collapsible-down 0.2s ease-in-out",
"collapsible-up": "collapsible-up 0.2s ease-in-out",
},
},
},
plugins: [animate],
};
| nobruf/shadcn-landing-page/tailwind.config.ts | {
"file_path": "nobruf/shadcn-landing-page/tailwind.config.ts",
"repo_id": "nobruf/shadcn-landing-page",
"token_count": 1367
} | 48 |
import { redirect } from "next/navigation"
import { authOptions } from "@/lib/auth"
import { getCurrentUser } from "@/lib/session"
import { DashboardHeader } from "@/components/header"
import { DashboardShell } from "@/components/shell"
import { UserNameForm } from "@/components/user-name-form"
export const metadata = {
title: "Settings",
description: "Manage account and website settings.",
}
export default async function SettingsPage() {
const user = await getCurrentUser()
if (!user) {
redirect(authOptions?.pages?.signIn || "/login")
}
return (
<DashboardShell>
<DashboardHeader
heading="Settings"
text="Manage account and website settings."
/>
<div className="grid gap-10">
<UserNameForm user={{ id: user.id, name: user.name || "" }} />
</div>
</DashboardShell>
)
}
| shadcn-ui/taxonomy/app/(dashboard)/dashboard/settings/page.tsx | {
"file_path": "shadcn-ui/taxonomy/app/(dashboard)/dashboard/settings/page.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 294
} | 49 |
import Link from "next/link"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
import { Icons } from "@/components/icons"
export const metadata = {
title: "Pricing",
}
export default function PricingPage() {
return (
<section className="container flex flex-col gap-6 py-8 md:max-w-[64rem] md:py-12 lg:py-24">
<div className="mx-auto flex w-full flex-col gap-4 md:max-w-[58rem]">
<h2 className="font-heading text-3xl leading-[1.1] sm:text-3xl md:text-6xl">
Simple, transparent pricing
</h2>
<p className="max-w-[85%] leading-normal text-muted-foreground sm:text-lg sm:leading-7">
Unlock all features including unlimited posts for your blog.
</p>
</div>
<div className="grid w-full items-start gap-10 rounded-lg border p-10 md:grid-cols-[1fr_200px]">
<div className="grid gap-6">
<h3 className="text-xl font-bold sm:text-2xl">
What's included in the PRO plan
</h3>
<ul className="grid gap-3 text-sm text-muted-foreground sm:grid-cols-2">
<li className="flex items-center">
<Icons.check className="mr-2 h-4 w-4" /> Unlimited Posts
</li>
<li className="flex items-center">
<Icons.check className="mr-2 h-4 w-4" /> Unlimited Users
</li>
<li className="flex items-center">
<Icons.check className="mr-2 h-4 w-4" /> Custom domain
</li>
<li className="flex items-center">
<Icons.check className="mr-2 h-4 w-4" /> Dashboard Analytics
</li>
<li className="flex items-center">
<Icons.check className="mr-2 h-4 w-4" /> Access to Discord
</li>
<li className="flex items-center">
<Icons.check className="mr-2 h-4 w-4" /> Premium Support
</li>
</ul>
</div>
<div className="flex flex-col gap-4 text-center">
<div>
<h4 className="text-7xl font-bold">$19</h4>
<p className="text-sm font-medium text-muted-foreground">
Billed Monthly
</p>
</div>
<Link href="/login" className={cn(buttonVariants({ size: "lg" }))}>
Get Started
</Link>
</div>
</div>
<div className="mx-auto flex w-full max-w-[58rem] flex-col gap-4">
<p className="max-w-[85%] leading-normal text-muted-foreground sm:leading-7">
Taxonomy is a demo app.{" "}
<strong>You can test the upgrade and won't be charged.</strong>
</p>
</div>
</section>
)
}
| shadcn-ui/taxonomy/app/(marketing)/pricing/page.tsx | {
"file_path": "shadcn-ui/taxonomy/app/(marketing)/pricing/page.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 1313
} | 50 |
"use client"
import * as React from "react"
import { useRouter } from "next/navigation"
import { cn } from "@/lib/utils"
import { ButtonProps, buttonVariants } from "@/components/ui/button"
import { toast } from "@/components/ui/use-toast"
import { Icons } from "@/components/icons"
interface PostCreateButtonProps extends ButtonProps {}
export function PostCreateButton({
className,
variant,
...props
}: PostCreateButtonProps) {
const router = useRouter()
const [isLoading, setIsLoading] = React.useState<boolean>(false)
async function onClick() {
setIsLoading(true)
const response = await fetch("/api/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Untitled Post",
}),
})
setIsLoading(false)
if (!response?.ok) {
if (response.status === 402) {
return toast({
title: "Limit of 3 posts reached.",
description: "Please upgrade to the PRO plan.",
variant: "destructive",
})
}
return toast({
title: "Something went wrong.",
description: "Your post was not created. Please try again.",
variant: "destructive",
})
}
const post = await response.json()
// This forces a cache invalidation.
router.refresh()
router.push(`/editor/${post.id}`)
}
return (
<button
onClick={onClick}
className={cn(
buttonVariants({ variant }),
{
"cursor-not-allowed opacity-60": isLoading,
},
className
)}
disabled={isLoading}
{...props}
>
{isLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.add className="mr-2 h-4 w-4" />
)}
New post
</button>
)
}
| shadcn-ui/taxonomy/components/post-create-button.tsx | {
"file_path": "shadcn-ui/taxonomy/components/post-create-button.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 776
} | 51 |
import * as React from "react"
import { VariantProps, cva } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "underline-offset-4 hover:underline text-primary",
},
size: {
default: "h-10 py-2 px-4",
sm: "h-9 px-3 rounded-md",
lg: "h-11 px-8 rounded-md",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, ...props }, ref) => {
return (
<button
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
| shadcn-ui/taxonomy/components/ui/button.tsx | {
"file_path": "shadcn-ui/taxonomy/components/ui/button.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 655
} | 52 |
"use client"
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn("grid gap-2", className)}
{...props}
ref={ref}
/>
)
})
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, children, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"h-4 w-4 rounded-full border border-input ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-primary text-primary" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
})
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
export { RadioGroup, RadioGroupItem }
| shadcn-ui/taxonomy/components/ui/radio-group.tsx | {
"file_path": "shadcn-ui/taxonomy/components/ui/radio-group.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 519
} | 53 |
"use client"
import * as React from "react"
import { useSearchParams } from "next/navigation"
import { zodResolver } from "@hookform/resolvers/zod"
import { signIn } from "next-auth/react"
import { useForm } from "react-hook-form"
import * as z from "zod"
import { cn } from "@/lib/utils"
import { userAuthSchema } from "@/lib/validations/auth"
import { buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { toast } from "@/components/ui/use-toast"
import { Icons } from "@/components/icons"
interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {}
type FormData = z.infer<typeof userAuthSchema>
export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(userAuthSchema),
})
const [isLoading, setIsLoading] = React.useState<boolean>(false)
const [isGitHubLoading, setIsGitHubLoading] = React.useState<boolean>(false)
const searchParams = useSearchParams()
async function onSubmit(data: FormData) {
setIsLoading(true)
const signInResult = await signIn("email", {
email: data.email.toLowerCase(),
redirect: false,
callbackUrl: searchParams?.get("from") || "/dashboard",
})
setIsLoading(false)
if (!signInResult?.ok) {
return toast({
title: "Something went wrong.",
description: "Your sign in request failed. Please try again.",
variant: "destructive",
})
}
return toast({
title: "Check your email",
description: "We sent you a login link. Be sure to check your spam too.",
})
}
return (
<div className={cn("grid gap-6", className)} {...props}>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-2">
<div className="grid gap-1">
<Label className="sr-only" htmlFor="email">
Email
</Label>
<Input
id="email"
placeholder="[email protected]"
type="email"
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
disabled={isLoading || isGitHubLoading}
{...register("email")}
/>
{errors?.email && (
<p className="px-1 text-xs text-red-600">
{errors.email.message}
</p>
)}
</div>
<button className={cn(buttonVariants())} disabled={isLoading}>
{isLoading && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)}
Sign In with Email
</button>
</div>
</form>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">
Or continue with
</span>
</div>
</div>
<button
type="button"
className={cn(buttonVariants({ variant: "outline" }))}
onClick={() => {
setIsGitHubLoading(true)
signIn("github")
}}
disabled={isLoading || isGitHubLoading}
>
{isGitHubLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.gitHub className="mr-2 h-4 w-4" />
)}{" "}
Github
</button>
</div>
)
}
| shadcn-ui/taxonomy/components/user-auth-form.tsx | {
"file_path": "shadcn-ui/taxonomy/components/user-auth-form.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 1646
} | 54 |
// @ts-nocheck
// TODO: Fix this when we turn strict mode on.
import { UserSubscriptionPlan } from "types"
import { freePlan, proPlan } from "@/config/subscriptions"
import { db } from "@/lib/db"
export async function getUserSubscriptionPlan(
userId: string
): Promise<UserSubscriptionPlan> {
const user = await db.user.findFirst({
where: {
id: userId,
},
select: {
stripeSubscriptionId: true,
stripeCurrentPeriodEnd: true,
stripeCustomerId: true,
stripePriceId: true,
},
})
if (!user) {
throw new Error("User not found")
}
// Check if user is on a pro plan.
const isPro =
user.stripePriceId &&
user.stripeCurrentPeriodEnd?.getTime() + 86_400_000 > Date.now()
const plan = isPro ? proPlan : freePlan
return {
...plan,
...user,
stripeCurrentPeriodEnd: user.stripeCurrentPeriodEnd?.getTime(),
isPro,
}
}
| shadcn-ui/taxonomy/lib/subscription.ts | {
"file_path": "shadcn-ui/taxonomy/lib/subscription.ts",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 338
} | 55 |
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "mysql" | shadcn-ui/taxonomy/prisma/migrations/migration_lock.toml | {
"file_path": "shadcn-ui/taxonomy/prisma/migrations/migration_lock.toml",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 35
} | 56 |
// The content of this directory is autogenerated by the registry server.
| shadcn-ui/ui/apps/www/__registry__/.autogenerated | {
"file_path": "shadcn-ui/ui/apps/www/__registry__/.autogenerated",
"repo_id": "shadcn-ui/ui",
"token_count": 17
} | 57 |
"use server"
import { track } from "@vercel/analytics/server"
import { capitalCase } from "change-case"
export async function editInV0({
name,
title,
description,
style,
code,
url,
}: {
name: string
title?: string
description: string
style: string
code: string
url: string
}) {
try {
title =
title ??
capitalCase(
name.replace(/\d+/g, "").replace("-demo", "").replace("-", " ")
)
await track("edit_in_v0", {
name,
title,
description,
style,
url,
})
// Replace "use client" in the code.
// v0 will handle this for us.
// code = code.replace(`"use client"`, "")
const payload = {
title,
description,
code,
source: {
title: "shadcn/ui",
url,
},
meta: {
project: capitalCase(name.replace(/\d+/g, "")),
file: `${name}.tsx`,
},
}
const response = await fetch(`${process.env.V0_URL}/chat/api/open-in-v0`, {
method: "POST",
body: JSON.stringify(payload),
headers: {
"x-v0-edit-secret": process.env.V0_EDIT_SECRET!,
"x-vercel-protection-bypass":
process.env.DEPLOYMENT_PROTECTION_BYPASS || "not-set",
"Content-Type": "application/json",
},
})
if (!response.ok) {
if (response.status === 403) {
throw new Error("Unauthorized")
}
console.error(response.statusText)
throw new Error("Something went wrong. Please try again later.")
}
const result = await response.json()
return {
...result,
url: `${process.env.V0_URL}/chat/api/open-in-v0/${result.id}`,
}
} catch (error) {
console.error(error)
if (error instanceof Error) {
return { error: error.message }
}
}
}
| shadcn-ui/ui/apps/www/actions/edit-in-v0.ts | {
"file_path": "shadcn-ui/ui/apps/www/actions/edit-in-v0.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 811
} | 58 |
import { BellIcon, EyeNoneIcon, PersonIcon } from "@radix-ui/react-icons"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/registry/new-york/ui/card"
export function DemoNotifications() {
return (
<Card>
<CardHeader className="pb-3">
<CardTitle>Notifications</CardTitle>
<CardDescription>
Choose what you want to be notified about.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-1">
<div className="-mx-2 flex items-start space-x-4 rounded-md p-2 transition-all hover:bg-accent hover:text-accent-foreground">
<BellIcon className="mt-px h-5 w-5" />
<div className="space-y-1">
<p className="text-sm font-medium leading-none">Everything</p>
<p className="text-sm text-muted-foreground">
Email digest, mentions & all activity.
</p>
</div>
</div>
<div className="-mx-2 flex items-start space-x-4 rounded-md bg-accent p-2 text-accent-foreground transition-all">
<PersonIcon className="mt-px h-5 w-5" />
<div className="space-y-1">
<p className="text-sm font-medium leading-none">Available</p>
<p className="text-sm text-muted-foreground">
Only mentions and comments.
</p>
</div>
</div>
<div className="-mx-2 flex items-start space-x-4 rounded-md p-2 transition-all hover:bg-accent hover:text-accent-foreground">
<EyeNoneIcon className="mt-px h-5 w-5" />
<div className="space-y-1">
<p className="text-sm font-medium leading-none">Ignoring</p>
<p className="text-sm text-muted-foreground">
Turn off all notifications.
</p>
</div>
</div>
</CardContent>
</Card>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/cards/components/notifications.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/cards/components/notifications.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 865
} | 59 |
Subsets and Splits