text
stringlengths
21
253k
id
stringlengths
25
123
metadata
dict
__index_level_0__
int64
0
181
import plugins from '@lucide/rollup-plugins'; import dts from 'rollup-plugin-dts'; import pkg from './package.json' assert { type: 'json' }; const packageName = 'LucidePreact'; const outputFileName = 'lucide-preact'; const outputDir = 'dist'; const inputs = [`src/lucide-preact.ts`]; const bundles = [ { format: 'umd', inputs, outputDir, minify: true, }, { format: 'umd', inputs, outputDir, }, { format: 'cjs', inputs, outputDir, }, { format: 'esm', inputs, outputDir, preserveModules: true, }, ]; const configs = bundles .map(({ inputs, outputDir, format, minify, preserveModules }) => inputs.map((input) => ({ input, plugins: plugins({ pkg, minify }), external: ['preact'], output: { name: packageName, ...(preserveModules ? { dir: `${outputDir}/${format}`, } : { file: `${outputDir}/${format}/${outputFileName}${minify ? '.min' : ''}.js`, }), preserveModules, format, sourcemap: true, preserveModulesRoot: 'src', globals: { preact: 'preact', }, }, })), ) .flat(); export default [ { input: inputs[0], output: [ { file: `dist/${outputFileName}.d.ts`, format: 'es', }, ], plugins: [dts()], }, ...configs, ];
lucide-icons/lucide/packages/lucide-preact/rollup.config.mjs
{ "file_path": "lucide-icons/lucide/packages/lucide-preact/rollup.config.mjs", "repo_id": "lucide-icons/lucide", "token_count": 686 }
87
import { ReactSVG, SVGProps, ForwardRefExoticComponent, RefAttributes } from 'react'; export type IconNode = [elementName: keyof ReactSVG, attrs: Record<string, string>][]; export type SVGAttributes = Partial<SVGProps<SVGSVGElement>>; type ElementAttributes = RefAttributes<SVGSVGElement> & SVGAttributes; export interface LucideProps extends ElementAttributes { size?: string | number; absoluteStrokeWidth?: boolean; } export type LucideIcon = ForwardRefExoticComponent< Omit<LucideProps, 'ref'> & RefAttributes<SVGSVGElement> >;
lucide-icons/lucide/packages/lucide-react/src/types.ts
{ "file_path": "lucide-icons/lucide/packages/lucide-react/src/types.ts", "repo_id": "lucide-icons/lucide", "token_count": 166 }
88
/* eslint-disable import/no-extraneous-dependencies */ import base64SVG from '@lucide/build-icons/utils/base64SVG.mjs'; export default ({ componentName, iconName, children, getSvg, deprecated, deprecationReason }) => { const svgContents = getSvg(); const svgBase64 = base64SVG(svgContents); return ` import Icon from '../Icon'; import type { IconNode, LucideProps } from '../types'; const iconNode: IconNode = ${JSON.stringify(children)}; /** * @component @name ${componentName} * @description Lucide SVG icon component, renders SVG Element with children. * * @preview ![img](data:image/svg+xml;base64,${svgBase64}) - https://lucide.dev/icons/${iconName} * @see https://lucide.dev/guide/packages/lucide-solid - Documentation * * @param {Object} props - Lucide icons props and any valid SVG attribute * @returns {JSX.Element} JSX Element * ${deprecated ? `@deprecated ${deprecationReason}` : ''} */ const ${componentName} = (props: LucideProps) => ( <Icon {...props} name="${componentName}" iconNode={iconNode} /> ) export default ${componentName}; `; };
lucide-icons/lucide/packages/lucide-solid/scripts/exportTemplate.mjs
{ "file_path": "lucide-icons/lucide/packages/lucide-solid/scripts/exportTemplate.mjs", "repo_id": "lucide-icons/lucide", "token_count": 353 }
89
import pkg from '../package.json' assert { type: 'json' }; export function getJSBanner() { return `/** * @license ${pkg.name} v${pkg.version} - ${pkg.license} * * This source code is licensed under the ${pkg.license} license. * See the LICENSE file in the root directory of this source tree. */ `; }
lucide-icons/lucide/packages/lucide-svelte/scripts/license.mjs
{ "file_path": "lucide-icons/lucide/packages/lucide-svelte/scripts/license.mjs", "repo_id": "lucide-icons/lucide", "token_count": 97 }
90
import { describe, it, expect } from 'vitest'; import { createIcons, icons } from '../src/lucide'; import fs from 'fs'; import path from 'path'; import { parseSync, stringify } from 'svgson'; const ICONS_DIR = path.resolve(__dirname, '../../../icons'); const getOriginalSvg = (iconName, aliasName) => { const svgContent = fs.readFileSync(path.join(ICONS_DIR, `${iconName}.svg`), 'utf8'); const svgParsed = parseSync(svgContent); svgParsed.attributes['data-lucide'] = aliasName ?? iconName; svgParsed.attributes['class'] = `lucide lucide-${aliasName ?? iconName}`; return stringify(svgParsed, { selfClose: false }); }; describe('createIcons', () => { it('should read elements from DOM and replace it with icons', () => { document.body.innerHTML = `<i data-lucide="volume-2"></i>`; createIcons({ icons }); const svg = getOriginalSvg('volume-2'); expect(document.body.innerHTML).toBe(svg); expect(document.body.innerHTML).toMatchSnapshot(); }); it('should customize the name attribute', () => { document.body.innerHTML = `<i data-custom-name="volume-2"></i>`; createIcons({ icons, nameAttr: 'data-custom-name', }); const hasSvg = !!document.querySelector('svg'); expect(hasSvg).toBeTruthy(); }); it('should add custom attributes', () => { document.body.innerHTML = `<i data-lucide="volume-2" class="lucide"></i>`; const attrs = { class: 'lucide lucide-volume-2 icon custom-class', fill: 'black', }; createIcons({ icons, attrs }); const element = document.querySelector('svg'); const attributes = element.getAttributeNames(); const attributesAndValues = attributes.reduce((acc, item) => { acc[item] = element.getAttribute(item); return acc; }, {}); expect(document.body.innerHTML).toMatchSnapshot(); expect(attributesAndValues).toEqual(expect.objectContaining(attrs)); }); it('should inherit elements attributes', () => { document.body.innerHTML = `<i data-lucide="sun" data-theme-switcher="light"></i>`; const attrs = { 'data-theme-switcher': 'light', }; createIcons({ icons }); const element = document.querySelector('svg'); const attributes = element.getAttributeNames(); const attributesAndValues = attributes.reduce((acc, item) => { acc[item] = element.getAttribute(item); return acc; }, {}); expect(attributesAndValues).toEqual(expect.objectContaining(attrs)); }); it('should read elements from DOM and replace icon with alias name', () => { document.body.innerHTML = `<i data-lucide="grid"></i>`; createIcons({ icons }); const svg = getOriginalSvg('grid-3x3', 'grid'); expect(document.body.innerHTML).toBe(svg); expect(document.body.innerHTML).toMatchSnapshot(); }); });
lucide-icons/lucide/packages/lucide/tests/lucide.spec.js
{ "file_path": "lucide-icons/lucide/packages/lucide/tests/lucide.spec.js", "repo_id": "lucide-icons/lucide", "token_count": 1023 }
91
import fs from 'fs'; import path from 'path'; import { parseSync } from 'svgson'; import { shuffleArray, readSvgDirectory, getCurrentDirPath, minifySvg, toPascalCase, } from '../tools/build-helpers/helpers.mjs'; const currentDir = getCurrentDirPath(import.meta.url); const ICONS_DIR = path.resolve(currentDir, '../icons'); const BASE_URL = 'https://lucide.dev/api/gh-icon'; const changedFilesPathString = process.env.CHANGED_FILES; const changedFiles = changedFilesPathString .split(' ') .map((file) => file.replace('.json', '.svg')) .filter((file, idx, arr) => arr.indexOf(file) === idx); const getImageTagsByFiles = (files, getBaseUrl, width) => files.map((file) => { const svgContent = fs.readFileSync(path.join(process.cwd(), file), 'utf-8'); const strippedAttrsSVG = svgContent.replace(/<svg[^>]*>/, '<svg>'); const minifiedSvg = minifySvg(strippedAttrsSVG); const base64 = Buffer.from(minifiedSvg).toString('base64'); const url = getBaseUrl(file); const widthAttr = width ? `width="${width}"` : ''; return `<img title="${file}" alt="${file}" ${widthAttr} src="${url}/${base64}.svg"/>`; }); const svgFiles = readSvgDirectory(ICONS_DIR).map((file) => `icons/${file}`); const iconsFilteredByName = (search) => svgFiles.filter((file) => file.includes(search)); const cohesionRandomImageTags = getImageTagsByFiles( shuffleArray(svgFiles).slice(0, changedFiles.length), () => `${BASE_URL}/stroke-width/2`, ).join(''); const cohesionSquaresImageTags = getImageTagsByFiles( shuffleArray(iconsFilteredByName('square')).slice(0, changedFiles.length), () => `${BASE_URL}/stroke-width/2`, ).join(''); const changeFiles1pxStrokeImageTags = getImageTagsByFiles( changedFiles, () => `${BASE_URL}/stroke-width/1`, ).join(''); const changeFiles2pxStrokeImageTags = getImageTagsByFiles( changedFiles, () => `${BASE_URL}/stroke-width/2`, ).join(''); const changeFiles3pxStrokeImageTags = getImageTagsByFiles( changedFiles, () => `${BASE_URL}/stroke-width/3`, ).join(''); const changeFilesLowDPIImageTags = getImageTagsByFiles( changedFiles, () => `${BASE_URL}/dpi/24`, ).join(' '); const changeFilesXRayImageTags = getImageTagsByFiles( changedFiles, (file) => { const iconName = path.basename(file, '.svg'); return `${BASE_URL}/${iconName}`; }, 400, ).join(' '); const changeFilesDiffImageTags = getImageTagsByFiles( changedFiles, (file) => { const iconName = path.basename(file, '.svg'); return `${BASE_URL}/diff/${iconName}`; }, 400, ).join(' '); const readyToUseCode = changedFiles .map((changedFile) => { const svgContent = fs.readFileSync(path.join(process.cwd(), changedFile), 'utf-8'); const name = path.basename(changedFile, '.svg'); return `const ${toPascalCase(name)}Icon = createLucideIcon('${toPascalCase(name)}', [ ${parseSync(svgContent) .children.map(({ name, attributes }) => JSON.stringify([name, attributes])) .join(',\n ')} ])`; }) .join('\n\n'); const commentMarkup = `\ ### Added or changed icons ${changeFiles2pxStrokeImageTags} <details> <summary>Preview cohesion</summary> ${cohesionSquaresImageTags}<br/> ${changeFiles2pxStrokeImageTags}<br/> ${cohesionRandomImageTags}<br/> </details> <details> <summary>Preview stroke widths</summary> ${changeFiles1pxStrokeImageTags}<br/> ${changeFiles2pxStrokeImageTags}<br/> ${changeFiles3pxStrokeImageTags}<br/> </details> <details> <summary>DPI Preview (24px)</summary> ${changeFilesLowDPIImageTags}<br/> </details> <details> <summary>Icon X-rays</summary> ${changeFilesXRayImageTags} </details> <details> <summary>Icon Diffs</summary> ${changeFilesDiffImageTags} </details> <details> <summary>Icons as code</summary> Works for: \`lucide-react\`, \`lucide-react-native\`, \`lucide-preact\`, \`lucide-vue-next\` \`\`\`ts ${readyToUseCode} \`\`\` </details>`; console.log(commentMarkup);
lucide-icons/lucide/scripts/generateChangedIconsCommentMarkup.mjs
{ "file_path": "lucide-icons/lucide/scripts/generateChangedIconsCommentMarkup.mjs", "repo_id": "lucide-icons/lucide", "token_count": 1458 }
92
/* eslint-disable import/prefer-default-export */ import fs from 'fs'; import path from 'path'; /** * Read svg from directory * * @param {string} fileName * @param {string} directory */ export const readSvg = (fileName, directory) => fs.readFileSync(path.join(directory, fileName), 'utf-8');
lucide-icons/lucide/tools/build-helpers/src/readSvg.mjs
{ "file_path": "lucide-icons/lucide/tools/build-helpers/src/readSvg.mjs", "repo_id": "lucide-icons/lucide", "token_count": 97 }
93
export { default as getAliases } from './utils/getAliases.mjs'; export { default as getIconMetaData } from './utils/getIconMetaData.mjs'; export { default as renderIconsObject } from './render/renderIconsObject.mjs';
lucide-icons/lucide/tools/build-icons/index.mjs
{ "file_path": "lucide-icons/lucide/tools/build-icons/index.mjs", "repo_id": "lucide-icons/lucide", "token_count": 67 }
94
"use client"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import CopyButton from "~/components/copy-button"; import Icons from "~/components/shared/icons"; import { Button } from "~/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "~/components/ui/form"; import { Input } from "~/components/ui/input"; import { toast } from "~/components/ui/use-toast"; import { updateProjectById } from "../action"; import { projectSchema, type ProjectFormValues } from "../create-project-modal"; // const projectEditSchema = projectSchema.extend({ // id: z.string().readonly(), // }); // type ProjectEditValues = z.infer<typeof projectEditSchema>; export default function EditableDetails({ initialValues, }: { initialValues: ProjectFormValues & { id: string }; }) { const form = useForm<ProjectFormValues>({ resolver: zodResolver(projectSchema), values: initialValues, }); async function onSubmit(values: ProjectFormValues) { try { await updateProjectById(initialValues.id, values); toast({ title: "Project Updated successfully.", }); form.reset(); } catch (error) { console.error(error); toast({ title: "Error creating project.", description: "Please try again.", variant: "destructive", }); } } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="mt-5 space-y-6"> <FormItem> <FormLabel>ID</FormLabel> <FormControl> <div className="relative "> <Input value={initialValues.id} readOnly disabled /> <CopyButton content={initialValues.id} /> </div> </FormControl> <FormMessage /> </FormItem> <FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input placeholder="XYZ" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="domain" render={({ field }) => ( <FormItem> <FormLabel>Domain</FormLabel> <FormControl> <Input placeholder="xyz.com" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Button disabled={form.formState.isSubmitting || !form.formState.isDirty} type="submit" > {form.formState.isSubmitting && ( <Icons.spinner className={"mr-2 h-5 w-5 animate-spin "} /> )} Save </Button> </form> </Form> ); }
moinulmoin/chadnext/src/app/[locale]/dashboard/projects/[projectId]/editable-details.tsx
{ "file_path": "moinulmoin/chadnext/src/app/[locale]/dashboard/projects/[projectId]/editable-details.tsx", "repo_id": "moinulmoin/chadnext", "token_count": 1324 }
95
import { OAuth2RequestError } from "arctic"; import { cookies } from "next/headers"; import type { NextRequest } from "next/server"; import { sendWelcomeEmail } from "~/actions/mail"; import prisma from "~/lib/prisma"; import { github } from "~/lib/github"; import { lucia } from "~/lib/lucia"; export const GET = async (request: NextRequest) => { const url = new URL(request.url); const code = url.searchParams.get("code"); const state = url.searchParams.get("state"); const storedState = cookies().get("github_oauth_state")?.value ?? null; if (!code || !state || !storedState || state !== storedState) { return new Response(null, { status: 400, }); } try { const tokens = await github.validateAuthorizationCode(code); const githubUserResponse = await fetch("https://api.github.com/user", { headers: { Authorization: `Bearer ${tokens.accessToken}`, }, }); const githubUser: GitHubUser = await githubUserResponse.json(); if (!githubUser.email) { const githubEmailsResponse = await fetch( "https://api.github.com/user/emails", { headers: { Authorization: `Bearer ${tokens.accessToken}`, }, } ); const githubEmails: { email: string; primary: boolean; verified: boolean; }[] = await githubEmailsResponse.json(); const verifiedEmail = githubEmails.find( (email) => email.primary && email.verified ); if (verifiedEmail) githubUser.email = verifiedEmail.email; } const existingUser = await prisma.user.findUnique({ where: { githubId: githubUser.id, }, }); if (existingUser) { const session = await lucia.createSession(existingUser.id, {}); const sessionCookie = lucia.createSessionCookie(session.id); cookies().set( sessionCookie.name, sessionCookie.value, sessionCookie.attributes ); return new Response(null, { status: 302, headers: { Location: "/dashboard", }, }); } const newUser = await prisma.user.create({ data: { githubId: githubUser.id, name: githubUser.name, email: githubUser.email, picture: githubUser.avatar_url, emailVerified: Boolean(githubUser.email), }, }); if (githubUser.email) { sendWelcomeEmail({ toMail: newUser.email!, userName: newUser.name! }); } const session = await lucia.createSession(newUser.id, {}); const sessionCookie = lucia.createSessionCookie(session.id); cookies().set( sessionCookie.name, sessionCookie.value, sessionCookie.attributes ); return new Response(null, { status: 302, headers: { Location: "/dashboard", }, }); } catch (e) { console.log(e); // the specific error message depends on the provider if (e instanceof OAuth2RequestError) { // invalid code return new Response(null, { status: 400, }); } return new Response(null, { status: 500, }); } }; interface GitHubUser { id: number; name: string; email: string; avatar_url: string; }
moinulmoin/chadnext/src/app/api/auth/login/github/callback/route.ts
{ "file_path": "moinulmoin/chadnext/src/app/api/auth/login/github/callback/route.ts", "repo_id": "moinulmoin/chadnext", "token_count": 1299 }
96
import { defaultCache } from "@serwist/next/worker"; import type { PrecacheEntry, SerwistGlobalConfig } from "serwist"; import { Serwist } from "serwist"; // This declares the value of `injectionPoint` to TypeScript. // `injectionPoint` is the string that will be replaced by the // actual precache manifest. By default, this string is set to // `"self.__SW_MANIFEST"`. declare global { interface WorkerGlobalScope extends SerwistGlobalConfig { __SW_MANIFEST: (PrecacheEntry | string)[] | undefined; } } declare const self: ServiceWorkerGlobalScope; const serwist = new Serwist({ precacheEntries: self.__SW_MANIFEST, skipWaiting: true, clientsClaim: true, navigationPreload: true, runtimeCaching: defaultCache, }); serwist.addEventListeners();
moinulmoin/chadnext/src/app/sw.ts
{ "file_path": "moinulmoin/chadnext/src/app/sw.ts", "repo_id": "moinulmoin/chadnext", "token_count": 242 }
97
import { LanguagesIcon } from "lucide-react"; import { BrandIcons } from "../shared/brand-icons"; import { Card } from "../ui/card"; export default function Features() { return ( <section> <div className="container space-y-6 rounded-md bg-secondary py-14 lg:py-24 "> <div className="mx-auto flex max-w-[58rem] flex-col items-center space-y-4 text-center"> <h2 className="font-heading text-4xl md:text-6xl">Features</h2> <p className="max-w-[85%] text-balance leading-normal text-primary/70 sm:text-lg sm:leading-7"> This template comes with features like Authentication, API routes, File uploading and more in Next.js App dir. </p> </div> <div className="mx-auto grid justify-center gap-4 text-center sm:grid-cols-2 md:max-w-[64rem] md:grid-cols-3"> <Card className="flex h-[160px] flex-col justify-between rounded-md p-6"> <BrandIcons.nextjs /> <p className="text-balance text-sm text-muted-foreground"> App dir, Routing, Layouts, API routes, Server Components, Server actions. </p> </Card> <Card className="flex h-[160px] flex-col justify-between rounded-md p-6"> <BrandIcons.shadcnUI /> <p className="text-balance text-sm text-muted-foreground"> UI components built using Radix UI and styled with Tailwind CSS. </p> </Card> <Card className="flex h-[160px] flex-col justify-between rounded-md p-6"> <BrandIcons.prisma /> <p className="text-balance text-sm text-muted-foreground"> Using Postgres with Prisma ORM, hosted on Vercel Postgres. </p> </Card> <Card className="flex h-[160px] flex-col justify-between rounded-md p-6"> <BrandIcons.luciaAuth /> <p className="text-balance text-sm text-muted-foreground"> Authentication and Authorization using LuciaAuth v3. </p> </Card> <Card className="flex h-[160px] flex-col justify-between rounded-md p-6"> <BrandIcons.uploadthing /> <p className="text-balance text-sm text-muted-foreground"> Upload and preview files effortlessly with UploadThing. </p> </Card> <Card className="flex h-[160px] flex-col justify-between p-6"> <BrandIcons.resend /> <p className="text-balance text-sm text-muted-foreground"> Create emails using React Email and Send with Resend. </p> </Card> <Card className="flex h-[160px] flex-col justify-between p-6"> <LanguagesIcon className="mx-auto h-12 w-12 fill-current" /> <p className="text-balance text-sm text-muted-foreground"> Internationalization support with type-safe Next-International. </p> </Card> <Card className="flex h-[160px] flex-col justify-between p-6"> <BrandIcons.stripe /> <p className="text-balance text-sm text-muted-foreground"> Receive and process payments with Stripe. </p> </Card> <Card className="flex h-[160px] flex-col justify-between p-6"> <BrandIcons.vercel /> <p className="text-balance text-sm text-muted-foreground"> Production and Preview deployments with Vercel. </p> </Card> </div> <div className="mx-auto text-center md:max-w-[58rem]"> <p className="leading-normal text-primary/70 sm:text-lg sm:leading-7"> ChadNext also includes Changelog & About page built using{" "} <a href="https://velite.js.org/" target="_blank" rel="noopener noreferrer" className=" underline underline-offset-4" > Velite </a>{" "} and Markdown. </p> </div> </div> </section> ); }
moinulmoin/chadnext/src/components/sections/features.tsx
{ "file_path": "moinulmoin/chadnext/src/components/sections/features.tsx", "repo_id": "moinulmoin/chadnext", "token_count": 1924 }
98
import { type SubscriptionPlan } from "~/types"; export const freePlan: SubscriptionPlan = { name: "Free", description: "You can create up to 3 Projects. Upgrade to the PRO plan for unlimited projects.", stripePriceId: "", }; export const proPlan: SubscriptionPlan = { name: "PRO", description: "Now you have unlimited projects!", stripePriceId: process.env.STRIPE_PRO_PLAN_ID as string, };
moinulmoin/chadnext/src/config/subscription.ts
{ "file_path": "moinulmoin/chadnext/src/config/subscription.ts", "repo_id": "moinulmoin/chadnext", "token_count": 124 }
99
import { UTApi } from "uploadthing/server"; export const utapi = new UTApi();
moinulmoin/chadnext/src/lib/uploadthing-server.ts
{ "file_path": "moinulmoin/chadnext/src/lib/uploadthing-server.ts", "repo_id": "moinulmoin/chadnext", "token_count": 26 }
100
import * as React from "react"; function GithubIcon(props: React.SVGProps<SVGSVGElement> | undefined) { return ( <svg width="20px" height="20px" xmlns="http://www.w3.org/2000/svg" className="ionicon fill-foreground" viewBox="0 0 512 512" {...props} > <path d="M256 32C132.3 32 32 134.9 32 261.7c0 101.5 64.2 187.5 153.2 217.9a17.56 17.56 0 003.8.4c8.3 0 11.5-6.1 11.5-11.4 0-5.5-.2-19.9-.3-39.1a102.4 102.4 0 01-22.6 2.7c-43.1 0-52.9-33.5-52.9-33.5-10.2-26.5-24.9-33.6-24.9-33.6-19.5-13.7-.1-14.1 1.4-14.1h.1c22.5 2 34.3 23.8 34.3 23.8 11.2 19.6 26.2 25.1 39.6 25.1a63 63 0 0025.6-6c2-14.8 7.8-24.9 14.2-30.7-49.7-5.8-102-25.5-102-113.5 0-25.1 8.7-45.6 23-61.6-2.3-5.8-10-29.2 2.2-60.8a18.64 18.64 0 015-.5c8.1 0 26.4 3.1 56.6 24.1a208.21 208.21 0 01112.2 0c30.2-21 48.5-24.1 56.6-24.1a18.64 18.64 0 015 .5c12.2 31.6 4.5 55 2.2 60.8 14.3 16.1 23 36.6 23 61.6 0 88.2-52.4 107.6-102.3 113.3 8 7.1 15.2 21.1 15.2 42.5 0 30.7-.3 55.5-.3 63 0 5.4 3.1 11.5 11.4 11.5a19.35 19.35 0 004-.4C415.9 449.2 480 363.1 480 261.7 480 134.9 379.7 32 256 32z" /> </svg> ); } export default GithubIcon;
nobruf/shadcn-landing-page/components/icons/github-icon.tsx
{ "file_path": "nobruf/shadcn-landing-page/components/icons/github-icon.tsx", "repo_id": "nobruf/shadcn-landing-page", "token_count": 668 }
101
"use client"; import * as React from "react"; import { ThemeProvider as NextThemesProvider } from "next-themes"; import { type ThemeProviderProps } from "next-themes/dist/types"; export function ThemeProvider({ children, ...props }: ThemeProviderProps) { return <NextThemesProvider {...props}>{children}</NextThemesProvider>; }
nobruf/shadcn-landing-page/components/layout/theme-provider.tsx
{ "file_path": "nobruf/shadcn-landing-page/components/layout/theme-provider.tsx", "repo_id": "nobruf/shadcn-landing-page", "token_count": 99 }
102
import Link from "next/link" import { allGuides } from "contentlayer/generated" import { compareDesc } from "date-fns" import { formatDate } from "@/lib/utils" import { DocsPageHeader } from "@/components/page-header" export const metadata = { title: "Guides", description: "This section includes end-to-end guides for developing Next.js 13 apps.", } export default function GuidesPage() { const guides = allGuides .filter((guide) => guide.published) .sort((a, b) => { return compareDesc(new Date(a.date), new Date(b.date)) }) return ( <div className="py-6 lg:py-10"> <DocsPageHeader heading="Guides" text="This section includes end-to-end guides for developing Next.js 13 apps." /> {guides?.length ? ( <div className="grid gap-4 md:grid-cols-2 md:gap-6"> {guides.map((guide) => ( <article key={guide._id} className="group relative rounded-lg border p-6 shadow-md transition-shadow hover:shadow-lg" > {guide.featured && ( <span className="absolute right-4 top-4 rounded-full px-3 py-1 text-xs font-medium"> Featured </span> )} <div className="flex flex-col justify-between space-y-4"> <div className="space-y-2"> <h2 className="text-xl font-medium tracking-tight"> {guide.title} </h2> {guide.description && ( <p className="text-muted-foreground">{guide.description}</p> )} </div> {guide.date && ( <p className="text-sm text-muted-foreground"> {formatDate(guide.date)} </p> )} </div> <Link href={guide.slug} className="absolute inset-0"> <span className="sr-only">View</span> </Link> </article> ))} </div> ) : ( <p>No guides published.</p> )} </div> ) }
shadcn-ui/taxonomy/app/(docs)/guides/page.tsx
{ "file_path": "shadcn-ui/taxonomy/app/(docs)/guides/page.tsx", "repo_id": "shadcn-ui/taxonomy", "token_count": 1084 }
103
import { getServerSession } from "next-auth/next" import { z } from "zod" import { authOptions } from "@/lib/auth" import { db } from "@/lib/db" import { userNameSchema } from "@/lib/validations/user" const routeContextSchema = z.object({ params: z.object({ userId: z.string(), }), }) export async function PATCH( req: Request, context: z.infer<typeof routeContextSchema> ) { try { // Validate the route context. const { params } = routeContextSchema.parse(context) // Ensure user is authentication and has access to this user. const session = await getServerSession(authOptions) if (!session?.user || params.userId !== session?.user.id) { return new Response(null, { status: 403 }) } // Get the request body and validate it. const body = await req.json() const payload = userNameSchema.parse(body) // Update the user. await db.user.update({ where: { id: session.user.id, }, data: { name: payload.name, }, }) return new Response(null, { status: 200 }) } catch (error) { if (error instanceof z.ZodError) { return new Response(JSON.stringify(error.issues), { status: 422 }) } return new Response(null, { status: 500 }) } }
shadcn-ui/taxonomy/app/api/users/[userId]/route.ts
{ "file_path": "shadcn-ui/taxonomy/app/api/users/[userId]/route.ts", "repo_id": "shadcn-ui/taxonomy", "token_count": 466 }
104
import * as React from "react" import { cn } from "@/lib/utils" import { Icons } from "@/components/icons" interface EmptyPlaceholderProps extends React.HTMLAttributes<HTMLDivElement> {} export function EmptyPlaceholder({ className, children, ...props }: EmptyPlaceholderProps) { return ( <div className={cn( "flex min-h-[400px] flex-col items-center justify-center rounded-md border border-dashed p-8 text-center animate-in fade-in-50", className )} {...props} > <div className="mx-auto flex max-w-[420px] flex-col items-center justify-center text-center"> {children} </div> </div> ) } interface EmptyPlaceholderIconProps extends Partial<React.SVGProps<SVGSVGElement>> { name: keyof typeof Icons } EmptyPlaceholder.Icon = function EmptyPlaceHolderIcon({ name, className, ...props }: EmptyPlaceholderIconProps) { const Icon = Icons[name] if (!Icon) { return null } return ( <div className="flex h-20 w-20 items-center justify-center rounded-full bg-muted"> <Icon className={cn("h-10 w-10", className)} {...props} /> </div> ) } interface EmptyPlacholderTitleProps extends React.HTMLAttributes<HTMLHeadingElement> {} EmptyPlaceholder.Title = function EmptyPlaceholderTitle({ className, ...props }: EmptyPlacholderTitleProps) { return ( <h2 className={cn("mt-6 text-xl font-semibold", className)} {...props} /> ) } interface EmptyPlacholderDescriptionProps extends React.HTMLAttributes<HTMLParagraphElement> {} EmptyPlaceholder.Description = function EmptyPlaceholderDescription({ className, ...props }: EmptyPlacholderDescriptionProps) { return ( <p className={cn( "mb-8 mt-2 text-center text-sm font-normal leading-6 text-muted-foreground", className )} {...props} /> ) }
shadcn-ui/taxonomy/components/empty-placeholder.tsx
{ "file_path": "shadcn-ui/taxonomy/components/empty-placeholder.tsx", "repo_id": "shadcn-ui/taxonomy", "token_count": 697 }
105
"use client" import Link from "next/link" import { usePathname } from "next/navigation" import { SidebarNavItem } from "types" import { cn } from "@/lib/utils" export interface DocsSidebarNavProps { items: SidebarNavItem[] } export function DocsSidebarNav({ items }: DocsSidebarNavProps) { const pathname = usePathname() return items.length ? ( <div className="w-full"> {items.map((item, index) => ( <div key={index} className={cn("pb-8")}> <h4 className="mb-1 rounded-md px-2 py-1 text-sm font-medium"> {item.title} </h4> {item.items ? ( <DocsSidebarNavItems items={item.items} pathname={pathname} /> ) : null} </div> ))} </div> ) : null } interface DocsSidebarNavItemsProps { items: SidebarNavItem[] pathname: string | null } export function DocsSidebarNavItems({ items, pathname, }: DocsSidebarNavItemsProps) { return items?.length ? ( <div className="grid grid-flow-row auto-rows-max text-sm"> {items.map((item, index) => !item.disabled && item.href ? ( <Link key={index} href={item.href} className={cn( "flex w-full items-center rounded-md p-2 hover:underline", { "bg-muted": pathname === item.href, } )} target={item.external ? "_blank" : ""} rel={item.external ? "noreferrer" : ""} > {item.title} </Link> ) : ( <span className="flex w-full cursor-not-allowed items-center rounded-md p-2 opacity-60"> {item.title} </span> ) )} </div> ) : null }
shadcn-ui/taxonomy/components/sidebar-nav.tsx
{ "file_path": "shadcn-ui/taxonomy/components/sidebar-nav.tsx", "repo_id": "shadcn-ui/taxonomy", "token_count": 835 }
106
import { cn } from "@/lib/utils" function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) { return ( <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} /> ) } export { Skeleton }
shadcn-ui/taxonomy/components/ui/skeleton.tsx
{ "file_path": "shadcn-ui/taxonomy/components/ui/skeleton.tsx", "repo_id": "shadcn-ui/taxonomy", "token_count": 106 }
107
import { MarketingConfig } from "types" export const marketingConfig: MarketingConfig = { mainNav: [ { title: "Features", href: "/#features", }, { title: "Pricing", href: "/pricing", }, { title: "Blog", href: "/blog", }, { title: "Documentation", href: "/docs", }, ], }
shadcn-ui/taxonomy/config/marketing.ts
{ "file_path": "shadcn-ui/taxonomy/config/marketing.ts", "repo_id": "shadcn-ui/taxonomy", "token_count": 165 }
108
import * as z from "zod" export const postPatchSchema = z.object({ title: z.string().min(3).max(128).optional(), // TODO: Type this properly from editorjs block types? content: z.any().optional(), })
shadcn-ui/taxonomy/lib/validations/post.ts
{ "file_path": "shadcn-ui/taxonomy/lib/validations/post.ts", "repo_id": "shadcn-ui/taxonomy", "token_count": 68 }
109
# .kodiak.toml version = 1 [merge] automerge_label = "automerge" require_automerge_label = true method = "squash" delete_branch_on_merge = true optimistic_updates = false prioritize_ready_to_merge = true notify_on_conflict = true [merge.message] title = "pull_request_title" body = "pull_request_body" include_pr_number = true body_type = "markdown" strip_html_comments = true
shadcn-ui/ui/.kodiak.toml
{ "file_path": "shadcn-ui/ui/.kodiak.toml", "repo_id": "shadcn-ui/ui", "token_count": 145 }
110
import { LoginForm } from "@/registry/default/block/login-01/components/login-form" export const iframeHeight = "870px" export const containerClassName = "w-full h-full" export default function Page() { return ( <div className="flex h-screen w-full items-center justify-center px-4"> <LoginForm /> </div> ) }
shadcn-ui/ui/apps/www/__registry__/default/block/login-01.tsx
{ "file_path": "shadcn-ui/ui/apps/www/__registry__/default/block/login-01.tsx", "repo_id": "shadcn-ui/ui", "token_count": 116 }
111
"use client" import { TrendingUp } from "lucide-react" import { Area, AreaChart, CartesianGrid, XAxis } from "recharts" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/registry/new-york/ui/card" import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent, } from "@/registry/new-york/ui/chart" export const description = "A stacked area chart with expand stacking" const chartData = [ { month: "January", desktop: 186, mobile: 80, other: 45 }, { month: "February", desktop: 305, mobile: 200, other: 100 }, { month: "March", desktop: 237, mobile: 120, other: 150 }, { month: "April", desktop: 73, mobile: 190, other: 50 }, { month: "May", desktop: 209, mobile: 130, other: 100 }, { month: "June", desktop: 214, mobile: 140, other: 160 }, ] const chartConfig = { desktop: { label: "Desktop", color: "hsl(var(--chart-1))", }, mobile: { label: "Mobile", color: "hsl(var(--chart-2))", }, other: { label: "Other", color: "hsl(var(--chart-3))", }, } satisfies ChartConfig export default function Component() { return ( <Card> <CardHeader> <CardTitle>Area Chart - Stacked Expanded</CardTitle> <CardDescription> Showing total visitors for the last 6months </CardDescription> </CardHeader> <CardContent> <ChartContainer config={chartConfig}> <AreaChart accessibilityLayer data={chartData} margin={{ left: 12, right: 12, top: 12, }} stackOffset="expand" > <CartesianGrid vertical={false} /> <XAxis dataKey="month" tickLine={false} axisLine={false} tickMargin={8} tickFormatter={(value) => value.slice(0, 3)} /> <ChartTooltip cursor={false} content={<ChartTooltipContent indicator="line" />} /> <Area dataKey="other" type="natural" fill="var(--color-other)" fillOpacity={0.1} stroke="var(--color-other)" stackId="a" /> <Area dataKey="mobile" type="natural" fill="var(--color-mobile)" fillOpacity={0.4} stroke="var(--color-mobile)" stackId="a" /> <Area dataKey="desktop" type="natural" fill="var(--color-desktop)" fillOpacity={0.4} stroke="var(--color-desktop)" stackId="a" /> </AreaChart> </ChartContainer> </CardContent> <CardFooter> <div className="flex w-full items-start gap-2 text-sm"> <div className="grid gap-2"> <div className="flex items-center gap-2 font-medium leading-none"> Trending up by 5.2% this month <TrendingUp className="h-4 w-4" /> </div> <div className="flex items-center gap-2 leading-none text-muted-foreground"> January - June 2024 </div> </div> </div> </CardFooter> </Card> ) }
shadcn-ui/ui/apps/www/__registry__/new-york/block/chart-area-stacked-expand.tsx
{ "file_path": "shadcn-ui/ui/apps/www/__registry__/new-york/block/chart-area-stacked-expand.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1663 }
112
import { THEMES } from "@/lib/themes" import { ChartDisplay } from "@/components/chart-display" import { ChartsNav } from "@/components/charts-nav" import { ThemesSwitcher } from "@/components/themes-selector" import { ThemesStyle } from "@/components/themes-styles" import { Separator } from "@/registry/new-york/ui/separator" import * as Charts from "@/app/(app)/charts/charts" export default function ChartsPage() { return ( <div className="grid gap-4"> <ChartsNav className="[&>a:first-child]:bg-muted [&>a:first-child]:font-medium [&>a:first-child]:text-primary" /> <ThemesStyle /> <div className="gap-6 md:flex md:flex-row-reverse md:items-start"> <ThemesSwitcher themes={THEMES} className="fixed inset-x-0 bottom-0 z-40 flex bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 lg:sticky lg:bottom-auto lg:top-20" /> <div className="grid flex-1 gap-12"> <h2 className="sr-only">Examples</h2> <div id="examples" className="grid flex-1 scroll-mt-20 items-start gap-10 md:grid-cols-2 md:gap-6 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-area-stacked"> <Charts.ChartAreaStacked /> </ChartDisplay> <ChartDisplay name="chart-bar-multiple"> <Charts.ChartBarMultiple /> </ChartDisplay> <ChartDisplay name="chart-pie-donut-text" className="[&_[data-chart]]:xl:max-h-[243px]" > <Charts.ChartPieDonutText /> </ChartDisplay> </div> <Separator /> <div id="area-chart" className="grid flex-1 scroll-mt-20 items-start gap-10 md:grid-cols-2 md:gap-6 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-area-default"> <Charts.ChartAreaDefault /> </ChartDisplay> <ChartDisplay name="chart-area-linear"> <Charts.ChartAreaLinear /> </ChartDisplay> <ChartDisplay name="chart-area-step"> <Charts.ChartAreaStep /> </ChartDisplay> <ChartDisplay name="chart-area-stacked"> <Charts.ChartAreaStacked /> </ChartDisplay> <ChartDisplay name="chart-area-stacked-expand"> <Charts.ChartAreaStackedExpand /> </ChartDisplay> <ChartDisplay name="chart-area-legend"> <Charts.ChartAreaLegend /> </ChartDisplay> <ChartDisplay name="chart-area-icons"> <Charts.ChartAreaIcons /> </ChartDisplay> <ChartDisplay name="chart-area-gradient"> <Charts.ChartAreaGradient /> </ChartDisplay> <ChartDisplay name="chart-area-axes"> <Charts.ChartAreaAxes /> </ChartDisplay> <div className="md:col-span-2 lg:col-span-3"> <ChartDisplay name="chart-area-interactive"> <Charts.ChartAreaInteractive /> </ChartDisplay> </div> </div> <Separator /> <div id="bar-chart" className="grid flex-1 scroll-mt-20 items-start gap-10 md:grid-cols-2 md:gap-6 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-bar-default"> <Charts.ChartBarDefault /> </ChartDisplay> <ChartDisplay name="chart-bar-horizontal"> <Charts.ChartBarHorizontal /> </ChartDisplay> <ChartDisplay name="chart-bar-multiple"> <Charts.ChartBarMultiple /> </ChartDisplay> <ChartDisplay name="chart-bar-label"> <Charts.ChartBarLabel /> </ChartDisplay> <ChartDisplay name="chart-bar-label-custom"> <Charts.ChartBarLabelCustom /> </ChartDisplay> <ChartDisplay name="chart-bar-mixed"> <Charts.ChartBarMixed /> </ChartDisplay> <ChartDisplay name="chart-bar-stacked"> <Charts.ChartBarStacked /> </ChartDisplay> <ChartDisplay name="chart-bar-active"> <Charts.ChartBarActive /> </ChartDisplay> <ChartDisplay name="chart-bar-negative"> <Charts.ChartBarNegative /> </ChartDisplay> <div className="md:col-span-2 lg:col-span-3"> <ChartDisplay name="chart-bar-interactive"> <Charts.ChartBarInteractive /> </ChartDisplay> </div> </div> <Separator /> <div id="line-chart" className="grid flex-1 scroll-mt-20 items-start gap-10 md:grid-cols-2 md:gap-6 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-line-default"> <Charts.ChartLineDefault /> </ChartDisplay> <ChartDisplay name="chart-line-linear"> <Charts.ChartLineLinear /> </ChartDisplay> <ChartDisplay name="chart-line-step"> <Charts.ChartLineStep /> </ChartDisplay> <ChartDisplay name="chart-line-multiple"> <Charts.ChartLineMultiple /> </ChartDisplay> <ChartDisplay name="chart-line-dots"> <Charts.ChartLineDots /> </ChartDisplay> <ChartDisplay name="chart-line-dots-custom"> <Charts.ChartLineDotsCustom /> </ChartDisplay> <ChartDisplay name="chart-line-dots-colors"> <Charts.ChartLineDotsColors /> </ChartDisplay> <ChartDisplay name="chart-line-label"> <Charts.ChartLineLabel /> </ChartDisplay> <ChartDisplay name="chart-line-label-custom"> <Charts.ChartLineLabelCustom /> </ChartDisplay> <div className="md:col-span-2 lg:col-span-3"> <ChartDisplay name="chart-line-interactive"> <Charts.ChartLineInteractive /> </ChartDisplay> </div> </div> <Separator /> <div id="pie-chart" className="grid flex-1 scroll-mt-20 items-start gap-10 md:grid-cols-2 md:gap-6 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-pie-simple"> <Charts.ChartPieSimple /> </ChartDisplay> <ChartDisplay name="chart-pie-separator-none"> <Charts.ChartPieSeparatorNone /> </ChartDisplay> <ChartDisplay name="chart-pie-label"> <Charts.ChartPieLabel /> </ChartDisplay> <ChartDisplay name="chart-pie-label-custom"> <Charts.ChartPieLabelCustom /> </ChartDisplay> <ChartDisplay name="chart-pie-label-list"> <Charts.ChartPieLabelList /> </ChartDisplay> <ChartDisplay name="chart-pie-legend"> <Charts.ChartPieLegend /> </ChartDisplay> <ChartDisplay name="chart-pie-donut"> <Charts.ChartPieDonut /> </ChartDisplay> <ChartDisplay name="chart-pie-donut-active"> <Charts.ChartPieDonutActive /> </ChartDisplay> <ChartDisplay name="chart-pie-donut-text"> <Charts.ChartPieDonutText /> </ChartDisplay> <ChartDisplay name="chart-pie-stacked"> <Charts.ChartPieStacked /> </ChartDisplay> <ChartDisplay name="chart-pie-interactive"> <Charts.ChartPieInteractive /> </ChartDisplay> </div> <Separator /> <div id="radar-chart" className="grid flex-1 scroll-mt-20 gap-6 md:grid-cols-2 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-radar-default"> <Charts.ChartRadarDefault /> </ChartDisplay> <ChartDisplay name="chart-radar-dots"> <Charts.ChartRadarDots /> </ChartDisplay> <ChartDisplay name="chart-radar-multiple"> <Charts.ChartRadarMultiple /> </ChartDisplay> <ChartDisplay name="chart-radar-lines-only"> <Charts.ChartRadarLinesOnly /> </ChartDisplay> <ChartDisplay name="chart-radar-label-custom"> <Charts.ChartRadarLabelCustom /> </ChartDisplay> <ChartDisplay name="chart-radar-radius"> <Charts.ChartRadarRadius /> </ChartDisplay> <ChartDisplay name="chart-radar-grid-custom"> <Charts.ChartRadarGridCustom /> </ChartDisplay> <ChartDisplay name="chart-radar-grid-fill"> <Charts.ChartRadarGridFill /> </ChartDisplay> <ChartDisplay name="chart-radar-grid-none"> <Charts.ChartRadarGridNone /> </ChartDisplay> <ChartDisplay name="chart-radar-grid-circle"> <Charts.ChartRadarGridCircle /> </ChartDisplay> <ChartDisplay name="chart-radar-grid-circle-no-lines"> <Charts.ChartRadarGridCircleNoLines /> </ChartDisplay> <ChartDisplay name="chart-radar-grid-circle-fill"> <Charts.ChartRadarGridCircleFill /> </ChartDisplay> <ChartDisplay name="chart-radar-legend"> <Charts.ChartRadarLegend /> </ChartDisplay> <ChartDisplay name="chart-radar-icons"> <Charts.ChartRadarIcons /> </ChartDisplay> </div> <Separator /> <div id="radial-chart" className="grid flex-1 scroll-mt-20 gap-6 md:grid-cols-2 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-radial-simple"> <Charts.ChartRadialSimple /> </ChartDisplay> <ChartDisplay name="chart-radial-label"> <Charts.ChartRadialLabel /> </ChartDisplay> <ChartDisplay name="chart-radial-grid"> <Charts.ChartRadialGrid /> </ChartDisplay> <ChartDisplay name="chart-radial-text"> <Charts.ChartRadialText /> </ChartDisplay> <ChartDisplay name="chart-radial-shape"> <Charts.ChartRadialShape /> </ChartDisplay> <ChartDisplay name="chart-radial-stacked"> <Charts.ChartRadialStacked /> </ChartDisplay> </div> <Separator /> <div id="tooltip" className="chart-wrapper grid flex-1 scroll-mt-20 items-start gap-10 md:grid-cols-2 md:gap-6 lg:grid-cols-3 xl:gap-10" > <ChartDisplay name="chart-tooltip-default"> <Charts.ChartTooltipDefault /> </ChartDisplay> <ChartDisplay name="chart-tooltip-indicator-line"> <Charts.ChartTooltipIndicatorLine /> </ChartDisplay> <ChartDisplay name="chart-tooltip-indicator-none"> <Charts.ChartTooltipIndicatorNone /> </ChartDisplay> <ChartDisplay name="chart-tooltip-label-custom"> <Charts.ChartTooltipLabelCustom /> </ChartDisplay> <ChartDisplay name="chart-tooltip-label-formatter"> <Charts.ChartTooltipLabelFormatter /> </ChartDisplay> <ChartDisplay name="chart-tooltip-label-none"> <Charts.ChartTooltipLabelNone /> </ChartDisplay> <ChartDisplay name="chart-tooltip-formatter"> <Charts.ChartTooltipFormatter /> </ChartDisplay> <ChartDisplay name="chart-tooltip-icons"> <Charts.ChartTooltipIcons /> </ChartDisplay> <ChartDisplay name="chart-tooltip-advanced"> <Charts.ChartTooltipAdvanced /> </ChartDisplay> </div> </div> </div> </div> ) }
shadcn-ui/ui/apps/www/app/(app)/charts/page.tsx
{ "file_path": "shadcn-ui/ui/apps/www/app/(app)/charts/page.tsx", "repo_id": "shadcn-ui/ui", "token_count": 6317 }
113
import { Metadata } from "next" import Image from "next/image" import { cn } from "@/lib/utils" import { DemoCookieSettings } from "./components/cookie-settings" import { DemoCreateAccount } from "./components/create-account" import { DemoDatePicker } from "./components/date-picker" import { DemoGithub } from "./components/github-card" import { DemoNotifications } from "./components/notifications" import { DemoPaymentMethod } from "./components/payment-method" import { DemoReportAnIssue } from "./components/report-an-issue" import { DemoShareDocument } from "./components/share-document" import { DemoTeamMembers } from "./components/team-members" export const metadata: Metadata = { title: "Cards", description: "Examples of cards built using the components.", } function DemoContainer({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) { return ( <div className={cn( "flex items-center justify-center [&>div]:w-full", className )} {...props} /> ) } export default function CardsPage() { return ( <> <div className="md:hidden"> <Image src="/examples/cards-light.png" width={1280} height={1214} alt="Cards" className="block dark:hidden" /> <Image src="/examples/cards-dark.png" width={1280} height={1214} alt="Cards" className="hidden dark:block" /> </div> <div className="hidden items-start justify-center gap-6 rounded-lg p-8 md:grid lg:grid-cols-2 xl:grid-cols-3"> <div className="col-span-2 grid items-start gap-6 lg:col-span-1"> <DemoContainer> <DemoCreateAccount /> </DemoContainer> <DemoContainer> <DemoPaymentMethod /> </DemoContainer> </div> <div className="col-span-2 grid items-start gap-6 lg:col-span-1"> <DemoContainer> <DemoTeamMembers /> </DemoContainer> <DemoContainer> <DemoShareDocument /> </DemoContainer> <DemoContainer> <DemoDatePicker /> </DemoContainer> <DemoContainer> <DemoNotifications /> </DemoContainer> </div> <div className="col-span-2 grid items-start gap-6 lg:col-span-2 lg:grid-cols-2 xl:col-span-1 xl:grid-cols-1"> <DemoContainer> <DemoReportAnIssue /> </DemoContainer> <DemoContainer> <DemoGithub /> </DemoContainer> <DemoContainer> <DemoCookieSettings /> </DemoContainer> </div> </div> </> ) }
shadcn-ui/ui/apps/www/app/(app)/examples/cards/page.tsx
{ "file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/cards/page.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1254 }
114
import { Metadata } from "next" import Image from "next/image" import { Separator } from "@/registry/new-york/ui/separator" import { SidebarNav } from "@/app/(app)/examples/forms/components/sidebar-nav" export const metadata: Metadata = { title: "Forms", description: "Advanced form example using react-hook-form and Zod.", } const sidebarNavItems = [ { title: "Profile", href: "/examples/forms", }, { title: "Account", href: "/examples/forms/account", }, { title: "Appearance", href: "/examples/forms/appearance", }, { title: "Notifications", href: "/examples/forms/notifications", }, { title: "Display", href: "/examples/forms/display", }, ] interface SettingsLayoutProps { children: React.ReactNode } export default function SettingsLayout({ children }: SettingsLayoutProps) { return ( <> <div className="md:hidden"> <Image src="/examples/forms-light.png" width={1280} height={791} alt="Forms" className="block dark:hidden" /> <Image src="/examples/forms-dark.png" width={1280} height={791} alt="Forms" className="hidden dark:block" /> </div> <div className="hidden space-y-6 p-10 pb-16 md:block"> <div className="space-y-0.5"> <h2 className="text-2xl font-bold tracking-tight">Settings</h2> <p className="text-muted-foreground"> Manage your account settings and set e-mail preferences. </p> </div> <Separator className="my-6" /> <div className="flex flex-col space-y-8 lg:flex-row lg:space-x-12 lg:space-y-0"> <aside className="-mx-4 lg:w-1/5"> <SidebarNav items={sidebarNavItems} /> </aside> <div className="flex-1 lg:max-w-2xl">{children}</div> </div> </div> </> ) }
shadcn-ui/ui/apps/www/app/(app)/examples/forms/layout.tsx
{ "file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/forms/layout.tsx", "repo_id": "shadcn-ui/ui", "token_count": 891 }
115
import { Button } from "@/registry/new-york/ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/registry/new-york/ui/dialog" import { Input } from "@/registry/new-york/ui/input" import { Label } from "@/registry/new-york/ui/label" export function PodcastEmptyPlaceholder() { return ( <div className="flex h-[450px] shrink-0 items-center justify-center rounded-md border border-dashed"> <div className="mx-auto flex max-w-[420px] flex-col items-center justify-center text-center"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" className="h-10 w-10 text-muted-foreground" viewBox="0 0 24 24" > <circle cx="12" cy="11" r="1" /> <path d="M11 17a1 1 0 0 1 2 0c0 .5-.34 3-.5 4.5a.5.5 0 0 1-1 0c-.16-1.5-.5-4-.5-4.5ZM8 14a5 5 0 1 1 8 0" /> <path d="M17 18.5a9 9 0 1 0-10 0" /> </svg> <h3 className="mt-4 text-lg font-semibold">No episodes added</h3> <p className="mb-4 mt-2 text-sm text-muted-foreground"> You have not added any podcasts. Add one below. </p> <Dialog> <DialogTrigger asChild> <Button size="sm" className="relative"> Add Podcast </Button> </DialogTrigger> <DialogContent> <DialogHeader> <DialogTitle>Add Podcast</DialogTitle> <DialogDescription> Copy and paste the podcast feed URL to import. </DialogDescription> </DialogHeader> <div className="grid gap-4 py-4"> <div className="grid gap-2"> <Label htmlFor="url">Podcast URL</Label> <Input id="url" placeholder="https://example.com/feed.xml" /> </div> </div> <DialogFooter> <Button>Import Podcast</Button> </DialogFooter> </DialogContent> </Dialog> </div> </div> ) }
shadcn-ui/ui/apps/www/app/(app)/examples/music/components/podcast-empty-placeholder.tsx
{ "file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/music/components/podcast-empty-placeholder.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1089 }
116
import { Metadata } from "next" import Image from "next/image" import { CounterClockwiseClockIcon } from "@radix-ui/react-icons" import { Button } from "@/registry/new-york/ui/button" import { HoverCard, HoverCardContent, HoverCardTrigger, } from "@/registry/new-york/ui/hover-card" import { Label } from "@/registry/new-york/ui/label" import { Separator } from "@/registry/new-york/ui/separator" import { Tabs, TabsContent, TabsList, TabsTrigger, } from "@/registry/new-york/ui/tabs" import { Textarea } from "@/registry/new-york/ui/textarea" import { CodeViewer } from "./components/code-viewer" import { MaxLengthSelector } from "./components/maxlength-selector" import { ModelSelector } from "./components/model-selector" import { PresetActions } from "./components/preset-actions" import { PresetSave } from "./components/preset-save" import { PresetSelector } from "./components/preset-selector" import { PresetShare } from "./components/preset-share" import { TemperatureSelector } from "./components/temperature-selector" import { TopPSelector } from "./components/top-p-selector" import { models, types } from "./data/models" import { presets } from "./data/presets" export const metadata: Metadata = { title: "Playground", description: "The OpenAI Playground built using the components.", } export default function PlaygroundPage() { return ( <> <div className="md:hidden"> <Image src="/examples/playground-light.png" width={1280} height={916} alt="Playground" className="block dark:hidden" /> <Image src="/examples/playground-dark.png" width={1280} height={916} alt="Playground" className="hidden dark:block" /> </div> <div className="hidden h-full flex-col md:flex"> <div className="container flex flex-col items-start justify-between space-y-2 py-4 sm:flex-row sm:items-center sm:space-y-0 md:h-16"> <h2 className="text-lg font-semibold">Playground</h2> <div className="ml-auto flex w-full space-x-2 sm:justify-end"> <PresetSelector presets={presets} /> <PresetSave /> <div className="hidden space-x-2 md:flex"> <CodeViewer /> <PresetShare /> </div> <PresetActions /> </div> </div> <Separator /> <Tabs defaultValue="complete" className="flex-1"> <div className="container h-full py-6"> <div className="grid h-full items-stretch gap-6 md:grid-cols-[1fr_200px]"> <div className="hidden flex-col space-y-4 sm:flex md:order-2"> <div className="grid gap-2"> <HoverCard openDelay={200}> <HoverCardTrigger asChild> <span className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"> Mode </span> </HoverCardTrigger> <HoverCardContent className="w-[320px] text-sm" side="left"> Choose the interface that best suits your task. You can provide: a simple prompt to complete, starting and ending text to insert a completion within, or some text with instructions to edit it. </HoverCardContent> </HoverCard> <TabsList className="grid grid-cols-3"> <TabsTrigger value="complete"> <span className="sr-only">Complete</span> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="none" className="h-5 w-5" > <rect x="4" y="3" width="12" height="2" rx="1" fill="currentColor" ></rect> <rect x="4" y="7" width="12" height="2" rx="1" fill="currentColor" ></rect> <rect x="4" y="11" width="3" height="2" rx="1" fill="currentColor" ></rect> <rect x="4" y="15" width="3" height="2" rx="1" fill="currentColor" ></rect> <rect x="8.5" y="11" width="3" height="2" rx="1" fill="currentColor" ></rect> <rect x="8.5" y="15" width="3" height="2" rx="1" fill="currentColor" ></rect> <rect x="13" y="11" width="3" height="2" rx="1" fill="currentColor" ></rect> </svg> </TabsTrigger> <TabsTrigger value="insert"> <span className="sr-only">Insert</span> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="none" className="h-5 w-5" > <path fillRule="evenodd" clipRule="evenodd" d="M14.491 7.769a.888.888 0 0 1 .287.648.888.888 0 0 1-.287.648l-3.916 3.667a1.013 1.013 0 0 1-.692.268c-.26 0-.509-.097-.692-.268L5.275 9.065A.886.886 0 0 1 5 8.42a.889.889 0 0 1 .287-.64c.181-.17.427-.267.683-.269.257-.002.504.09.69.258L8.903 9.87V3.917c0-.243.103-.477.287-.649.183-.171.432-.268.692-.268.26 0 .509.097.692.268a.888.888 0 0 1 .287.649V9.87l2.245-2.102c.183-.172.432-.269.692-.269.26 0 .508.097.692.269Z" fill="currentColor" ></path> <rect x="4" y="15" width="3" height="2" rx="1" fill="currentColor" ></rect> <rect x="8.5" y="15" width="3" height="2" rx="1" fill="currentColor" ></rect> <rect x="13" y="15" width="3" height="2" rx="1" fill="currentColor" ></rect> </svg> </TabsTrigger> <TabsTrigger value="edit"> <span className="sr-only">Edit</span> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="none" className="h-5 w-5" > <rect x="4" y="3" width="12" height="2" rx="1" fill="currentColor" ></rect> <rect x="4" y="7" width="12" height="2" rx="1" fill="currentColor" ></rect> <rect x="4" y="11" width="3" height="2" rx="1" fill="currentColor" ></rect> <rect x="4" y="15" width="4" height="2" rx="1" fill="currentColor" ></rect> <rect x="8.5" y="11" width="3" height="2" rx="1" fill="currentColor" ></rect> <path d="M17.154 11.346a1.182 1.182 0 0 0-1.671 0L11 15.829V17.5h1.671l4.483-4.483a1.182 1.182 0 0 0 0-1.671Z" fill="currentColor" ></path> </svg> </TabsTrigger> </TabsList> </div> <ModelSelector types={types} models={models} /> <TemperatureSelector defaultValue={[0.56]} /> <MaxLengthSelector defaultValue={[256]} /> <TopPSelector defaultValue={[0.9]} /> </div> <div className="md:order-1"> <TabsContent value="complete" className="mt-0 border-0 p-0"> <div className="flex h-full flex-col space-y-4"> <Textarea placeholder="Write a tagline for an ice cream shop" className="min-h-[400px] flex-1 p-4 md:min-h-[700px] lg:min-h-[700px]" /> <div className="flex items-center space-x-2"> <Button>Submit</Button> <Button variant="secondary"> <span className="sr-only">Show history</span> <CounterClockwiseClockIcon className="h-4 w-4" /> </Button> </div> </div> </TabsContent> <TabsContent value="insert" className="mt-0 border-0 p-0"> <div className="flex flex-col space-y-4"> <div className="grid h-full grid-rows-2 gap-6 lg:grid-cols-2 lg:grid-rows-1"> <Textarea placeholder="We're writing to [inset]. Congrats from OpenAI!" className="h-full min-h-[300px] lg:min-h-[700px] xl:min-h-[700px]" /> <div className="rounded-md border bg-muted"></div> </div> <div className="flex items-center space-x-2"> <Button>Submit</Button> <Button variant="secondary"> <span className="sr-only">Show history</span> <CounterClockwiseClockIcon className="h-4 w-4" /> </Button> </div> </div> </TabsContent> <TabsContent value="edit" className="mt-0 border-0 p-0"> <div className="flex flex-col space-y-4"> <div className="grid h-full gap-6 lg:grid-cols-2"> <div className="flex flex-col space-y-4"> <div className="flex flex-1 flex-col space-y-2"> <Label htmlFor="input">Input</Label> <Textarea id="input" placeholder="We is going to the market." className="flex-1 lg:min-h-[580px]" /> </div> <div className="flex flex-col space-y-2"> <Label htmlFor="instructions">Instructions</Label> <Textarea id="instructions" placeholder="Fix the grammar." /> </div> </div> <div className="mt-[21px] min-h-[400px] rounded-md border bg-muted lg:min-h-[700px]" /> </div> <div className="flex items-center space-x-2"> <Button>Submit</Button> <Button variant="secondary"> <span className="sr-only">Show history</span> <CounterClockwiseClockIcon className="h-4 w-4" /> </Button> </div> </div> </TabsContent> </div> </div> </div> </Tabs> </div> </> ) }
shadcn-ui/ui/apps/www/app/(app)/examples/playground/page.tsx
{ "file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/playground/page.tsx", "repo_id": "shadcn-ui/ui", "token_count": 8972 }
117
import Image from "next/image" import Link from "next/link" import { siteConfig } from "@/config/site" import { Announcement } from "@/components/announcement" import { ExamplesNav } from "@/components/examples-nav" import { PageActions, PageHeader, PageHeaderDescription, PageHeaderHeading, } from "@/components/page-header" import { Button } from "@/registry/new-york/ui/button" import MailPage from "@/app/(app)/examples/mail/page" export default function IndexPage() { return ( <div className="container relative"> <PageHeader> <Announcement /> <PageHeaderHeading>Build your component library</PageHeaderHeading> <PageHeaderDescription> Beautifully designed components that you can copy and paste into your apps. </PageHeaderDescription> <PageActions> <Button asChild size="sm"> <Link href="/docs">Get Started</Link> </Button> <Button asChild size="sm" variant="ghost"> <Link target="_blank" rel="noreferrer" href={siteConfig.links.github} > GitHub </Link> </Button> </PageActions> </PageHeader> <ExamplesNav className="[&>a:first-child]:text-primary" /> <section className="overflow-hidden rounded-lg border bg-background shadow-md md:hidden md:shadow-xl"> <Image src="/examples/mail-dark.png" width={1280} height={727} alt="Mail" className="hidden dark:block" /> <Image src="/examples/mail-light.png" width={1280} height={727} alt="Mail" className="block dark:hidden" /> </section> <section className="hidden md:block"> <div className="overflow-hidden rounded-lg border bg-background shadow"> <MailPage /> </div> </section> </div> ) }
shadcn-ui/ui/apps/www/app/(app)/page.tsx
{ "file_path": "shadcn-ui/ui/apps/www/app/(app)/page.tsx", "repo_id": "shadcn-ui/ui", "token_count": 883 }
118
"use client" import * as React from "react" import { CircleHelp, Monitor, Smartphone, Tablet } from "lucide-react" import { ImperativePanelHandle } from "react-resizable-panels" import { trackEvent } from "@/lib/events" import { cn } from "@/lib/utils" import { useLiftMode } from "@/hooks/use-lift-mode" import { BlockCopyButton } from "@/components/block-copy-button" import { StyleSwitcher } from "@/components/style-switcher" import { V0Button } from "@/components/v0-button" import { Badge } from "@/registry/new-york/ui/badge" import { Label } from "@/registry/new-york/ui/label" import { Popover, PopoverContent, PopoverTrigger, } from "@/registry/new-york/ui/popover" import { Separator } from "@/registry/new-york/ui/separator" import { Switch } from "@/registry/new-york/ui/switch" import { TabsList, TabsTrigger } from "@/registry/new-york/ui/tabs" import { ToggleGroup, ToggleGroupItem, } from "@/registry/new-york/ui/toggle-group" import { Block } from "@/registry/schema" export function BlockToolbar({ block, resizablePanelRef, }: { block: Block & { hasLiftMode: boolean } resizablePanelRef: React.RefObject<ImperativePanelHandle> }) { const { isLiftMode, toggleLiftMode } = useLiftMode(block.name) return ( <div className="flex items-center gap-4"> <div className="flex items-center gap-2"> <TabsList className="hidden h-7 rounded-md p-0 px-[calc(theme(spacing.1)_-_2px)] py-[theme(spacing.1)] sm:flex"> <TabsTrigger value="preview" className="h-[1.45rem] rounded-sm px-2 text-xs" disabled={isLiftMode} > Preview </TabsTrigger> <TabsTrigger value="code" className="h-[1.45rem] rounded-sm px-2 text-xs" disabled={isLiftMode} > Code </TabsTrigger> </TabsList> <Separator orientation="vertical" className="mx-2 hidden h-4 md:flex" /> <StyleSwitcher className="h-[calc(theme(spacing.7)_-_1px)] dark:h-7" disabled={isLiftMode} /> <Popover> <PopoverTrigger disabled={isLiftMode} className="hidden text-muted-foreground hover:text-foreground disabled:opacity-50 sm:flex" > <CircleHelp className="h-3.5 w-3.5" /> <span className="sr-only">Block description</span> </PopoverTrigger> <PopoverContent side="top" sideOffset={20} className="space-y-3 rounded-[0.5rem] text-sm" > <p className="font-medium"> What is the difference between the New York and Default style? </p> <p> A style comes with its own set of components, animations, icons and more. </p> <p> The <span className="font-medium">Default</span> style has larger inputs, uses lucide-react for icons and tailwindcss-animate for animations. </p> <p> The <span className="font-medium">New York</span> style ships with smaller buttons and inputs. It also uses shadows on cards and buttons. </p> </PopoverContent> </Popover> <div className="hidden items-center gap-2 sm:flex"> <Separator orientation="vertical" className="mx-2 mr-0 hidden h-4 md:flex" /> <div className="flex items-center gap-2"> <a href={`#${block.name}`}> <Badge variant="secondary" className={cn("bg-transparent", isLiftMode && "opacity-50")} > {block.name} </Badge> </a> </div> </div> </div> {block.code && ( <div className="ml-auto flex items-center gap-2 md:pr-[14px]"> {block.hasLiftMode && ( <> <div className="hidden h-7 items-center justify-between gap-2 md:flex"> <Label htmlFor={`lift-mode-${block.name}`} className="text-xs"> Lift Mode </Label> <Switch id={`lift-mode-${block.name}`} checked={isLiftMode} onCheckedChange={(value) => { resizablePanelRef.current?.resize(100) toggleLiftMode(block.name) if (value) { trackEvent({ name: "enable_lift_mode", properties: { name: block.name, }, }) } }} /> </div> <Separator orientation="vertical" className="mx-2 hidden h-4 lg:inline-flex" /> </> )} <div className="hidden h-[28px] items-center gap-1.5 rounded-md border p-[2px] shadow-sm md:flex"> <ToggleGroup disabled={isLiftMode} type="single" defaultValue="100" onValueChange={(value) => { if (resizablePanelRef.current) { resizablePanelRef.current.resize(parseInt(value)) } }} > <ToggleGroupItem value="100" className="h-[22px] w-[22px] rounded-sm p-0" > <Monitor className="h-3.5 w-3.5" /> </ToggleGroupItem> <ToggleGroupItem value="60" className="h-[22px] w-[22px] rounded-sm p-0" > <Tablet className="h-3.5 w-3.5" /> </ToggleGroupItem> <ToggleGroupItem value="30" className="h-[22px] w-[22px] rounded-sm p-0" > <Smartphone className="h-3.5 w-3.5" /> </ToggleGroupItem> </ToggleGroup> </div> <Separator orientation="vertical" className="mx-2 hidden h-4 md:flex" /> <BlockCopyButton event="copy_block_code" name={block.name} code={block.code} disabled={isLiftMode} /> <V0Button className="hidden md:flex" id={`v0-button-${block.name}`} disabled={ isLiftMode || ["login-01", "sidebar-01"].includes(block.name) } block={{ name: block.name, description: block.description || "Edit in v0", code: block.code, style: block.style, }} /> </div> )} </div> ) }
shadcn-ui/ui/apps/www/components/block-toolbar.tsx
{ "file_path": "shadcn-ui/ui/apps/www/components/block-toolbar.tsx", "repo_id": "shadcn-ui/ui", "token_count": 3730 }
119
"use client" import * as React from "react" import { DropdownMenuTriggerProps } from "@radix-ui/react-dropdown-menu" import { CheckIcon, ClipboardIcon } from "lucide-react" import { NpmCommands } from "types/unist" import { Event, trackEvent } from "@/lib/events" import { cn } from "@/lib/utils" import { Button, ButtonProps } from "@/registry/new-york/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/registry/new-york/ui/dropdown-menu" interface CopyButtonProps extends ButtonProps { value: string src?: string event?: Event["name"] } export async function copyToClipboardWithMeta(value: string, event?: Event) { navigator.clipboard.writeText(value) if (event) { trackEvent(event) } } export function CopyButton({ value, className, src, variant = "ghost", event, ...props }: CopyButtonProps) { const [hasCopied, setHasCopied] = React.useState(false) React.useEffect(() => { setTimeout(() => { setHasCopied(false) }, 2000) }, [hasCopied]) return ( <Button size="icon" variant={variant} className={cn( "relative z-10 h-6 w-6 text-zinc-50 hover:bg-zinc-700 hover:text-zinc-50 [&_svg]:h-3 [&_svg]:w-3", className )} onClick={() => { copyToClipboardWithMeta( value, event ? { name: event, properties: { code: value, }, } : undefined ) setHasCopied(true) }} {...props} > <span className="sr-only">Copy</span> {hasCopied ? <CheckIcon /> : <ClipboardIcon />} </Button> ) } interface CopyWithClassNamesProps extends DropdownMenuTriggerProps { value: string classNames: string className?: string } export function CopyWithClassNames({ value, classNames, className, ...props }: CopyWithClassNamesProps) { const [hasCopied, setHasCopied] = React.useState(false) React.useEffect(() => { setTimeout(() => { setHasCopied(false) }, 2000) }, [hasCopied]) const copyToClipboard = React.useCallback((value: string) => { copyToClipboardWithMeta(value) setHasCopied(true) }, []) return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button size="icon" variant="ghost" className={cn( "relative z-10 h-6 w-6 text-zinc-50 hover:bg-zinc-700 hover:text-zinc-50", className )} > {hasCopied ? ( <CheckIcon className="h-3 w-3" /> ) : ( <ClipboardIcon className="h-3 w-3" /> )} <span className="sr-only">Copy</span> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem onClick={() => copyToClipboard(value)}> Component </DropdownMenuItem> <DropdownMenuItem onClick={() => copyToClipboard(classNames)}> Classname </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) } interface CopyNpmCommandButtonProps extends DropdownMenuTriggerProps { commands: Required<NpmCommands> } export function CopyNpmCommandButton({ commands, className, ...props }: CopyNpmCommandButtonProps) { const [hasCopied, setHasCopied] = React.useState(false) React.useEffect(() => { setTimeout(() => { setHasCopied(false) }, 2000) }, [hasCopied]) const copyCommand = React.useCallback( (value: string, pm: "npm" | "pnpm" | "yarn" | "bun") => { copyToClipboardWithMeta(value, { name: "copy_npm_command", properties: { command: value, pm, }, }) setHasCopied(true) }, [] ) return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button size="icon" variant="ghost" className={cn( "relative z-10 h-6 w-6 text-zinc-50 hover:bg-zinc-700 hover:text-zinc-50", className )} > {hasCopied ? ( <CheckIcon className="h-3 w-3" /> ) : ( <ClipboardIcon className="h-3 w-3" /> )} <span className="sr-only">Copy</span> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem onClick={() => copyCommand(commands.__npmCommand__, "npm")} > npm </DropdownMenuItem> <DropdownMenuItem onClick={() => copyCommand(commands.__yarnCommand__, "yarn")} > yarn </DropdownMenuItem> <DropdownMenuItem onClick={() => copyCommand(commands.__pnpmCommand__, "pnpm")} > pnpm </DropdownMenuItem> <DropdownMenuItem onClick={() => copyCommand(commands.__bunCommand__, "bun")} > bun </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) }
shadcn-ui/ui/apps/www/components/copy-button.tsx
{ "file_path": "shadcn-ui/ui/apps/www/components/copy-button.tsx", "repo_id": "shadcn-ui/ui", "token_count": 2362 }
120
import Link from "next/link" import { siteConfig } from "@/config/site" import { cn } from "@/lib/utils" import { CommandMenu } from "@/components/command-menu" import { Icons } from "@/components/icons" import { MainNav } from "@/components/main-nav" import { MobileNav } from "@/components/mobile-nav" import { ModeToggle } from "@/components/mode-toggle" import { buttonVariants } from "@/registry/new-york/ui/button" export function SiteHeader() { return ( <header className="sticky top-0 z-50 w-full border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60"> <div className="container flex h-14 max-w-screen-2xl items-center"> <MainNav /> <MobileNav /> <div className="flex flex-1 items-center justify-between space-x-2 md:justify-end"> <div className="w-full flex-1 md:w-auto md:flex-none"> <CommandMenu /> </div> <nav className="flex items-center"> <Link href={siteConfig.links.github} target="_blank" rel="noreferrer" > <div className={cn( buttonVariants({ variant: "ghost", }), "h-8 w-8 px-0" )} > <Icons.gitHub className="h-4 w-4" /> <span className="sr-only">GitHub</span> </div> </Link> <Link href={siteConfig.links.twitter} target="_blank" rel="noreferrer" > <div className={cn( buttonVariants({ variant: "ghost", }), "h-8 w-8 px-0" )} > <Icons.twitter className="h-3 w-3 fill-current" /> <span className="sr-only">Twitter</span> </div> </Link> <ModeToggle /> </nav> </div> </div> </header> ) }
shadcn-ui/ui/apps/www/components/site-header.tsx
{ "file_path": "shadcn-ui/ui/apps/www/components/site-header.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1134 }
121
export function themeColorsToCssVariables( colors: Record<string, string> ): Record<string, string> { const cssVars = colors ? Object.fromEntries( Object.entries(colors).map(([name, value]) => { if (value === undefined) return [] const cssName = themeColorNameToCssVariable(name) return [cssName, value] }) ) : {} // for (const key of Array.from({ length: 5 }, (_, index) => index)) { // cssVars[`--chart-${key + 1}`] = // cssVars[`--chart-${key + 1}`] || // `${cssVars["--primary"]} / ${100 - key * 20}%` // } return cssVars } export function themeColorNameToCssVariable(name: string) { return `--${name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}` }
shadcn-ui/ui/apps/www/lib/charts.ts
{ "file_path": "shadcn-ui/ui/apps/www/lib/charts.ts", "repo_id": "shadcn-ui/ui", "token_count": 323 }
122
import Image from "next/image" import Link from "next/link" import { Button } from "@/registry/default/ui/button" import { Input } from "@/registry/default/ui/input" import { Label } from "@/registry/default/ui/label" export const description = "A login page with two columns. The first column has the login form with email and password. There's a Forgot your passwork link and a link to sign up if you do not have an account. The second column has a cover image." export const iframeHeight = "800px" export const containerClassName = "w-full h-full p-4 lg:p-0" export default function Dashboard() { return ( <div className="w-full lg:grid lg:min-h-[600px] lg:grid-cols-2 xl:min-h-[800px]"> <div className="flex items-center justify-center py-12"> <div className="mx-auto grid w-[350px] gap-6"> <div className="grid gap-2 text-center"> <h1 className="text-3xl font-bold">Login</h1> <p className="text-balance text-muted-foreground"> Enter your email below to login to your account </p> </div> <div className="grid gap-4"> <div className="grid gap-2"> <Label htmlFor="email">Email</Label> <Input id="email" type="email" placeholder="[email protected]" required /> </div> <div className="grid gap-2"> <div className="flex items-center"> <Label htmlFor="password">Password</Label> <Link href="/forgot-password" className="ml-auto inline-block text-sm underline" > Forgot your password? </Link> </div> <Input id="password" type="password" required /> </div> <Button type="submit" className="w-full"> Login </Button> <Button variant="outline" className="w-full"> Login with Google </Button> </div> <div className="mt-4 text-center text-sm"> Don&apos;t have an account?{" "} <Link href="#" className="underline"> Sign up </Link> </div> </div> </div> <div className="hidden bg-muted lg:block"> <Image src="/placeholder.svg" alt="Image" width="1920" height="1080" className="h-full w-full object-cover dark:brightness-[0.2] dark:grayscale" /> </div> </div> ) }
shadcn-ui/ui/apps/www/registry/default/block/authentication-04.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/block/authentication-04.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1289 }
123
"use client" import { TrendingUp } from "lucide-react" import { Bar, BarChart, CartesianGrid, LabelList, XAxis } from "recharts" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/registry/default/ui/card" import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent, } from "@/registry/default/ui/chart" export const description = "A bar chart with a label" const chartData = [ { month: "January", desktop: 186 }, { month: "February", desktop: 305 }, { month: "March", desktop: 237 }, { month: "April", desktop: 73 }, { month: "May", desktop: 209 }, { month: "June", desktop: 214 }, ] const chartConfig = { desktop: { label: "Desktop", color: "hsl(var(--chart-1))", }, } satisfies ChartConfig export default function Component() { return ( <Card> <CardHeader> <CardTitle>Bar Chart - Label</CardTitle> <CardDescription>January - June 2024</CardDescription> </CardHeader> <CardContent> <ChartContainer config={chartConfig}> <BarChart accessibilityLayer data={chartData} margin={{ top: 20, }} > <CartesianGrid vertical={false} /> <XAxis dataKey="month" tickLine={false} tickMargin={10} axisLine={false} tickFormatter={(value) => value.slice(0, 3)} /> <ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} /> <Bar dataKey="desktop" fill="var(--color-desktop)" radius={8}> <LabelList position="top" offset={12} className="fill-foreground" fontSize={12} /> </Bar> </BarChart> </ChartContainer> </CardContent> <CardFooter className="flex-col items-start gap-2 text-sm"> <div className="flex gap-2 font-medium leading-none"> Trending up by 5.2% this month <TrendingUp className="h-4 w-4" /> </div> <div className="leading-none text-muted-foreground"> Showing total visitors for the last 6 months </div> </CardFooter> </Card> ) }
shadcn-ui/ui/apps/www/registry/default/block/chart-bar-label.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/block/chart-bar-label.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1086 }
124
"use client" import * as React from "react" import { TrendingUp } from "lucide-react" import { Label, Pie, PieChart } from "recharts" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/registry/default/ui/card" import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent, } from "@/registry/default/ui/chart" export const description = "A donut chart with text" const chartData = [ { browser: "chrome", visitors: 275, fill: "var(--color-chrome)" }, { browser: "safari", visitors: 200, fill: "var(--color-safari)" }, { browser: "firefox", visitors: 287, fill: "var(--color-firefox)" }, { browser: "edge", visitors: 173, fill: "var(--color-edge)" }, { browser: "other", visitors: 190, fill: "var(--color-other)" }, ] const chartConfig = { visitors: { label: "Visitors", }, chrome: { label: "Chrome", color: "hsl(var(--chart-1))", }, safari: { label: "Safari", color: "hsl(var(--chart-2))", }, firefox: { label: "Firefox", color: "hsl(var(--chart-3))", }, edge: { label: "Edge", color: "hsl(var(--chart-4))", }, other: { label: "Other", color: "hsl(var(--chart-5))", }, } satisfies ChartConfig export default function Component() { const totalVisitors = React.useMemo(() => { return chartData.reduce((acc, curr) => acc + curr.visitors, 0) }, []) return ( <Card className="flex flex-col"> <CardHeader className="items-center pb-0"> <CardTitle>Pie Chart - Donut with Text</CardTitle> <CardDescription>January - June 2024</CardDescription> </CardHeader> <CardContent className="flex-1 pb-0"> <ChartContainer config={chartConfig} className="mx-auto aspect-square max-h-[250px]" > <PieChart> <ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} /> <Pie data={chartData} dataKey="visitors" nameKey="browser" innerRadius={60} strokeWidth={5} > <Label content={({ viewBox }) => { if (viewBox && "cx" in viewBox && "cy" in viewBox) { return ( <text x={viewBox.cx} y={viewBox.cy} textAnchor="middle" dominantBaseline="middle" > <tspan x={viewBox.cx} y={viewBox.cy} className="fill-foreground text-3xl font-bold" > {totalVisitors.toLocaleString()} </tspan> <tspan x={viewBox.cx} y={(viewBox.cy || 0) + 24} className="fill-muted-foreground" > Visitors </tspan> </text> ) } }} /> </Pie> </PieChart> </ChartContainer> </CardContent> <CardFooter className="flex-col gap-2 text-sm"> <div className="flex items-center gap-2 font-medium leading-none"> Trending up by 5.2% this month <TrendingUp className="h-4 w-4" /> </div> <div className="leading-none text-muted-foreground"> Showing total visitors for the last 6 months </div> </CardFooter> </Card> ) }
shadcn-ui/ui/apps/www/registry/default/block/chart-pie-donut-text.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/block/chart-pie-donut-text.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1961 }
125
"use client" import { Bar, BarChart, XAxis } from "recharts" import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/registry/default/ui/card" import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent, } from "@/registry/default/ui/chart" export const description = "A stacked bar chart with a legend" const chartData = [ { date: "2024-07-15", running: 450, swimming: 300 }, { date: "2024-07-16", running: 380, swimming: 420 }, { date: "2024-07-17", running: 520, swimming: 120 }, { date: "2024-07-18", running: 140, swimming: 550 }, { date: "2024-07-19", running: 600, swimming: 350 }, { date: "2024-07-20", running: 480, swimming: 400 }, ] const chartConfig = { running: { label: "Running", color: "hsl(var(--chart-1))", }, swimming: { label: "Swimming", color: "hsl(var(--chart-2))", }, } satisfies ChartConfig export default function Component() { return ( <Card> <CardHeader> <CardTitle>Tooltip - Formatter</CardTitle> <CardDescription>Tooltip with custom formatter .</CardDescription> </CardHeader> <CardContent> <ChartContainer config={chartConfig}> <BarChart accessibilityLayer data={chartData}> <XAxis dataKey="date" tickLine={false} tickMargin={10} axisLine={false} tickFormatter={(value) => { return new Date(value).toLocaleDateString("en-US", { weekday: "short", }) }} /> <Bar dataKey="running" stackId="a" fill="var(--color-running)" radius={[0, 0, 4, 4]} /> <Bar dataKey="swimming" stackId="a" fill="var(--color-swimming)" radius={[4, 4, 0, 0]} /> <ChartTooltip content={ <ChartTooltipContent hideLabel formatter={(value, name) => ( <div className="flex min-w-[130px] items-center text-xs text-muted-foreground"> {chartConfig[name as keyof typeof chartConfig]?.label || name} <div className="ml-auto flex items-baseline gap-0.5 font-mono font-medium tabular-nums text-foreground"> {value} <span className="font-normal text-muted-foreground"> kcal </span> </div> </div> )} /> } cursor={false} defaultIndex={1} /> </BarChart> </ChartContainer> </CardContent> </Card> ) }
shadcn-ui/ui/apps/www/registry/default/block/chart-tooltip-formatter.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/block/chart-tooltip-formatter.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1504 }
126
import Link from "next/link" import { CircleUser, Menu, Package2, Search } from "lucide-react" import { Button } from "@/registry/default/ui/button" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/registry/default/ui/card" import { Checkbox } from "@/registry/default/ui/checkbox" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/registry/default/ui/dropdown-menu" import { Input } from "@/registry/default/ui/input" import { Sheet, SheetContent, SheetTrigger } from "@/registry/default/ui/sheet" export const description = "A settings page. The settings page has a sidebar navigation and a main content area. The main content area has a form to update the store name and a form to update the plugins directory. The sidebar navigation has links to general, security, integrations, support, organizations, and advanced settings." export const iframeHeight = "780px" export const containerClassName = "w-full h-full" export default function Dashboard() { return ( <div className="flex min-h-screen w-full flex-col"> <header className="sticky top-0 flex h-16 items-center gap-4 border-b bg-background px-4 md:px-6"> <nav className="hidden flex-col gap-6 text-lg font-medium md:flex md:flex-row md:items-center md:gap-5 md:text-sm lg:gap-6"> <Link href="#" className="flex items-center gap-2 text-lg font-semibold md:text-base" > <Package2 className="h-6 w-6" /> <span className="sr-only">Acme Inc</span> </Link> <Link href="#" className="text-muted-foreground transition-colors hover:text-foreground" > Dashboard </Link> <Link href="#" className="text-muted-foreground transition-colors hover:text-foreground" > Orders </Link> <Link href="#" className="text-muted-foreground transition-colors hover:text-foreground" > Products </Link> <Link href="#" className="text-muted-foreground transition-colors hover:text-foreground" > Customers </Link> <Link href="#" className="text-foreground transition-colors hover:text-foreground" > Settings </Link> </nav> <Sheet> <SheetTrigger asChild> <Button variant="outline" size="icon" className="shrink-0 md:hidden" > <Menu className="h-5 w-5" /> <span className="sr-only">Toggle navigation menu</span> </Button> </SheetTrigger> <SheetContent side="left"> <nav className="grid gap-6 text-lg font-medium"> <Link href="#" className="flex items-center gap-2 text-lg font-semibold" > <Package2 className="h-6 w-6" /> <span className="sr-only">Acme Inc</span> </Link> <Link href="#" className="text-muted-foreground hover:text-foreground" > Dashboard </Link> <Link href="#" className="text-muted-foreground hover:text-foreground" > Orders </Link> <Link href="#" className="text-muted-foreground hover:text-foreground" > Products </Link> <Link href="#" className="text-muted-foreground hover:text-foreground" > Customers </Link> <Link href="#" className="hover:text-foreground"> Settings </Link> </nav> </SheetContent> </Sheet> <div className="flex w-full items-center gap-4 md:ml-auto md:gap-2 lg:gap-4"> <form className="ml-auto flex-1 sm:flex-initial"> <div className="relative"> <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" /> <Input type="search" placeholder="Search products..." className="pl-8 sm:w-[300px] md:w-[200px] lg:w-[300px]" /> </div> </form> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="secondary" size="icon" className="rounded-full"> <CircleUser className="h-5 w-5" /> <span className="sr-only">Toggle user menu</span> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuLabel>My Account</DropdownMenuLabel> <DropdownMenuSeparator /> <DropdownMenuItem>Settings</DropdownMenuItem> <DropdownMenuItem>Support</DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem>Logout</DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </div> </header> <main className="flex min-h-[calc(100vh_-_theme(spacing.16))] flex-1 flex-col gap-4 bg-muted/40 p-4 md:gap-8 md:p-10"> <div className="mx-auto grid w-full max-w-6xl gap-2"> <h1 className="text-3xl font-semibold">Settings</h1> </div> <div className="mx-auto grid w-full max-w-6xl items-start gap-6 md:grid-cols-[180px_1fr] lg:grid-cols-[250px_1fr]"> <nav className="grid gap-4 text-sm text-muted-foreground" x-chunk="A sidebar navigation with links to general, security, integrations, support, organizations, and advanced settings." x-chunk-container="chunk-container after:right-0" > <Link href="#" className="font-semibold text-primary"> General </Link> <Link href="#">Security</Link> <Link href="#">Integrations</Link> <Link href="#">Support</Link> <Link href="#">Organizations</Link> <Link href="#">Advanced</Link> </nav> <div className="grid gap-6"> <Card x-chunk="A form to update the store name."> <CardHeader> <CardTitle>Store Name</CardTitle> <CardDescription> Used to identify your store in the marketplace. </CardDescription> </CardHeader> <CardContent> <form> <Input placeholder="Store Name" /> </form> </CardContent> <CardFooter className="border-t px-6 py-4"> <Button>Save</Button> </CardFooter> </Card> <Card x-chunk="A form to update the plugins directory with a checkbox to allow administrators to change the directory."> <CardHeader> <CardTitle>Plugins Directory</CardTitle> <CardDescription> The directory within your project, in which your plugins are located. </CardDescription> </CardHeader> <CardContent> <form className="flex flex-col gap-4"> <Input placeholder="Project Name" defaultValue="/content/plugins" /> <div className="flex items-center space-x-2"> <Checkbox id="include" defaultChecked /> <label htmlFor="include" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Allow administrators to change the directory. </label> </div> </form> </CardContent> <CardFooter className="border-t px-6 py-4"> <Button>Save</Button> </CardFooter> </Card> </div> </div> </main> </div> ) }
shadcn-ui/ui/apps/www/registry/default/block/dashboard-04.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/block/dashboard-04.tsx", "repo_id": "shadcn-ui/ui", "token_count": 4361 }
127
import Image from "next/image" import { AspectRatio } from "@/registry/default/ui/aspect-ratio" export default function AspectRatioDemo() { return ( <AspectRatio ratio={16 / 9} className="bg-muted"> <Image src="https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80" alt="Photo by Drew Beamer" fill className="h-full w-full rounded-md object-cover" /> </AspectRatio> ) }
shadcn-ui/ui/apps/www/registry/default/example/aspect-ratio-demo.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/aspect-ratio-demo.tsx", "repo_id": "shadcn-ui/ui", "token_count": 205 }
128
import { ChevronRight } from "lucide-react" import { Button } from "@/registry/default/ui/button" export default function ButtonIcon() { return ( <Button variant="outline" size="icon"> <ChevronRight className="h-4 w-4" /> </Button> ) }
shadcn-ui/ui/apps/www/registry/default/example/button-icon.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/button-icon.tsx", "repo_id": "shadcn-ui/ui", "token_count": 94 }
129
"use client" import * as React from "react" import { CaretSortIcon, ChevronDownIcon, DotsHorizontalIcon, } from "@radix-ui/react-icons" import { ColumnDef, ColumnFiltersState, SortingState, VisibilityState, flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, useReactTable, } from "@tanstack/react-table" import { Button } from "@/registry/default/ui/button" import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/registry/default/ui/card" import { Checkbox } from "@/registry/default/ui/checkbox" import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/registry/default/ui/dropdown-menu" import { Input } from "@/registry/default/ui/input" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/registry/default/ui/table" const data: Payment[] = [ { id: "m5gr84i9", amount: 316, status: "success", email: "[email protected]", }, { id: "3u1reuv4", amount: 242, status: "success", email: "[email protected]", }, { id: "derv1ws0", amount: 837, status: "processing", email: "[email protected]", }, { id: "5kma53ae", amount: 874, status: "success", email: "[email protected]", }, { id: "bhqecj4p", amount: 721, status: "failed", email: "[email protected]", }, ] export type Payment = { id: string amount: number status: "pending" | "processing" | "success" | "failed" email: string } export const columns: ColumnDef<Payment>[] = [ { id: "select", header: ({ table }) => ( <Checkbox checked={ table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate") } onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} aria-label="Select all" /> ), cell: ({ row }) => ( <Checkbox checked={row.getIsSelected()} onCheckedChange={(value) => row.toggleSelected(!!value)} aria-label="Select row" /> ), enableSorting: false, enableHiding: false, }, { accessorKey: "status", header: "Status", cell: ({ row }) => ( <div className="capitalize">{row.getValue("status")}</div> ), }, { accessorKey: "email", header: ({ column }) => { return ( <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Email <CaretSortIcon className="ml-2 h-4 w-4" /> </Button> ) }, cell: ({ row }) => <div className="lowercase">{row.getValue("email")}</div>, }, { accessorKey: "amount", header: () => <div className="text-right">Amount</div>, cell: ({ row }) => { const amount = parseFloat(row.getValue("amount")) // Format the amount as a dollar amount const formatted = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }).format(amount) return <div className="text-right font-medium">{formatted}</div> }, }, { id: "actions", enableHiding: false, cell: ({ row }) => { const payment = row.original return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" className="h-8 w-8 p-0"> <span className="sr-only">Open menu</span> <DotsHorizontalIcon className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuItem onClick={() => navigator.clipboard.writeText(payment.id)} > Copy payment ID </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem>View customer</DropdownMenuItem> <DropdownMenuItem>View payment details</DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) }, }, ] export function CardsDataTable() { const [sorting, setSorting] = React.useState<SortingState>([]) const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>( [] ) const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({}) const [rowSelection, setRowSelection] = React.useState({}) const table = useReactTable({ data, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, getCoreRowModel: getCoreRowModel(), getPaginationRowModel: getPaginationRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, state: { sorting, columnFilters, columnVisibility, rowSelection, }, }) return ( <Card> <CardHeader> <CardTitle>Payments</CardTitle> <CardDescription>Manage your payments.</CardDescription> </CardHeader> <CardContent> <div className="mb-4 flex items-center gap-4"> <Input placeholder="Filter emails..." value={(table.getColumn("email")?.getFilterValue() as string) ?? ""} onChange={(event) => table.getColumn("email")?.setFilterValue(event.target.value) } className="max-w-sm" /> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline" className="ml-auto"> Columns <ChevronDownIcon className="ml-2 h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> {table .getAllColumns() .filter((column) => column.getCanHide()) .map((column) => { return ( <DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value) } > {column.id} </DropdownMenuCheckboxItem> ) })} </DropdownMenuContent> </DropdownMenu> </div> <div className="rounded-md border"> <Table> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id} className="[&:has([role=checkbox])]:pl-3" > {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} </TableHead> ) })} </TableRow> ))} </TableHeader> <TableBody> {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( <TableRow key={row.id} data-state={row.getIsSelected() && "selected"} > {row.getVisibleCells().map((cell) => ( <TableCell key={cell.id} className="[&:has([role=checkbox])]:pl-3" > {flexRender( cell.column.columnDef.cell, cell.getContext() )} </TableCell> ))} </TableRow> )) ) : ( <TableRow> <TableCell colSpan={columns.length} className="h-24 text-center" > No results. </TableCell> </TableRow> )} </TableBody> </Table> </div> <div className="flex items-center justify-end space-x-2 pt-4"> <div className="flex-1 text-sm text-muted-foreground"> {table.getFilteredSelectedRowModel().rows.length} of{" "} {table.getFilteredRowModel().rows.length} row(s) selected. </div> <div className="space-x-2"> <Button variant="outline" size="sm" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} > Previous </Button> <Button variant="outline" size="sm" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} > Next </Button> </div> </div> </CardContent> </Card> ) }
shadcn-ui/ui/apps/www/registry/default/example/cards/data-table.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/cards/data-table.tsx", "repo_id": "shadcn-ui/ui", "token_count": 4921 }
130
"use client" import { Bar, BarChart, CartesianGrid, XAxis } from "recharts" import { ChartConfig, ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent, } from "@/registry/default/ui/chart" const chartData = [ { month: "January", desktop: 186, mobile: 80 }, { month: "February", desktop: 305, mobile: 200 }, { month: "March", desktop: 237, mobile: 120 }, { month: "April", desktop: 73, mobile: 190 }, { month: "May", desktop: 209, mobile: 130 }, { month: "June", desktop: 214, mobile: 140 }, ] const chartConfig = { desktop: { label: "Desktop", color: "#2563eb", }, mobile: { label: "Mobile", color: "#60a5fa", }, } satisfies ChartConfig export default function Component() { return ( <ChartContainer config={chartConfig} className="min-h-[200px] w-full"> <BarChart accessibilityLayer data={chartData}> <CartesianGrid vertical={false} /> <XAxis dataKey="month" tickLine={false} tickMargin={10} axisLine={false} tickFormatter={(value) => value.slice(0, 3)} /> <ChartTooltip content={<ChartTooltipContent />} /> <ChartLegend content={<ChartLegendContent />} /> <Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} /> <Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} /> </BarChart> </ChartContainer> ) }
shadcn-ui/ui/apps/www/registry/default/example/chart-bar-demo-legend.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/chart-bar-demo-legend.tsx", "repo_id": "shadcn-ui/ui", "token_count": 557 }
131
"use client" import * as React from "react" import { Calculator, Calendar, CreditCard, Settings, Smile, User, } from "lucide-react" import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, } from "@/registry/default/ui/command" export default function CommandDialogDemo() { const [open, setOpen] = React.useState(false) React.useEffect(() => { const down = (e: KeyboardEvent) => { if (e.key === "j" && (e.metaKey || e.ctrlKey)) { e.preventDefault() setOpen((open) => !open) } } document.addEventListener("keydown", down) return () => document.removeEventListener("keydown", down) }, []) return ( <> <p className="text-sm text-muted-foreground"> Press{" "} <kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100"> <span className="text-xs"></span>J </kbd> </p> <CommandDialog open={open} onOpenChange={setOpen}> <CommandInput placeholder="Type a command or search..." /> <CommandList> <CommandEmpty>No results found.</CommandEmpty> <CommandGroup heading="Suggestions"> <CommandItem> <Calendar className="mr-2 h-4 w-4" /> <span>Calendar</span> </CommandItem> <CommandItem> <Smile className="mr-2 h-4 w-4" /> <span>Search Emoji</span> </CommandItem> <CommandItem> <Calculator className="mr-2 h-4 w-4" /> <span>Calculator</span> </CommandItem> </CommandGroup> <CommandSeparator /> <CommandGroup heading="Settings"> <CommandItem> <User className="mr-2 h-4 w-4" /> <span>Profile</span> <CommandShortcut>P</CommandShortcut> </CommandItem> <CommandItem> <CreditCard className="mr-2 h-4 w-4" /> <span>Billing</span> <CommandShortcut>B</CommandShortcut> </CommandItem> <CommandItem> <Settings className="mr-2 h-4 w-4" /> <span>Settings</span> <CommandShortcut>S</CommandShortcut> </CommandItem> </CommandGroup> </CommandList> </CommandDialog> </> ) }
shadcn-ui/ui/apps/www/registry/default/example/command-dialog.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/command-dialog.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1203 }
132
import { Input } from "@/registry/default/ui/input" export default function InputDisabled() { return <Input disabled type="email" placeholder="Email" /> }
shadcn-ui/ui/apps/www/registry/default/example/input-disabled.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/input-disabled.tsx", "repo_id": "shadcn-ui/ui", "token_count": 44 }
133
import { Button } from "@/registry/default/ui/button" import { Input } from "@/registry/default/ui/input" import { Label } from "@/registry/default/ui/label" import { Popover, PopoverContent, PopoverTrigger, } from "@/registry/default/ui/popover" export default function PopoverDemo() { return ( <Popover> <PopoverTrigger asChild> <Button variant="outline">Open popover</Button> </PopoverTrigger> <PopoverContent className="w-80"> <div className="grid gap-4"> <div className="space-y-2"> <h4 className="font-medium leading-none">Dimensions</h4> <p className="text-sm text-muted-foreground"> Set the dimensions for the layer. </p> </div> <div className="grid gap-2"> <div className="grid grid-cols-3 items-center gap-4"> <Label htmlFor="width">Width</Label> <Input id="width" defaultValue="100%" className="col-span-2 h-8" /> </div> <div className="grid grid-cols-3 items-center gap-4"> <Label htmlFor="maxWidth">Max. width</Label> <Input id="maxWidth" defaultValue="300px" className="col-span-2 h-8" /> </div> <div className="grid grid-cols-3 items-center gap-4"> <Label htmlFor="height">Height</Label> <Input id="height" defaultValue="25px" className="col-span-2 h-8" /> </div> <div className="grid grid-cols-3 items-center gap-4"> <Label htmlFor="maxHeight">Max. height</Label> <Input id="maxHeight" defaultValue="none" className="col-span-2 h-8" /> </div> </div> </div> </PopoverContent> </Popover> ) }
shadcn-ui/ui/apps/www/registry/default/example/popover-demo.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/popover-demo.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1080 }
134
import { Skeleton } from "@/registry/default/ui/skeleton" export default function SkeletonCard() { return ( <div className="flex flex-col space-y-3"> <Skeleton className="h-[125px] w-[250px] rounded-xl" /> <div className="space-y-2"> <Skeleton className="h-4 w-[250px]" /> <Skeleton className="h-4 w-[200px]" /> </div> </div> ) }
shadcn-ui/ui/apps/www/registry/default/example/skeleton-card.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/skeleton-card.tsx", "repo_id": "shadcn-ui/ui", "token_count": 164 }
135
"use client" import { useToast } from "@/registry/default/hooks/use-toast" import { Button } from "@/registry/default/ui/button" export default function ToastSimple() { const { toast } = useToast() return ( <Button variant="outline" onClick={() => { toast({ description: "Your message has been sent.", }) }} > Show Toast </Button> ) }
shadcn-ui/ui/apps/www/registry/default/example/toast-simple.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/toast-simple.tsx", "repo_id": "shadcn-ui/ui", "token_count": 169 }
136
export default function TypographyBlockquote() { return ( <blockquote className="mt-6 border-l-2 pl-6 italic"> "After all," he said, "everyone enjoys a good joke, so it's only fair that they should pay for the privilege." </blockquote> ) }
shadcn-ui/ui/apps/www/registry/default/example/typography-blockquote.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/example/typography-blockquote.tsx", "repo_id": "shadcn-ui/ui", "token_count": 90 }
137
import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }
shadcn-ui/ui/apps/www/registry/default/lib/utils.ts
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/lib/utils.ts", "repo_id": "shadcn-ui/ui", "token_count": 64 }
138
"use client" import * as React from "react" import * as ContextMenuPrimitive from "@radix-ui/react-context-menu" import { Check, ChevronRight, Circle } from "lucide-react" import { cn } from "@/lib/utils" const ContextMenu = ContextMenuPrimitive.Root const ContextMenuTrigger = ContextMenuPrimitive.Trigger const ContextMenuGroup = ContextMenuPrimitive.Group const ContextMenuPortal = ContextMenuPrimitive.Portal const ContextMenuSub = ContextMenuPrimitive.Sub const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup const ContextMenuSubTrigger = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & { inset?: boolean } >(({ className, inset, children, ...props }, ref) => ( <ContextMenuPrimitive.SubTrigger ref={ref} className={cn( "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground", inset && "pl-8", className )} {...props} > {children} <ChevronRight className="ml-auto h-4 w-4" /> </ContextMenuPrimitive.SubTrigger> )) ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName const ContextMenuSubContent = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.SubContent>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent> >(({ className, ...props }, ref) => ( <ContextMenuPrimitive.SubContent ref={ref} className={cn( "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> )) ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName const ContextMenuContent = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.Content>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content> >(({ className, ...props }, ref) => ( <ContextMenuPrimitive.Portal> <ContextMenuPrimitive.Content ref={ref} className={cn( "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className )} {...props} /> </ContextMenuPrimitive.Portal> )) ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName const ContextMenuItem = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.Item>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( <ContextMenuPrimitive.Item ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className )} {...props} /> )) ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName const ContextMenuCheckboxItem = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem> >(({ className, children, checked, ...props }, ref) => ( <ContextMenuPrimitive.CheckboxItem ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} checked={checked} {...props} > <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <ContextMenuPrimitive.ItemIndicator> <Check className="h-4 w-4" /> </ContextMenuPrimitive.ItemIndicator> </span> {children} </ContextMenuPrimitive.CheckboxItem> )) ContextMenuCheckboxItem.displayName = ContextMenuPrimitive.CheckboxItem.displayName const ContextMenuRadioItem = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.RadioItem>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem> >(({ className, children, ...props }, ref) => ( <ContextMenuPrimitive.RadioItem ref={ref} className={cn( "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} {...props} > <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <ContextMenuPrimitive.ItemIndicator> <Circle className="h-2 w-2 fill-current" /> </ContextMenuPrimitive.ItemIndicator> </span> {children} </ContextMenuPrimitive.RadioItem> )) ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName const ContextMenuLabel = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.Label>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( <ContextMenuPrimitive.Label ref={ref} className={cn( "px-2 py-1.5 text-sm font-semibold text-foreground", inset && "pl-8", className )} {...props} /> )) ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName const ContextMenuSeparator = React.forwardRef< React.ElementRef<typeof ContextMenuPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator> >(({ className, ...props }, ref) => ( <ContextMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-border", className)} {...props} /> )) ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName const ContextMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => { return ( <span className={cn( "ml-auto text-xs tracking-widest text-muted-foreground", className )} {...props} /> ) } ContextMenuShortcut.displayName = "ContextMenuShortcut" export { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioItem, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut, ContextMenuGroup, ContextMenuPortal, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, }
shadcn-ui/ui/apps/www/registry/default/ui/context-menu.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/default/ui/context-menu.tsx", "repo_id": "shadcn-ui/ui", "token_count": 2568 }
139
import { blocks } from "@/registry/registry-blocks" import { charts } from "@/registry/registry-charts" import { examples } from "@/registry/registry-examples" import { hooks } from "@/registry/registry-hooks" import { lib } from "@/registry/registry-lib" import { themes } from "@/registry/registry-themes" import { ui } from "@/registry/registry-ui" import { Registry } from "@/registry/schema" export const registry: Registry = [ ...ui, ...examples, ...blocks, ...charts, ...lib, ...hooks, ...themes, ]
shadcn-ui/ui/apps/www/registry/index.ts
{ "file_path": "shadcn-ui/ui/apps/www/registry/index.ts", "repo_id": "shadcn-ui/ui", "token_count": 181 }
140
"use client" import { TrendingUp } from "lucide-react" import { Label, PolarRadiusAxis, RadialBar, RadialBarChart } from "recharts" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/registry/new-york/ui/card" import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent, } from "@/registry/new-york/ui/chart" export const description = "A radial chart with stacked sections" const chartData = [{ month: "january", desktop: 1260, mobile: 570 }] const chartConfig = { desktop: { label: "Desktop", color: "hsl(var(--chart-1))", }, mobile: { label: "Mobile", color: "hsl(var(--chart-2))", }, } satisfies ChartConfig export default function Component() { const totalVisitors = chartData[0].desktop + chartData[0].mobile return ( <Card className="flex flex-col"> <CardHeader className="items-center pb-0"> <CardTitle>Radial Chart - Stacked</CardTitle> <CardDescription>January - June 2024</CardDescription> </CardHeader> <CardContent className="flex flex-1 items-center pb-0"> <ChartContainer config={chartConfig} className="mx-auto aspect-square w-full max-w-[250px]" > <RadialBarChart data={chartData} endAngle={180} innerRadius={80} outerRadius={130} > <ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} /> <PolarRadiusAxis tick={false} tickLine={false} axisLine={false}> <Label content={({ viewBox }) => { if (viewBox && "cx" in viewBox && "cy" in viewBox) { return ( <text x={viewBox.cx} y={viewBox.cy} textAnchor="middle"> <tspan x={viewBox.cx} y={(viewBox.cy || 0) - 16} className="fill-foreground text-2xl font-bold" > {totalVisitors.toLocaleString()} </tspan> <tspan x={viewBox.cx} y={(viewBox.cy || 0) + 4} className="fill-muted-foreground" > Visitors </tspan> </text> ) } }} /> </PolarRadiusAxis> <RadialBar dataKey="desktop" stackId="a" cornerRadius={5} fill="var(--color-desktop)" className="stroke-transparent stroke-2" /> <RadialBar dataKey="mobile" fill="var(--color-mobile)" stackId="a" cornerRadius={5} className="stroke-transparent stroke-2" /> </RadialBarChart> </ChartContainer> </CardContent> <CardFooter className="flex-col gap-2 text-sm"> <div className="flex items-center gap-2 font-medium leading-none"> Trending up by 5.2% this month <TrendingUp className="h-4 w-4" /> </div> <div className="leading-none text-muted-foreground"> Showing total visitors for the last 6 months </div> </CardFooter> </Card> ) }
shadcn-ui/ui/apps/www/registry/new-york/block/chart-radial-stacked.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/block/chart-radial-stacked.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1864 }
141
"use client" import { PolarAngleAxis, RadialBar, RadialBarChart } from "recharts" import { Card, CardContent } from "@/registry/new-york//ui/card" import { ChartContainer } from "@/registry/new-york//ui/chart" export default function Component() { return ( <Card className="max-w-xs" x-chunk="charts-01-chunk-5"> <CardContent className="flex gap-4 p-4"> <div className="grid items-center gap-2"> <div className="grid flex-1 auto-rows-min gap-0.5"> <div className="text-sm text-muted-foreground">Move</div> <div className="flex items-baseline gap-1 text-xl font-bold tabular-nums leading-none"> 562/600 <span className="text-sm font-normal text-muted-foreground"> kcal </span> </div> </div> <div className="grid flex-1 auto-rows-min gap-0.5"> <div className="text-sm text-muted-foreground">Exercise</div> <div className="flex items-baseline gap-1 text-xl font-bold tabular-nums leading-none"> 73/120 <span className="text-sm font-normal text-muted-foreground"> min </span> </div> </div> <div className="grid flex-1 auto-rows-min gap-0.5"> <div className="text-sm text-muted-foreground">Stand</div> <div className="flex items-baseline gap-1 text-xl font-bold tabular-nums leading-none"> 8/12 <span className="text-sm font-normal text-muted-foreground"> hr </span> </div> </div> </div> <ChartContainer config={{ move: { label: "Move", color: "hsl(var(--chart-1))", }, exercise: { label: "Exercise", color: "hsl(var(--chart-2))", }, stand: { label: "Stand", color: "hsl(var(--chart-3))", }, }} className="mx-auto aspect-square w-full max-w-[80%]" > <RadialBarChart margin={{ left: -10, right: -10, top: -10, bottom: -10, }} data={[ { activity: "stand", value: (8 / 12) * 100, fill: "var(--color-stand)", }, { activity: "exercise", value: (46 / 60) * 100, fill: "var(--color-exercise)", }, { activity: "move", value: (245 / 360) * 100, fill: "var(--color-move)", }, ]} innerRadius="20%" barSize={24} startAngle={90} endAngle={450} > <PolarAngleAxis type="number" domain={[0, 100]} dataKey="value" tick={false} /> <RadialBar dataKey="value" background cornerRadius={5} /> </RadialBarChart> </ChartContainer> </CardContent> </Card> ) }
shadcn-ui/ui/apps/www/registry/new-york/block/charts-01-chunk-5.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/block/charts-01-chunk-5.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1843 }
142
import { Bird, Book, Bot, Code2, CornerDownLeft, LifeBuoy, Mic, Paperclip, Rabbit, Settings, Settings2, Share, SquareTerminal, SquareUser, Triangle, Turtle, } from "lucide-react" import { Badge } from "@/registry/new-york/ui/badge" import { Button } from "@/registry/new-york/ui/button" import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger, } from "@/registry/new-york/ui/drawer" import { Input } from "@/registry/new-york/ui/input" import { Label } from "@/registry/new-york/ui/label" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/registry/new-york/ui/select" import { Textarea } from "@/registry/new-york/ui/textarea" import { Tooltip, TooltipContent, TooltipTrigger, } from "@/registry/new-york/ui/tooltip" export const description = "An AI playground with a sidebar navigation and a main content area. The playground has a header with a settings drawer and a share button. The sidebar has navigation links and a user menu. The main content area shows a form to configure the model and messages." export const iframeHeight = "720px" export const containerClassName = "w-full h-full" export default function Dashboard() { return ( <div className="grid h-screen w-full pl-[53px]"> <aside className="inset-y fixed left-0 z-20 flex h-full flex-col border-r"> <div className="border-b p-2"> <Button variant="outline" size="icon" aria-label="Home"> <Triangle className="size-5 fill-foreground" /> </Button> </div> <nav className="grid gap-1 p-2"> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon" className="rounded-lg bg-muted" aria-label="Playground" > <SquareTerminal className="size-5" /> </Button> </TooltipTrigger> <TooltipContent side="right" sideOffset={5}> Playground </TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon" className="rounded-lg" aria-label="Models" > <Bot className="size-5" /> </Button> </TooltipTrigger> <TooltipContent side="right" sideOffset={5}> Models </TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon" className="rounded-lg" aria-label="API" > <Code2 className="size-5" /> </Button> </TooltipTrigger> <TooltipContent side="right" sideOffset={5}> API </TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon" className="rounded-lg" aria-label="Documentation" > <Book className="size-5" /> </Button> </TooltipTrigger> <TooltipContent side="right" sideOffset={5}> Documentation </TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon" className="rounded-lg" aria-label="Settings" > <Settings2 className="size-5" /> </Button> </TooltipTrigger> <TooltipContent side="right" sideOffset={5}> Settings </TooltipContent> </Tooltip> </nav> <nav className="mt-auto grid gap-1 p-2"> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon" className="mt-auto rounded-lg" aria-label="Help" > <LifeBuoy className="size-5" /> </Button> </TooltipTrigger> <TooltipContent side="right" sideOffset={5}> Help </TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon" className="mt-auto rounded-lg" aria-label="Account" > <SquareUser className="size-5" /> </Button> </TooltipTrigger> <TooltipContent side="right" sideOffset={5}> Account </TooltipContent> </Tooltip> </nav> </aside> <div className="flex flex-col"> <header className="sticky top-0 z-10 flex h-[53px] items-center gap-1 border-b bg-background px-4"> <h1 className="text-xl font-semibold">Playground</h1> <Drawer> <DrawerTrigger asChild> <Button variant="ghost" size="icon" className="md:hidden"> <Settings className="size-4" /> <span className="sr-only">Settings</span> </Button> </DrawerTrigger> <DrawerContent className="max-h-[80vh]"> <DrawerHeader> <DrawerTitle>Configuration</DrawerTitle> <DrawerDescription> Configure the settings for the model and messages. </DrawerDescription> </DrawerHeader> <form className="grid w-full items-start gap-6 overflow-auto p-4 pt-0"> <fieldset className="grid gap-6 rounded-lg border p-4"> <legend className="-ml-1 px-1 text-sm font-medium"> Settings </legend> <div className="grid gap-3"> <Label htmlFor="model">Model</Label> <Select> <SelectTrigger id="model" className="items-start [&_[data-description]]:hidden" > <SelectValue placeholder="Select a model" /> </SelectTrigger> <SelectContent> <SelectItem value="genesis"> <div className="flex items-start gap-3 text-muted-foreground"> <Rabbit className="size-5" /> <div className="grid gap-0.5"> <p> Neural{" "} <span className="font-medium text-foreground"> Genesis </span> </p> <p className="text-xs" data-description> Our fastest model for general use cases. </p> </div> </div> </SelectItem> <SelectItem value="explorer"> <div className="flex items-start gap-3 text-muted-foreground"> <Bird className="size-5" /> <div className="grid gap-0.5"> <p> Neural{" "} <span className="font-medium text-foreground"> Explorer </span> </p> <p className="text-xs" data-description> Performance and speed for efficiency. </p> </div> </div> </SelectItem> <SelectItem value="quantum"> <div className="flex items-start gap-3 text-muted-foreground"> <Turtle className="size-5" /> <div className="grid gap-0.5"> <p> Neural{" "} <span className="font-medium text-foreground"> Quantum </span> </p> <p className="text-xs" data-description> The most powerful model for complex computations. </p> </div> </div> </SelectItem> </SelectContent> </Select> </div> <div className="grid gap-3"> <Label htmlFor="temperature">Temperature</Label> <Input id="temperature" type="number" placeholder="0.4" /> </div> <div className="grid gap-3"> <Label htmlFor="top-p">Top P</Label> <Input id="top-p" type="number" placeholder="0.7" /> </div> <div className="grid gap-3"> <Label htmlFor="top-k">Top K</Label> <Input id="top-k" type="number" placeholder="0.0" /> </div> </fieldset> <fieldset className="grid gap-6 rounded-lg border p-4"> <legend className="-ml-1 px-1 text-sm font-medium"> Messages </legend> <div className="grid gap-3"> <Label htmlFor="role">Role</Label> <Select defaultValue="system"> <SelectTrigger> <SelectValue placeholder="Select a role" /> </SelectTrigger> <SelectContent> <SelectItem value="system">System</SelectItem> <SelectItem value="user">User</SelectItem> <SelectItem value="assistant">Assistant</SelectItem> </SelectContent> </Select> </div> <div className="grid gap-3"> <Label htmlFor="content">Content</Label> <Textarea id="content" placeholder="You are a..." /> </div> </fieldset> </form> </DrawerContent> </Drawer> <Button variant="outline" size="sm" className="ml-auto gap-1.5 text-sm" > <Share className="size-3.5" /> Share </Button> </header> <main className="grid flex-1 gap-4 overflow-auto p-4 md:grid-cols-2 lg:grid-cols-3"> <div className="relative hidden flex-col items-start gap-8 md:flex" x-chunk="A settings form a configuring an AI model and messages." > <form className="grid w-full items-start gap-6"> <fieldset className="grid gap-6 rounded-lg border p-4"> <legend className="-ml-1 px-1 text-sm font-medium"> Settings </legend> <div className="grid gap-3"> <Label htmlFor="model">Model</Label> <Select> <SelectTrigger id="model" className="items-start [&_[data-description]]:hidden" > <SelectValue placeholder="Select a model" /> </SelectTrigger> <SelectContent> <SelectItem value="genesis"> <div className="flex items-start gap-3 text-muted-foreground"> <Rabbit className="size-5" /> <div className="grid gap-0.5"> <p> Neural{" "} <span className="font-medium text-foreground"> Genesis </span> </p> <p className="text-xs" data-description> Our fastest model for general use cases. </p> </div> </div> </SelectItem> <SelectItem value="explorer"> <div className="flex items-start gap-3 text-muted-foreground"> <Bird className="size-5" /> <div className="grid gap-0.5"> <p> Neural{" "} <span className="font-medium text-foreground"> Explorer </span> </p> <p className="text-xs" data-description> Performance and speed for efficiency. </p> </div> </div> </SelectItem> <SelectItem value="quantum"> <div className="flex items-start gap-3 text-muted-foreground"> <Turtle className="size-5" /> <div className="grid gap-0.5"> <p> Neural{" "} <span className="font-medium text-foreground"> Quantum </span> </p> <p className="text-xs" data-description> The most powerful model for complex computations. </p> </div> </div> </SelectItem> </SelectContent> </Select> </div> <div className="grid gap-3"> <Label htmlFor="temperature">Temperature</Label> <Input id="temperature" type="number" placeholder="0.4" /> </div> <div className="grid grid-cols-2 gap-4"> <div className="grid gap-3"> <Label htmlFor="top-p">Top P</Label> <Input id="top-p" type="number" placeholder="0.7" /> </div> <div className="grid gap-3"> <Label htmlFor="top-k">Top K</Label> <Input id="top-k" type="number" placeholder="0.0" /> </div> </div> </fieldset> <fieldset className="grid gap-6 rounded-lg border p-4"> <legend className="-ml-1 px-1 text-sm font-medium"> Messages </legend> <div className="grid gap-3"> <Label htmlFor="role">Role</Label> <Select defaultValue="system"> <SelectTrigger> <SelectValue placeholder="Select a role" /> </SelectTrigger> <SelectContent> <SelectItem value="system">System</SelectItem> <SelectItem value="user">User</SelectItem> <SelectItem value="assistant">Assistant</SelectItem> </SelectContent> </Select> </div> <div className="grid gap-3"> <Label htmlFor="content">Content</Label> <Textarea id="content" placeholder="You are a..." className="min-h-[9.5rem]" /> </div> </fieldset> </form> </div> <div className="relative flex h-full min-h-[50vh] flex-col rounded-xl bg-muted/50 p-4 lg:col-span-2"> <Badge variant="outline" className="absolute right-3 top-3"> Output </Badge> <div className="flex-1" /> <form className="relative overflow-hidden rounded-lg border bg-background focus-within:ring-1 focus-within:ring-ring" x-chunk="A form for sending a message to an AI chatbot. The form has a textarea and buttons to upload files and record audio." > <Label htmlFor="message" className="sr-only"> Message </Label> <Textarea id="message" placeholder="Type your message here..." className="min-h-12 resize-none border-0 p-3 shadow-none focus-visible:ring-0" /> <div className="flex items-center p-3 pt-0"> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon"> <Paperclip className="size-4" /> <span className="sr-only">Attach file</span> </Button> </TooltipTrigger> <TooltipContent side="top">Attach File</TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button variant="ghost" size="icon"> <Mic className="size-4" /> <span className="sr-only">Use Microphone</span> </Button> </TooltipTrigger> <TooltipContent side="top">Use Microphone</TooltipContent> </Tooltip> <Button type="submit" size="sm" className="ml-auto gap-1.5"> Send Message <CornerDownLeft className="size-3.5" /> </Button> </div> </form> </div> </main> </div> </div> ) }
shadcn-ui/ui/apps/www/registry/new-york/block/dashboard-03.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/block/dashboard-03.tsx", "repo_id": "shadcn-ui/ui", "token_count": 11046 }
143
"use client" import { PlusCircle } from "lucide-react" import { Button } from "@/registry/new-york/ui/button" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/registry/new-york/ui/card" import { Input } from "@/registry/new-york/ui/input" import { Label } from "@/registry/new-york/ui/label" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/registry/new-york/ui/table" import { ToggleGroup, ToggleGroupItem, } from "@/registry/new-york/ui/toggle-group" export default function Component() { return ( <Card x-chunk="dashboard-07-chunk-1"> <CardHeader> <CardTitle>Stock</CardTitle> <CardDescription> Lipsum dolor sit amet, consectetur adipiscing elit </CardDescription> </CardHeader> <CardContent> <Table> <TableHeader> <TableRow> <TableHead className="w-[100px]">SKU</TableHead> <TableHead>Stock</TableHead> <TableHead>Price</TableHead> <TableHead className="w-[100px]">Size</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-semibold">GGPC-001</TableCell> <TableCell> <Label htmlFor="stock-1" className="sr-only"> Stock </Label> <Input id="stock-1" type="number" defaultValue="100" /> </TableCell> <TableCell> <Label htmlFor="price-1" className="sr-only"> Price </Label> <Input id="price-1" type="number" defaultValue="99.99" /> </TableCell> <TableCell> <ToggleGroup type="single" defaultValue="s" variant="outline"> <ToggleGroupItem value="s">S</ToggleGroupItem> <ToggleGroupItem value="m">M</ToggleGroupItem> <ToggleGroupItem value="l">L</ToggleGroupItem> </ToggleGroup> </TableCell> </TableRow> <TableRow> <TableCell className="font-semibold">GGPC-002</TableCell> <TableCell> <Label htmlFor="stock-2" className="sr-only"> Stock </Label> <Input id="stock-2" type="number" defaultValue="143" /> </TableCell> <TableCell> <Label htmlFor="price-2" className="sr-only"> Price </Label> <Input id="price-2" type="number" defaultValue="99.99" /> </TableCell> <TableCell> <ToggleGroup type="single" defaultValue="m" variant="outline"> <ToggleGroupItem value="s">S</ToggleGroupItem> <ToggleGroupItem value="m">M</ToggleGroupItem> <ToggleGroupItem value="l">L</ToggleGroupItem> </ToggleGroup> </TableCell> </TableRow> <TableRow> <TableCell className="font-semibold">GGPC-003</TableCell> <TableCell> <Label htmlFor="stock-3" className="sr-only"> Stock </Label> <Input id="stock-3" type="number" defaultValue="32" /> </TableCell> <TableCell> <Label htmlFor="price-3" className="sr-only"> Stock </Label> <Input id="price-3" type="number" defaultValue="99.99" /> </TableCell> <TableCell> <ToggleGroup type="single" defaultValue="s" variant="outline"> <ToggleGroupItem value="s">S</ToggleGroupItem> <ToggleGroupItem value="m">M</ToggleGroupItem> <ToggleGroupItem value="l">L</ToggleGroupItem> </ToggleGroup> </TableCell> </TableRow> </TableBody> </Table> </CardContent> <CardFooter className="justify-center border-t p-4"> <Button size="sm" variant="ghost" className="gap-1"> <PlusCircle className="h-3.5 w-3.5" /> Add Variant </Button> </CardFooter> </Card> ) }
shadcn-ui/ui/apps/www/registry/new-york/block/dashboard-07-chunk-1.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/block/dashboard-07-chunk-1.tsx", "repo_id": "shadcn-ui/ui", "token_count": 2322 }
144
import { AppSidebar } from "@/registry/new-york/block/sidebar-01/components/app-sidebar" import { SidebarLayout, SidebarTrigger, } from "@/registry/new-york/block/sidebar-01/ui/sidebar" export const iframeHeight = "870px" export const containerClassName = "w-full h-full" export default async function Page() { const { cookies } = await import("next/headers") return ( <SidebarLayout defaultOpen={cookies().get("sidebar:state")?.value === "true"} > <AppSidebar /> <main className="flex flex-1 flex-col p-2 transition-all duration-300 ease-in-out"> <div className="h-full rounded-md border-2 border-dashed p-2"> <SidebarTrigger /> </div> </main> </SidebarLayout> ) }
shadcn-ui/ui/apps/www/registry/new-york/block/sidebar-01/page.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/block/sidebar-01/page.tsx", "repo_id": "shadcn-ui/ui", "token_count": 290 }
145
"use client" import * as React from "react" import Link from "next/link" import { useMediaQuery } from "@/hooks/use-media-query" import { Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, } from "@/registry/new-york/ui/breadcrumb" import { Button } from "@/registry/new-york/ui/button" import { Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerTitle, DrawerTrigger, } from "@/registry/new-york/ui/drawer" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/registry/new-york/ui/dropdown-menu" const items = [ { href: "#", label: "Home" }, { href: "#", label: "Documentation" }, { href: "#", label: "Building Your Application" }, { href: "#", label: "Data Fetching" }, { label: "Caching and Revalidating" }, ] const ITEMS_TO_DISPLAY = 3 export default function BreadcrumbResponsive() { const [open, setOpen] = React.useState(false) const isDesktop = useMediaQuery("(min-width: 768px)") return ( <Breadcrumb> <BreadcrumbList> <BreadcrumbItem> <BreadcrumbLink href={items[0].href}>{items[0].label}</BreadcrumbLink> </BreadcrumbItem> <BreadcrumbSeparator /> {items.length > ITEMS_TO_DISPLAY ? ( <> <BreadcrumbItem> {isDesktop ? ( <DropdownMenu open={open} onOpenChange={setOpen}> <DropdownMenuTrigger className="flex items-center gap-1" aria-label="Toggle menu" > <BreadcrumbEllipsis className="h-4 w-4" /> </DropdownMenuTrigger> <DropdownMenuContent align="start"> {items.slice(1, -2).map((item, index) => ( <DropdownMenuItem key={index}> <Link href={item.href ? item.href : "#"}> {item.label} </Link> </DropdownMenuItem> ))} </DropdownMenuContent> </DropdownMenu> ) : ( <Drawer open={open} onOpenChange={setOpen}> <DrawerTrigger aria-label="Toggle Menu"> <BreadcrumbEllipsis className="h-4 w-4" /> </DrawerTrigger> <DrawerContent> <DrawerHeader className="text-left"> <DrawerTitle>Navigate to</DrawerTitle> <DrawerDescription> Select a page to navigate to. </DrawerDescription> </DrawerHeader> <div className="grid gap-1 px-4"> {items.slice(1, -2).map((item, index) => ( <Link key={index} href={item.href ? item.href : "#"} className="py-1 text-sm" > {item.label} </Link> ))} </div> <DrawerFooter className="pt-4"> <DrawerClose asChild> <Button variant="outline">Close</Button> </DrawerClose> </DrawerFooter> </DrawerContent> </Drawer> )} </BreadcrumbItem> <BreadcrumbSeparator /> </> ) : null} {items.slice(-ITEMS_TO_DISPLAY + 1).map((item, index) => ( <BreadcrumbItem key={index}> {item.href ? ( <> <BreadcrumbLink asChild className="max-w-20 truncate md:max-w-none" > <Link href={item.href}>{item.label}</Link> </BreadcrumbLink> <BreadcrumbSeparator /> </> ) : ( <BreadcrumbPage className="max-w-20 truncate md:max-w-none"> {item.label} </BreadcrumbPage> )} </BreadcrumbItem> ))} </BreadcrumbList> </Breadcrumb> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/breadcrumb-responsive.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/breadcrumb-responsive.tsx", "repo_id": "shadcn-ui/ui", "token_count": 2459 }
146
"use client" import * as React from "react" import { MinusIcon, PlusIcon } from "@radix-ui/react-icons" import { useTheme } from "next-themes" import { Bar, BarChart, ResponsiveContainer } from "recharts" import { useConfig } from "@/hooks/use-config" import { Button } from "@/registry/new-york/ui/button" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/registry/new-york/ui/card" import { baseColors } from "@/registry/registry-base-colors" const data = [ { goal: 400, }, { goal: 300, }, { goal: 200, }, { goal: 300, }, { goal: 200, }, { goal: 278, }, { goal: 189, }, { goal: 239, }, { goal: 300, }, { goal: 200, }, { goal: 278, }, { goal: 189, }, { goal: 349, }, ] export function CardsActivityGoal() { const { theme: mode } = useTheme() const [config] = useConfig() const baseColor = baseColors.find( (baseColor) => baseColor.name === config.theme ) const [goal, setGoal] = React.useState(350) function onClick(adjustment: number) { setGoal(Math.max(200, Math.min(400, goal + adjustment))) } return ( <Card> <CardHeader className="pb-4"> <CardTitle>Move Goal</CardTitle> <CardDescription>Set your daily activity goal.</CardDescription> </CardHeader> <CardContent className="pb-2"> <div className="flex items-center justify-center space-x-2"> <Button variant="outline" size="icon" className="h-8 w-8 shrink-0 rounded-full" onClick={() => onClick(-10)} disabled={goal <= 200} > <MinusIcon className="h-4 w-4" /> <span className="sr-only">Decrease</span> </Button> <div className="flex-1 text-center"> <div className="text-5xl font-bold tracking-tighter">{goal}</div> <div className="text-[0.70rem] uppercase text-muted-foreground"> Calories/day </div> </div> <Button variant="outline" size="icon" className="h-8 w-8 shrink-0 rounded-full" onClick={() => onClick(10)} disabled={goal >= 400} > <PlusIcon className="h-4 w-4" /> <span className="sr-only">Increase</span> </Button> </div> <div className="my-3 h-[60px]"> <ResponsiveContainer width="100%" height="100%"> <BarChart data={data}> <Bar dataKey="goal" style={ { fill: "var(--theme-primary)", opacity: 0.2, "--theme-primary": `hsl(${ baseColor?.cssVars[mode === "dark" ? "dark" : "light"] .primary })`, } as React.CSSProperties } /> </BarChart> </ResponsiveContainer> </div> </CardContent> <CardFooter> <Button className="w-full">Set Goal</Button> </CardFooter> </Card> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/cards/activity-goal.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/cards/activity-goal.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1612 }
147
import * as React from "react" import Autoplay from "embla-carousel-autoplay" import { Card, CardContent } from "@/registry/new-york/ui/card" import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, } from "@/registry/new-york/ui/carousel" export default function CarouselPlugin() { const plugin = React.useRef( Autoplay({ delay: 2000, stopOnInteraction: true }) ) return ( <Carousel plugins={[plugin.current]} className="w-full max-w-xs" onMouseEnter={plugin.current.stop} onMouseLeave={plugin.current.reset} > <CarouselContent> {Array.from({ length: 5 }).map((_, index) => ( <CarouselItem key={index}> <div className="p-1"> <Card> <CardContent className="flex aspect-square items-center justify-center p-6"> <span className="text-4xl font-semibold">{index + 1}</span> </CardContent> </Card> </div> </CarouselItem> ))} </CarouselContent> <CarouselPrevious /> <CarouselNext /> </Carousel> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/carousel-plugin.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/carousel-plugin.tsx", "repo_id": "shadcn-ui/ui", "token_count": 517 }
148
"use client" import * as React from "react" import { DotsHorizontalIcon } from "@radix-ui/react-icons" import { Button } from "@/registry/new-york/ui/button" import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/registry/new-york/ui/command" import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, } from "@/registry/new-york/ui/dropdown-menu" const labels = [ "feature", "bug", "enhancement", "documentation", "design", "question", "maintenance", ] export default function ComboboxDropdownMenu() { const [label, setLabel] = React.useState("feature") const [open, setOpen] = React.useState(false) return ( <div className="flex w-full flex-col items-start justify-between rounded-md border px-4 py-3 sm:flex-row sm:items-center"> <p className="text-sm font-medium leading-none"> <span className="mr-2 rounded-lg bg-primary px-2 py-1 text-xs text-primary-foreground"> {label} </span> <span className="text-muted-foreground">Create a new project</span> </p> <DropdownMenu open={open} onOpenChange={setOpen}> <DropdownMenuTrigger asChild> <Button variant="ghost" size="sm"> <DotsHorizontalIcon /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="w-[200px]"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuGroup> <DropdownMenuItem>Assign to...</DropdownMenuItem> <DropdownMenuItem>Set due date...</DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuSub> <DropdownMenuSubTrigger>Apply label</DropdownMenuSubTrigger> <DropdownMenuSubContent className="p-0"> <Command> <CommandInput placeholder="Filter label..." autoFocus={true} className="h-9" /> <CommandList> <CommandEmpty>No label found.</CommandEmpty> <CommandGroup> {labels.map((label) => ( <CommandItem key={label} value={label} onSelect={(value) => { setLabel(value) setOpen(false) }} > {label} </CommandItem> ))} </CommandGroup> </CommandList> </Command> </DropdownMenuSubContent> </DropdownMenuSub> <DropdownMenuSeparator /> <DropdownMenuItem className="text-red-600"> Delete <DropdownMenuShortcut></DropdownMenuShortcut> </DropdownMenuItem> </DropdownMenuGroup> </DropdownMenuContent> </DropdownMenu> </div> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/combobox-dropdown-menu.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/combobox-dropdown-menu.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1623 }
149
"use client" import * as React from "react" import { DropdownMenuCheckboxItemProps } from "@radix-ui/react-dropdown-menu" import { Button } from "@/registry/new-york/ui/button" import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/registry/new-york/ui/dropdown-menu" type Checked = DropdownMenuCheckboxItemProps["checked"] export default function DropdownMenuCheckboxes() { const [showStatusBar, setShowStatusBar] = React.useState<Checked>(true) const [showActivityBar, setShowActivityBar] = React.useState<Checked>(false) const [showPanel, setShowPanel] = React.useState<Checked>(false) return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline">Open</Button> </DropdownMenuTrigger> <DropdownMenuContent className="w-56"> <DropdownMenuLabel>Appearance</DropdownMenuLabel> <DropdownMenuSeparator /> <DropdownMenuCheckboxItem checked={showStatusBar} onCheckedChange={setShowStatusBar} > Status Bar </DropdownMenuCheckboxItem> <DropdownMenuCheckboxItem checked={showActivityBar} onCheckedChange={setShowActivityBar} disabled > Activity Bar </DropdownMenuCheckboxItem> <DropdownMenuCheckboxItem checked={showPanel} onCheckedChange={setShowPanel} > Panel </DropdownMenuCheckboxItem> </DropdownMenuContent> </DropdownMenu> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/dropdown-menu-checkboxes.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/dropdown-menu-checkboxes.tsx", "repo_id": "shadcn-ui/ui", "token_count": 640 }
150
import { Checkbox } from "@/registry/new-york/ui/checkbox" import { Label } from "@/registry/new-york/ui/label" export default function LabelDemo() { return ( <div> <div className="flex items-center space-x-2"> <Checkbox id="terms" /> <Label htmlFor="terms">Accept terms and conditions</Label> </div> </div> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/label-demo.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/label-demo.tsx", "repo_id": "shadcn-ui/ui", "token_count": 143 }
151
"use client" import Link from "next/link" 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/registry/new-york/ui/select" const FormSchema = z.object({ email: z .string({ required_error: "Please select an email to display.", }) .email(), }) export default function SelectForm() { 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="email" render={({ field }) => ( <FormItem> <FormLabel>Email</FormLabel> <Select onValueChange={field.onChange} defaultValue={field.value}> <FormControl> <SelectTrigger> <SelectValue placeholder="Select a verified email to display" /> </SelectTrigger> </FormControl> <SelectContent> <SelectItem value="[email protected]">[email protected]</SelectItem> <SelectItem value="[email protected]">[email protected]</SelectItem> <SelectItem value="[email protected]">[email protected]</SelectItem> </SelectContent> </Select> <FormDescription> You can manage email addresses in your{" "} <Link href="/examples/forms">email settings</Link>. </FormDescription> <FormMessage /> </FormItem> )} /> <Button type="submit">Submit</Button> </form> </Form> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/select-form.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/select-form.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1103 }
152
import { Button } from "@/registry/new-york/ui/button" import { Textarea } from "@/registry/new-york/ui/textarea" export default function TextareaWithButton() { return ( <div className="grid w-full gap-2"> <Textarea placeholder="Type your message here." /> <Button>Send message</Button> </div> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/textarea-with-button.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/textarea-with-button.tsx", "repo_id": "shadcn-ui/ui", "token_count": 117 }
153
import { FontItalicIcon } from "@radix-ui/react-icons" import { Toggle } from "@/registry/new-york/ui/toggle" export default function ToggleLg() { return ( <Toggle size="lg" aria-label="Toggle italic"> <FontItalicIcon className="h-4 w-4" /> </Toggle> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/toggle-lg.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/toggle-lg.tsx", "repo_id": "shadcn-ui/ui", "token_count": 113 }
154
export default function TypographyP() { return ( <p className="leading-7 [&:not(:first-child)]:mt-6"> The king, seeing how much happier his subjects were, realized the error of his ways and repealed the joke tax. </p> ) }
shadcn-ui/ui/apps/www/registry/new-york/example/typography-p.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/typography-p.tsx", "repo_id": "shadcn-ui/ui", "token_count": 86 }
155
"use client" import * as React from "react" import { ArrowLeftIcon, ArrowRightIcon } from "@radix-ui/react-icons" import useEmblaCarousel, { type UseEmblaCarouselType, } from "embla-carousel-react" import { cn } from "@/lib/utils" import { Button } from "@/registry/new-york/ui/button" type CarouselApi = UseEmblaCarouselType[1] type UseCarouselParameters = Parameters<typeof useEmblaCarousel> type CarouselOptions = UseCarouselParameters[0] type CarouselPlugin = UseCarouselParameters[1] type CarouselProps = { opts?: CarouselOptions plugins?: CarouselPlugin orientation?: "horizontal" | "vertical" setApi?: (api: CarouselApi) => void } type CarouselContextProps = { carouselRef: ReturnType<typeof useEmblaCarousel>[0] api: ReturnType<typeof useEmblaCarousel>[1] scrollPrev: () => void scrollNext: () => void canScrollPrev: boolean canScrollNext: boolean } & CarouselProps const CarouselContext = React.createContext<CarouselContextProps | null>(null) function useCarousel() { const context = React.useContext(CarouselContext) if (!context) { throw new Error("useCarousel must be used within a <Carousel />") } return context } const Carousel = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & CarouselProps >( ( { orientation = "horizontal", opts, setApi, plugins, className, children, ...props }, ref ) => { const [carouselRef, api] = useEmblaCarousel( { ...opts, axis: orientation === "horizontal" ? "x" : "y", }, plugins ) const [canScrollPrev, setCanScrollPrev] = React.useState(false) const [canScrollNext, setCanScrollNext] = React.useState(false) const onSelect = React.useCallback((api: CarouselApi) => { if (!api) { return } setCanScrollPrev(api.canScrollPrev()) setCanScrollNext(api.canScrollNext()) }, []) const scrollPrev = React.useCallback(() => { api?.scrollPrev() }, [api]) const scrollNext = React.useCallback(() => { api?.scrollNext() }, [api]) const handleKeyDown = React.useCallback( (event: React.KeyboardEvent<HTMLDivElement>) => { if (event.key === "ArrowLeft") { event.preventDefault() scrollPrev() } else if (event.key === "ArrowRight") { event.preventDefault() scrollNext() } }, [scrollPrev, scrollNext] ) React.useEffect(() => { if (!api || !setApi) { return } setApi(api) }, [api, setApi]) React.useEffect(() => { if (!api) { return } onSelect(api) api.on("reInit", onSelect) api.on("select", onSelect) return () => { api?.off("select", onSelect) } }, [api, onSelect]) return ( <CarouselContext.Provider value={{ carouselRef, api: api, opts, orientation: orientation || (opts?.axis === "y" ? "vertical" : "horizontal"), scrollPrev, scrollNext, canScrollPrev, canScrollNext, }} > <div ref={ref} onKeyDownCapture={handleKeyDown} className={cn("relative", className)} role="region" aria-roledescription="carousel" {...props} > {children} </div> </CarouselContext.Provider> ) } ) Carousel.displayName = "Carousel" const CarouselContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => { const { carouselRef, orientation } = useCarousel() return ( <div ref={carouselRef} className="overflow-hidden"> <div ref={ref} className={cn( "flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className )} {...props} /> </div> ) }) CarouselContent.displayName = "CarouselContent" const CarouselItem = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => { const { orientation } = useCarousel() return ( <div ref={ref} role="group" aria-roledescription="slide" className={cn( "min-w-0 shrink-0 grow-0 basis-full", orientation === "horizontal" ? "pl-4" : "pt-4", className )} {...props} /> ) }) CarouselItem.displayName = "CarouselItem" const CarouselPrevious = React.forwardRef< HTMLButtonElement, React.ComponentProps<typeof Button> >(({ className, variant = "outline", size = "icon", ...props }, ref) => { const { orientation, scrollPrev, canScrollPrev } = useCarousel() return ( <Button ref={ref} variant={variant} size={size} className={cn( "absolute h-8 w-8 rounded-full", orientation === "horizontal" ? "-left-12 top-1/2 -translate-y-1/2" : "-top-12 left-1/2 -translate-x-1/2 rotate-90", className )} disabled={!canScrollPrev} onClick={scrollPrev} {...props} > <ArrowLeftIcon className="h-4 w-4" /> <span className="sr-only">Previous slide</span> </Button> ) }) CarouselPrevious.displayName = "CarouselPrevious" const CarouselNext = React.forwardRef< HTMLButtonElement, React.ComponentProps<typeof Button> >(({ className, variant = "outline", size = "icon", ...props }, ref) => { const { orientation, scrollNext, canScrollNext } = useCarousel() return ( <Button ref={ref} variant={variant} size={size} className={cn( "absolute h-8 w-8 rounded-full", orientation === "horizontal" ? "-right-12 top-1/2 -translate-y-1/2" : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90", className )} disabled={!canScrollNext} onClick={scrollNext} {...props} > <ArrowRightIcon className="h-4 w-4" /> <span className="sr-only">Next slide</span> </Button> ) }) CarouselNext.displayName = "CarouselNext" export { type CarouselApi, Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext, }
shadcn-ui/ui/apps/www/registry/new-york/ui/carousel.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/ui/carousel.tsx", "repo_id": "shadcn-ui/ui", "token_count": 2702 }
156
import * as React from "react" import { ChevronLeftIcon, ChevronRightIcon, DotsHorizontalIcon, } from "@radix-ui/react-icons" import { cn } from "@/lib/utils" import { ButtonProps, buttonVariants } from "@/registry/new-york/ui/button" const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => ( <nav role="navigation" aria-label="pagination" className={cn("mx-auto flex w-full justify-center", className)} {...props} /> ) Pagination.displayName = "Pagination" const PaginationContent = React.forwardRef< HTMLUListElement, React.ComponentProps<"ul"> >(({ className, ...props }, ref) => ( <ul ref={ref} className={cn("flex flex-row items-center gap-1", className)} {...props} /> )) PaginationContent.displayName = "PaginationContent" const PaginationItem = React.forwardRef< HTMLLIElement, React.ComponentProps<"li"> >(({ className, ...props }, ref) => ( <li ref={ref} className={cn("", className)} {...props} /> )) PaginationItem.displayName = "PaginationItem" type PaginationLinkProps = { isActive?: boolean } & Pick<ButtonProps, "size"> & React.ComponentProps<"a"> const PaginationLink = ({ className, isActive, size = "icon", ...props }: PaginationLinkProps) => ( <a aria-current={isActive ? "page" : undefined} className={cn( buttonVariants({ variant: isActive ? "outline" : "ghost", size, }), className )} {...props} /> ) PaginationLink.displayName = "PaginationLink" const PaginationPrevious = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => ( <PaginationLink aria-label="Go to previous page" size="default" className={cn("gap-1 pl-2.5", className)} {...props} > <ChevronLeftIcon className="h-4 w-4" /> <span>Previous</span> </PaginationLink> ) PaginationPrevious.displayName = "PaginationPrevious" const PaginationNext = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => ( <PaginationLink aria-label="Go to next page" size="default" className={cn("gap-1 pr-2.5", className)} {...props} > <span>Next</span> <ChevronRightIcon className="h-4 w-4" /> </PaginationLink> ) PaginationNext.displayName = "PaginationNext" const PaginationEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => ( <span aria-hidden className={cn("flex h-9 w-9 items-center justify-center", className)} {...props} > <DotsHorizontalIcon className="h-4 w-4" /> <span className="sr-only">More pages</span> </span> ) PaginationEllipsis.displayName = "PaginationEllipsis" export { Pagination, PaginationContent, PaginationLink, PaginationItem, PaginationPrevious, PaginationNext, PaginationEllipsis, }
shadcn-ui/ui/apps/www/registry/new-york/ui/pagination.tsx
{ "file_path": "shadcn-ui/ui/apps/www/registry/new-york/ui/pagination.tsx", "repo_id": "shadcn-ui/ui", "token_count": 1088 }
157
// @sts-nocheck import { existsSync, promises as fs, readFileSync } from "fs" import { tmpdir } from "os" import path from "path" import { cwd } from "process" import template from "lodash.template" import { rimraf } from "rimraf" import { Project, ScriptKind, SyntaxKind } from "ts-morph" import { z } from "zod" import { registry } from "../registry" import { baseColors } from "../registry/registry-base-colors" import { colorMapping, colors } from "../registry/registry-colors" import { styles } from "../registry/registry-styles" import { Registry, RegistryEntry, registryEntrySchema, registryItemTypeSchema, registrySchema, } from "../registry/schema" const REGISTRY_PATH = path.join(process.cwd(), "public/r") const REGISTRY_INDEX_WHITELIST: z.infer<typeof registryItemTypeSchema>[] = [ "registry:ui", "registry:lib", "registry:hook", "registry:theme", "registry:block", ] const project = new Project({ compilerOptions: {}, }) async function createTempSourceFile(filename: string) { const dir = await fs.mkdtemp(path.join(tmpdir(), "shadcn-")) return path.join(dir, filename) } // ---------------------------------------------------------------------------- // Build __registry__/index.tsx. // ---------------------------------------------------------------------------- async function buildRegistry(registry: Registry) { let index = `// @ts-nocheck // This file is autogenerated by scripts/build-registry.ts // Do not edit this file directly. import * as React from "react" export const Index: Record<string, any> = { ` for (const style of styles) { index += ` "${style.name}": {` // Build style index. for (const item of registry) { const resolveFiles = item.files?.map( (file) => `registry/${style.name}/${ typeof file === "string" ? file : file.path }` ) if (!resolveFiles) { continue } const type = item.type.split(":")[1] let sourceFilename = "" let chunks: any = [] if (item.type === "registry:block") { const file = resolveFiles[0] const filename = path.basename(file) const raw = await fs.readFile(file, "utf8") const tempFile = await createTempSourceFile(filename) const sourceFile = project.createSourceFile(tempFile, raw, { scriptKind: ScriptKind.TSX, }) // Find all imports. const imports = new Map< string, { module: string text: string isDefault?: boolean } >() sourceFile.getImportDeclarations().forEach((node) => { const module = node.getModuleSpecifier().getLiteralValue() node.getNamedImports().forEach((item) => { imports.set(item.getText(), { module, text: node.getText(), }) }) const defaultImport = node.getDefaultImport() if (defaultImport) { imports.set(defaultImport.getText(), { module, text: defaultImport.getText(), isDefault: true, }) } }) // Find all opening tags with x-chunk attribute. const components = sourceFile .getDescendantsOfKind(SyntaxKind.JsxOpeningElement) .filter((node) => { return node.getAttribute("x-chunk") !== undefined }) chunks = await Promise.all( components.map(async (component, index) => { const chunkName = `${item.name}-chunk-${index}` // Get the value of x-chunk attribute. const attr = component .getAttributeOrThrow("x-chunk") .asKindOrThrow(SyntaxKind.JsxAttribute) const description = attr .getInitializerOrThrow() .asKindOrThrow(SyntaxKind.StringLiteral) .getLiteralValue() // Delete the x-chunk attribute. attr.remove() // Add a new attribute to the component. component.addAttribute({ name: "x-chunk", initializer: `"${chunkName}"`, }) // Get the value of x-chunk-container attribute. const containerAttr = component .getAttribute("x-chunk-container") ?.asKindOrThrow(SyntaxKind.JsxAttribute) const containerClassName = containerAttr ?.getInitializer() ?.asKindOrThrow(SyntaxKind.StringLiteral) .getLiteralValue() containerAttr?.remove() const parentJsxElement = component.getParentIfKindOrThrow( SyntaxKind.JsxElement ) // Find all opening tags on component. const children = parentJsxElement .getDescendantsOfKind(SyntaxKind.JsxOpeningElement) .map((node) => { return node.getTagNameNode().getText() }) .concat( parentJsxElement .getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement) .map((node) => { return node.getTagNameNode().getText() }) ) const componentImports = new Map< string, string | string[] | Set<string> >() children.forEach((child) => { const importLine = imports.get(child) if (importLine) { const imports = componentImports.get(importLine.module) || [] const newImports = importLine.isDefault ? importLine.text : new Set([...imports, child]) componentImports.set( importLine.module, importLine?.isDefault ? newImports : Array.from(newImports) ) } }) const componnetImportLines = Array.from( componentImports.keys() ).map((key) => { const values = componentImports.get(key) const specifier = Array.isArray(values) ? `{${values.join(",")}}` : values return `import ${specifier} from "${key}"` }) const code = ` 'use client' ${componnetImportLines.join("\n")} export default function Component() { return (${parentJsxElement.getText()}) }` const targetFile = file.replace(item.name, `${chunkName}`) const targetFilePath = path.join( cwd(), `registry/${style.name}/${type}/${chunkName}.tsx` ) // Write component file. rimraf.sync(targetFilePath) await fs.writeFile(targetFilePath, code, "utf8") return { name: chunkName, description, component: `React.lazy(() => import("@/registry/${style.name}/${type}/${chunkName}")),`, file: targetFile, container: { className: containerClassName, }, } }) ) // // Write the source file for blocks only. sourceFilename = `__registry__/${style.name}/${type}/${item.name}.tsx` if (item.files) { const files = item.files.map((file) => typeof file === "string" ? { type: "registry:page", path: file } : file ) if (files?.length) { sourceFilename = `__registry__/${style.name}/${files[0].path}` } } const sourcePath = path.join(process.cwd(), sourceFilename) if (!existsSync(sourcePath)) { await fs.mkdir(sourcePath, { recursive: true }) } rimraf.sync(sourcePath) await fs.writeFile(sourcePath, sourceFile.getText()) } let componentPath = `@/registry/${style.name}/${type}/${item.name}` if (item.files) { const files = item.files.map((file) => typeof file === "string" ? { type: "registry:page", path: file } : file ) if (files?.length) { componentPath = `@/registry/${style.name}/${files[0].path}` } } index += ` "${item.name}": { name: "${item.name}", type: "${item.type}", registryDependencies: ${JSON.stringify(item.registryDependencies)}, files: [${resolveFiles.map((file) => `"${file}"`)}], component: React.lazy(() => import("${componentPath}")), source: "${sourceFilename}", category: "${item.category}", subcategory: "${item.subcategory}", chunks: [${chunks.map( (chunk) => `{ name: "${chunk.name}", description: "${chunk.description ?? "No description"}", component: ${chunk.component} file: "${chunk.file}", container: { className: "${chunk.container.className}" } }` )}] },` } index += ` },` } index += ` } ` // ---------------------------------------------------------------------------- // Build registry/index.json. // ---------------------------------------------------------------------------- const items = registry .filter((item) => ["registry:ui"].includes(item.type)) .map((item) => { return { ...item, files: item.files?.map((_file) => { const file = typeof _file === "string" ? { path: _file, type: item.type, } : _file return file }), } }) const registryJson = JSON.stringify(items, null, 2) rimraf.sync(path.join(REGISTRY_PATH, "index.json")) await fs.writeFile( path.join(REGISTRY_PATH, "index.json"), registryJson, "utf8" ) // Write style index. rimraf.sync(path.join(process.cwd(), "__registry__/index.tsx")) await fs.writeFile(path.join(process.cwd(), "__registry__/index.tsx"), index) } // ---------------------------------------------------------------------------- // Build registry/styles/[style]/[name].json. // ---------------------------------------------------------------------------- async function buildStyles(registry: Registry) { for (const style of styles) { const targetPath = path.join(REGISTRY_PATH, "styles", style.name) // Create directory if it doesn't exist. if (!existsSync(targetPath)) { await fs.mkdir(targetPath, { recursive: true }) } for (const item of registry) { if (!REGISTRY_INDEX_WHITELIST.includes(item.type)) { continue } let files if (item.files) { files = await Promise.all( item.files.map(async (_file) => { const file = typeof _file === "string" ? { path: _file, type: item.type, content: "", target: "", } : _file const content = await fs.readFile( path.join(process.cwd(), "registry", style.name, file.path), "utf8" ) const tempFile = await createTempSourceFile(file.path) const sourceFile = project.createSourceFile(tempFile, content, { scriptKind: ScriptKind.TSX, }) sourceFile.getVariableDeclaration("iframeHeight")?.remove() sourceFile.getVariableDeclaration("containerClassName")?.remove() sourceFile.getVariableDeclaration("description")?.remove() return { path: file.path, type: file.type, content: sourceFile.getText(), target: file.target, } }) ) } const payload = registryEntrySchema .omit({ source: true, category: true, subcategory: true, chunks: true, }) .safeParse({ ...item, files, }) if (payload.success) { await fs.writeFile( path.join(targetPath, `${item.name}.json`), JSON.stringify(payload.data, null, 2), "utf8" ) } } } // ---------------------------------------------------------------------------- // Build registry/styles/index.json. // ---------------------------------------------------------------------------- const stylesJson = JSON.stringify(styles, null, 2) await fs.writeFile( path.join(REGISTRY_PATH, "styles/index.json"), stylesJson, "utf8" ) } // ---------------------------------------------------------------------------- // Build registry/styles/[name]/index.json. // ---------------------------------------------------------------------------- async function buildStylesIndex() { for (const style of styles) { const targetPath = path.join(REGISTRY_PATH, "styles", style.name) const dependencies = [ "tailwindcss-animate", "class-variance-authority", "lucide-react", ] // TODO: Remove this when we migrate to lucide-react. if (style.name === "new-york") { dependencies.push("@radix-ui/react-icons") } const payload: RegistryEntry = { name: style.name, type: "registry:style", dependencies, registryDependencies: ["utils"], tailwind: { config: { plugins: [`require("tailwindcss-animate")`], }, }, cssVars: {}, files: [], } await fs.writeFile( path.join(targetPath, "index.json"), JSON.stringify(payload, null, 2), "utf8" ) } } // ---------------------------------------------------------------------------- // Build registry/colors/index.json. // ---------------------------------------------------------------------------- async function buildThemes() { const colorsTargetPath = path.join(REGISTRY_PATH, "colors") rimraf.sync(colorsTargetPath) if (!existsSync(colorsTargetPath)) { await fs.mkdir(colorsTargetPath, { recursive: true }) } const colorsData: Record<string, any> = {} for (const [color, value] of Object.entries(colors)) { if (typeof value === "string") { colorsData[color] = value continue } if (Array.isArray(value)) { colorsData[color] = value.map((item) => ({ ...item, rgbChannel: item.rgb.replace(/^rgb\((\d+),(\d+),(\d+)\)$/, "$1 $2 $3"), hslChannel: item.hsl.replace( /^hsl\(([\d.]+),([\d.]+%),([\d.]+%)\)$/, "$1 $2 $3" ), })) continue } if (typeof value === "object") { colorsData[color] = { ...value, rgbChannel: value.rgb.replace(/^rgb\((\d+),(\d+),(\d+)\)$/, "$1 $2 $3"), hslChannel: value.hsl.replace( /^hsl\(([\d.]+),([\d.]+%),([\d.]+%)\)$/, "$1 $2 $3" ), } continue } } await fs.writeFile( path.join(colorsTargetPath, "index.json"), JSON.stringify(colorsData, null, 2), "utf8" ) // ---------------------------------------------------------------------------- // Build registry/colors/[base].json. // ---------------------------------------------------------------------------- const BASE_STYLES = `@tailwind base; @tailwind components; @tailwind utilities; ` const BASE_STYLES_WITH_VARIABLES = `@tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: <%- colors.light["background"] %>; --foreground: <%- colors.light["foreground"] %>; --card: <%- colors.light["card"] %>; --card-foreground: <%- colors.light["card-foreground"] %>; --popover: <%- colors.light["popover"] %>; --popover-foreground: <%- colors.light["popover-foreground"] %>; --primary: <%- colors.light["primary"] %>; --primary-foreground: <%- colors.light["primary-foreground"] %>; --secondary: <%- colors.light["secondary"] %>; --secondary-foreground: <%- colors.light["secondary-foreground"] %>; --muted: <%- colors.light["muted"] %>; --muted-foreground: <%- colors.light["muted-foreground"] %>; --accent: <%- colors.light["accent"] %>; --accent-foreground: <%- colors.light["accent-foreground"] %>; --destructive: <%- colors.light["destructive"] %>; --destructive-foreground: <%- colors.light["destructive-foreground"] %>; --border: <%- colors.light["border"] %>; --input: <%- colors.light["input"] %>; --ring: <%- colors.light["ring"] %>; --radius: 0.5rem; --chart-1: <%- colors.light["chart-1"] %>; --chart-2: <%- colors.light["chart-2"] %>; --chart-3: <%- colors.light["chart-3"] %>; --chart-4: <%- colors.light["chart-4"] %>; --chart-5: <%- colors.light["chart-5"] %>; } .dark { --background: <%- colors.dark["background"] %>; --foreground: <%- colors.dark["foreground"] %>; --card: <%- colors.dark["card"] %>; --card-foreground: <%- colors.dark["card-foreground"] %>; --popover: <%- colors.dark["popover"] %>; --popover-foreground: <%- colors.dark["popover-foreground"] %>; --primary: <%- colors.dark["primary"] %>; --primary-foreground: <%- colors.dark["primary-foreground"] %>; --secondary: <%- colors.dark["secondary"] %>; --secondary-foreground: <%- colors.dark["secondary-foreground"] %>; --muted: <%- colors.dark["muted"] %>; --muted-foreground: <%- colors.dark["muted-foreground"] %>; --accent: <%- colors.dark["accent"] %>; --accent-foreground: <%- colors.dark["accent-foreground"] %>; --destructive: <%- colors.dark["destructive"] %>; --destructive-foreground: <%- colors.dark["destructive-foreground"] %>; --border: <%- colors.dark["border"] %>; --input: <%- colors.dark["input"] %>; --ring: <%- colors.dark["ring"] %>; --chart-1: <%- colors.dark["chart-1"] %>; --chart-2: <%- colors.dark["chart-2"] %>; --chart-3: <%- colors.dark["chart-3"] %>; --chart-4: <%- colors.dark["chart-4"] %>; --chart-5: <%- colors.dark["chart-5"] %>; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } }` for (const baseColor of ["slate", "gray", "zinc", "neutral", "stone"]) { const base: Record<string, any> = { inlineColors: {}, cssVars: {}, } for (const [mode, values] of Object.entries(colorMapping)) { base["inlineColors"][mode] = {} base["cssVars"][mode] = {} for (const [key, value] of Object.entries(values)) { if (typeof value === "string") { // Chart colors do not have a 1-to-1 mapping with tailwind colors. if (key.startsWith("chart-")) { base["cssVars"][mode][key] = value continue } const resolvedColor = value.replace(/{{base}}-/g, `${baseColor}-`) base["inlineColors"][mode][key] = resolvedColor const [resolvedBase, scale] = resolvedColor.split("-") const color = scale ? colorsData[resolvedBase].find( (item: any) => item.scale === parseInt(scale) ) : colorsData[resolvedBase] if (color) { base["cssVars"][mode][key] = color.hslChannel } } } } // Build css vars. base["inlineColorsTemplate"] = template(BASE_STYLES)({}) base["cssVarsTemplate"] = template(BASE_STYLES_WITH_VARIABLES)({ colors: base["cssVars"], }) await fs.writeFile( path.join(REGISTRY_PATH, `colors/${baseColor}.json`), JSON.stringify(base, null, 2), "utf8" ) // ---------------------------------------------------------------------------- // Build registry/themes.css // ---------------------------------------------------------------------------- const THEME_STYLES_WITH_VARIABLES = ` .theme-<%- theme %> { --background: <%- colors.light["background"] %>; --foreground: <%- colors.light["foreground"] %>; --muted: <%- colors.light["muted"] %>; --muted-foreground: <%- colors.light["muted-foreground"] %>; --popover: <%- colors.light["popover"] %>; --popover-foreground: <%- colors.light["popover-foreground"] %>; --card: <%- colors.light["card"] %>; --card-foreground: <%- colors.light["card-foreground"] %>; --border: <%- colors.light["border"] %>; --input: <%- colors.light["input"] %>; --primary: <%- colors.light["primary"] %>; --primary-foreground: <%- colors.light["primary-foreground"] %>; --secondary: <%- colors.light["secondary"] %>; --secondary-foreground: <%- colors.light["secondary-foreground"] %>; --accent: <%- colors.light["accent"] %>; --accent-foreground: <%- colors.light["accent-foreground"] %>; --destructive: <%- colors.light["destructive"] %>; --destructive-foreground: <%- colors.light["destructive-foreground"] %>; --ring: <%- colors.light["ring"] %>; --radius: <%- colors.light["radius"] %>; } .dark .theme-<%- theme %> { --background: <%- colors.dark["background"] %>; --foreground: <%- colors.dark["foreground"] %>; --muted: <%- colors.dark["muted"] %>; --muted-foreground: <%- colors.dark["muted-foreground"] %>; --popover: <%- colors.dark["popover"] %>; --popover-foreground: <%- colors.dark["popover-foreground"] %>; --card: <%- colors.dark["card"] %>; --card-foreground: <%- colors.dark["card-foreground"] %>; --border: <%- colors.dark["border"] %>; --input: <%- colors.dark["input"] %>; --primary: <%- colors.dark["primary"] %>; --primary-foreground: <%- colors.dark["primary-foreground"] %>; --secondary: <%- colors.dark["secondary"] %>; --secondary-foreground: <%- colors.dark["secondary-foreground"] %>; --accent: <%- colors.dark["accent"] %>; --accent-foreground: <%- colors.dark["accent-foreground"] %>; --destructive: <%- colors.dark["destructive"] %>; --destructive-foreground: <%- colors.dark["destructive-foreground"] %>; --ring: <%- colors.dark["ring"] %>; }` const themeCSS = [] for (const theme of baseColors) { themeCSS.push( // @ts-ignore template(THEME_STYLES_WITH_VARIABLES)({ colors: theme.cssVars, theme: theme.name, }) ) } await fs.writeFile( path.join(REGISTRY_PATH, `themes.css`), themeCSS.join("\n"), "utf8" ) // ---------------------------------------------------------------------------- // Build registry/themes/[theme].json // ---------------------------------------------------------------------------- rimraf.sync(path.join(REGISTRY_PATH, "themes")) for (const baseColor of ["slate", "gray", "zinc", "neutral", "stone"]) { const payload: Record<string, any> = { name: baseColor, label: baseColor.charAt(0).toUpperCase() + baseColor.slice(1), cssVars: {}, } for (const [mode, values] of Object.entries(colorMapping)) { payload.cssVars[mode] = {} for (const [key, value] of Object.entries(values)) { if (typeof value === "string") { const resolvedColor = value.replace(/{{base}}-/g, `${baseColor}-`) payload.cssVars[mode][key] = resolvedColor const [resolvedBase, scale] = resolvedColor.split("-") const color = scale ? colorsData[resolvedBase].find( (item: any) => item.scale === parseInt(scale) ) : colorsData[resolvedBase] if (color) { payload["cssVars"][mode][key] = color.hslChannel } } } } const targetPath = path.join(REGISTRY_PATH, "themes") // Create directory if it doesn't exist. if (!existsSync(targetPath)) { await fs.mkdir(targetPath, { recursive: true }) } await fs.writeFile( path.join(targetPath, `${payload.name}.json`), JSON.stringify(payload, null, 2), "utf8" ) } } } try { const result = registrySchema.safeParse(registry) if (!result.success) { console.error(result.error) process.exit(1) } await buildRegistry(result.data) await buildStyles(result.data) await buildStylesIndex() await buildThemes() console.log(" Done!") } catch (error) { console.error(error) process.exit(1) }
shadcn-ui/ui/apps/www/scripts/build-registry.mts
{ "file_path": "shadcn-ui/ui/apps/www/scripts/build-registry.mts", "repo_id": "shadcn-ui/ui", "token_count": 10653 }
158
import { existsSync, promises as fs } from "fs" import path from "path" import { DEPRECATED_MESSAGE } from "@/src/deprecated" import { DEFAULT_COMPONENTS, DEFAULT_TAILWIND_CONFIG, DEFAULT_TAILWIND_CSS, DEFAULT_UTILS, getConfig, rawConfigSchema, resolveConfigPaths, type Config, } from "@/src/utils/get-config" import { getPackageManager } from "@/src/utils/get-package-manager" import { getProjectConfig, preFlight } from "@/src/utils/get-project-info" import { handleError } from "@/src/utils/handle-error" import { logger } from "@/src/utils/logger" import { getRegistryBaseColor, getRegistryBaseColors, getRegistryStyles, } from "@/src/utils/registry" import * as templates from "@/src/utils/templates" import chalk from "chalk" import { Command } from "commander" import { execa } from "execa" import template from "lodash.template" import ora from "ora" import prompts from "prompts" import { z } from "zod" import { applyPrefixesCss } from "../utils/transformers/transform-tw-prefix" const PROJECT_DEPENDENCIES = [ "tailwindcss-animate", "class-variance-authority", "clsx", "tailwind-merge", ] const initOptionsSchema = z.object({ cwd: z.string(), yes: z.boolean(), defaults: z.boolean(), }) export const init = new Command() .name("init") .description("initialize your project and install dependencies") .option("-y, --yes", "skip confirmation prompt.", false) .option("-d, --defaults,", "use default configuration.", false) .option( "-c, --cwd <cwd>", "the working directory. defaults to the current directory.", process.cwd() ) .action(async (opts) => { try { console.log(DEPRECATED_MESSAGE) const options = initOptionsSchema.parse(opts) const cwd = path.resolve(options.cwd) // Ensure target directory exists. if (!existsSync(cwd)) { logger.error(`The path ${cwd} does not exist. Please try again.`) process.exit(1) } preFlight(cwd) const projectConfig = await getProjectConfig(cwd) if (projectConfig) { const config = await promptForMinimalConfig( cwd, projectConfig, opts.defaults ) await runInit(cwd, config) } else { // Read config. const existingConfig = await getConfig(cwd) const config = await promptForConfig(cwd, existingConfig, options.yes) await runInit(cwd, config) } logger.info("") logger.info( `${chalk.green( "Success!" )} Project initialization completed. You may now add components.` ) logger.info("") } catch (error) { handleError(error) } }) export async function promptForConfig( cwd: string, defaultConfig: Config | null = null, skip = false ) { const highlight = (text: string) => chalk.cyan(text) const styles = await getRegistryStyles() const baseColors = await getRegistryBaseColors() const options = await prompts([ { type: "toggle", name: "typescript", message: `Would you like to use ${highlight( "TypeScript" )} (recommended)?`, initial: defaultConfig?.tsx ?? true, active: "yes", inactive: "no", }, { type: "select", name: "style", message: `Which ${highlight("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 ${highlight( "base color" )}?`, choices: baseColors.map((color) => ({ title: color.label, value: color.name, })), }, { type: "text", name: "tailwindCss", message: `Where is your ${highlight("global CSS")} file?`, initial: defaultConfig?.tailwind.css ?? DEFAULT_TAILWIND_CSS, }, { type: "toggle", name: "tailwindCssVariables", message: `Would you like to use ${highlight( "CSS variables" )} for colors?`, initial: defaultConfig?.tailwind.cssVariables ?? true, active: "yes", inactive: "no", }, { type: "text", name: "tailwindPrefix", message: `Are you using a custom ${highlight( "tailwind prefix eg. tw-" )}? (Leave blank if not)`, initial: "", }, { type: "text", name: "tailwindConfig", message: `Where is your ${highlight("tailwind.config.js")} located?`, initial: defaultConfig?.tailwind.config ?? DEFAULT_TAILWIND_CONFIG, }, { type: "text", name: "components", message: `Configure the import alias for ${highlight("components")}:`, initial: defaultConfig?.aliases["components"] ?? DEFAULT_COMPONENTS, }, { type: "text", name: "utils", message: `Configure the import alias for ${highlight("utils")}:`, initial: defaultConfig?.aliases["utils"] ?? DEFAULT_UTILS, }, { type: "toggle", name: "rsc", message: `Are you using ${highlight("React Server Components")}?`, initial: defaultConfig?.rsc ?? true, active: "yes", inactive: "no", }, ]) const config = 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, }, }) if (!skip) { const { proceed } = await prompts({ type: "confirm", name: "proceed", message: `Write configuration to ${highlight( "components.json" )}. Proceed?`, initial: true, }) if (!proceed) { process.exit(0) } } // Write to file. logger.info("") const spinner = ora(`Writing components.json...`).start() const targetPath = path.resolve(cwd, "components.json") await fs.writeFile(targetPath, JSON.stringify(config, null, 2), "utf8") spinner.succeed() return await resolveConfigPaths(cwd, config) } export async function promptForMinimalConfig( cwd: string, defaultConfig: Config, defaults = false ) { const highlight = (text: string) => chalk.cyan(text) let style = defaultConfig.style let baseColor = defaultConfig.tailwind.baseColor let cssVariables = defaultConfig.tailwind.cssVariables if (!defaults) { const styles = await getRegistryStyles() const baseColors = await getRegistryBaseColors() const options = await prompts([ { type: "select", name: "style", message: `Which ${highlight("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 ${highlight( "base color" )}?`, choices: baseColors.map((color) => ({ title: color.label, value: color.name, })), }, { type: "toggle", name: "tailwindCssVariables", message: `Would you like to use ${highlight( "CSS variables" )} for colors?`, initial: defaultConfig?.tailwind.cssVariables, active: "yes", inactive: "no", }, ]) style = options.style baseColor = options.tailwindBaseColor cssVariables = options.tailwindCssVariables } const config = rawConfigSchema.parse({ $schema: defaultConfig?.$schema, style, tailwind: { ...defaultConfig?.tailwind, baseColor, cssVariables, }, rsc: defaultConfig?.rsc, tsx: defaultConfig?.tsx, aliases: defaultConfig?.aliases, }) // Write to file. logger.info("") const spinner = ora(`Writing components.json...`).start() const targetPath = path.resolve(cwd, "components.json") await fs.writeFile(targetPath, JSON.stringify(config, null, 2), "utf8") spinner.succeed() return await resolveConfigPaths(cwd, config) } export async function runInit(cwd: string, config: Config) { const spinner = ora(`Initializing project...`)?.start() // Ensure all resolved paths directories exist. for (const [key, resolvedPath] of Object.entries(config.resolvedPaths)) { // Determine if the path is a file or directory. // TODO: is there a better way to do this? let dirname = path.extname(resolvedPath) ? path.dirname(resolvedPath) : resolvedPath // If the utils alias is set to something like "@/lib/utils", // assume this is a file and remove the "utils" file name. // TODO: In future releases we should add support for individual utils. if (key === "utils" && resolvedPath.endsWith("/utils")) { // Remove /utils at the end. dirname = dirname.replace(/\/utils$/, "") } if (!existsSync(dirname)) { await fs.mkdir(dirname, { recursive: true }) } } const extension = config.tsx ? "ts" : "js" const tailwindConfigExtension = path.extname( config.resolvedPaths.tailwindConfig ) let tailwindConfigTemplate: string if (tailwindConfigExtension === ".ts") { tailwindConfigTemplate = config.tailwind.cssVariables ? templates.TAILWIND_CONFIG_TS_WITH_VARIABLES : templates.TAILWIND_CONFIG_TS } else { tailwindConfigTemplate = config.tailwind.cssVariables ? templates.TAILWIND_CONFIG_WITH_VARIABLES : templates.TAILWIND_CONFIG } // Write tailwind config. await fs.writeFile( config.resolvedPaths.tailwindConfig, template(tailwindConfigTemplate)({ extension, prefix: config.tailwind.prefix, }), "utf8" ) // Write css file. const baseColor = await getRegistryBaseColor(config.tailwind.baseColor) if (baseColor) { await fs.writeFile( config.resolvedPaths.tailwindCss, config.tailwind.cssVariables ? config.tailwind.prefix ? applyPrefixesCss(baseColor.cssVarsTemplate, config.tailwind.prefix) : baseColor.cssVarsTemplate : baseColor.inlineColorsTemplate, "utf8" ) } // Write cn file. await fs.writeFile( `${config.resolvedPaths.utils}.${extension}`, extension === "ts" ? templates.UTILS : templates.UTILS_JS, "utf8" ) spinner?.succeed() // Install dependencies. const dependenciesSpinner = ora(`Installing dependencies...`)?.start() const packageManager = await getPackageManager(cwd) // TODO: add support for other icon libraries. const deps = [ ...PROJECT_DEPENDENCIES, config.style === "new-york" ? "@radix-ui/react-icons" : "lucide-react", ] await execa( packageManager, [packageManager === "npm" ? "install" : "add", ...deps], { cwd, } ) dependenciesSpinner?.succeed() }
shadcn-ui/ui/packages/cli/src/commands/init.ts
{ "file_path": "shadcn-ui/ui/packages/cli/src/commands/init.ts", "repo_id": "shadcn-ui/ui", "token_count": 4437 }
159
import { type Transformer } from "@/src/utils/transformers" import { transformFromAstSync } from "@babel/core" import { ParserOptions, parse } from "@babel/parser" // @ts-ignore import transformTypescript from "@babel/plugin-transform-typescript" import * as recast from "recast" // TODO. // I'm using recast for the AST here. // Figure out if ts-morph AST is compatible with Babel. // This is a copy of the babel options from recast/parser. // The goal here is to tolerate as much syntax as possible. // We want to be able to parse any valid tsx code. // See https://github.com/benjamn/recast/blob/master/parsers/_babel_options.ts. const PARSE_OPTIONS: ParserOptions = { sourceType: "module", allowImportExportEverywhere: true, allowReturnOutsideFunction: true, startLine: 1, tokens: true, plugins: [ "asyncGenerators", "bigInt", "classPrivateMethods", "classPrivateProperties", "classProperties", "classStaticBlock", "decimal", "decorators-legacy", "doExpressions", "dynamicImport", "exportDefaultFrom", "exportNamespaceFrom", "functionBind", "functionSent", "importAssertions", "importMeta", "nullishCoalescingOperator", "numericSeparator", "objectRestSpread", "optionalCatchBinding", "optionalChaining", [ "pipelineOperator", { proposal: "minimal", }, ], [ "recordAndTuple", { syntaxType: "hash", }, ], "throwExpressions", "topLevelAwait", "v8intrinsic", "typescript", "jsx", ], } export const transformJsx: Transformer<String> = async ({ sourceFile, config, }) => { const output = sourceFile.getFullText() if (config.tsx) { return output } const ast = recast.parse(output, { parser: { parse: (code: string) => { return parse(code, PARSE_OPTIONS) }, }, }) const result = transformFromAstSync(ast, output, { cloneInputAst: false, code: false, ast: true, plugins: [transformTypescript], configFile: false, }) if (!result || !result.ast) { throw new Error("Failed to transform JSX") } return recast.print(result.ast).code }
shadcn-ui/ui/packages/cli/src/utils/transformers/transform-jsx.ts
{ "file_path": "shadcn-ui/ui/packages/cli/src/utils/transformers/transform-jsx.ts", "repo_id": "shadcn-ui/ui", "token_count": 847 }
160
/// <reference types="next" /> /// <reference types="next/image-types/global" /> // NOTE: This file should not be edited // see https://nextjs.org/docs/basic-features/typescript for more information.
shadcn-ui/ui/packages/cli/test/fixtures/next-app-src/next-env.d.ts
{ "file_path": "shadcn-ui/ui/packages/cli/test/fixtures/next-app-src/next-env.d.ts", "repo_id": "shadcn-ui/ui", "token_count": 58 }
161
import './globals.css' import type { Metadata } from 'next' import { Inter } from 'next/font/google' const inter = Inter({ subsets: ['latin'] }) export const metadata: Metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body className={inter.className}>{children}</body> </html> ) }
shadcn-ui/ui/packages/cli/test/fixtures/next-app/app/layout.tsx
{ "file_path": "shadcn-ui/ui/packages/cli/test/fixtures/next-app/app/layout.tsx", "repo_id": "shadcn-ui/ui", "token_count": 158 }
162
body { background-color: red; }
shadcn-ui/ui/packages/cli/test/fixtures/next-pages-src/src/other.css
{ "file_path": "shadcn-ui/ui/packages/cli/test/fixtures/next-pages-src/src/other.css", "repo_id": "shadcn-ui/ui", "token_count": 13 }
163
body { background-color: red; }
shadcn-ui/ui/packages/cli/test/fixtures/next-pages/pages/other.css
{ "file_path": "shadcn-ui/ui/packages/cli/test/fixtures/next-pages/pages/other.css", "repo_id": "shadcn-ui/ui", "token_count": 13 }
164
export const MISSING_DIR_OR_EMPTY_PROJECT = "1" export const EXISTING_CONFIG = "2" export const MISSING_CONFIG = "3" export const FAILED_CONFIG_READ = "4" export const TAILWIND_NOT_CONFIGURED = "5" export const IMPORT_ALIAS_MISSING = "6" export const UNSUPPORTED_FRAMEWORK = "7" export const COMPONENT_URL_NOT_FOUND = "8" export const COMPONENT_URL_UNAUTHORIZED = "9" export const COMPONENT_URL_FORBIDDEN = "10" export const COMPONENT_URL_BAD_REQUEST = "11" export const COMPONENT_URL_INTERNAL_SERVER_ERROR = "12"
shadcn-ui/ui/packages/shadcn/src/utils/errors.ts
{ "file_path": "shadcn-ui/ui/packages/shadcn/src/utils/errors.ts", "repo_id": "shadcn-ui/ui", "token_count": 200 }
165
import { Config } from "@/src/utils/get-config" import { Transformer } from "@/src/utils/transformers" export const transformImport: Transformer = async ({ sourceFile, config }) => { const importDeclarations = sourceFile.getImportDeclarations() for (const importDeclaration of importDeclarations) { const moduleSpecifier = updateImportAliases( importDeclaration.getModuleSpecifierValue(), config ) importDeclaration.setModuleSpecifier(moduleSpecifier) // Replace `import { cn } from "@/lib/utils"` if (moduleSpecifier == "@/lib/utils") { const namedImports = importDeclaration.getNamedImports() const cnImport = namedImports.find((i) => i.getName() === "cn") if (cnImport) { importDeclaration.setModuleSpecifier( moduleSpecifier.replace(/^@\/lib\/utils/, config.aliases.utils) ) } } } return sourceFile } function updateImportAliases(moduleSpecifier: string, config: Config) { // Not a local import. if (!moduleSpecifier.startsWith("@/")) { return moduleSpecifier } // Not a registry import. if (!moduleSpecifier.startsWith("@/registry/")) { // We fix the alias an return. const alias = config.aliases.components.charAt(0) return moduleSpecifier.replace(/^@\//, `${alias}/`) } if (moduleSpecifier.match(/^@\/registry\/(.+)\/ui/)) { return moduleSpecifier.replace( /^@\/registry\/(.+)\/ui/, config.aliases.ui ?? `${config.aliases.components}/ui` ) } if ( config.aliases.components && moduleSpecifier.match(/^@\/registry\/(.+)\/components/) ) { return moduleSpecifier.replace( /^@\/registry\/(.+)\/components/, config.aliases.components ) } if (config.aliases.lib && moduleSpecifier.match(/^@\/registry\/(.+)\/lib/)) { return moduleSpecifier.replace( /^@\/registry\/(.+)\/lib/, config.aliases.lib ) } if ( config.aliases.hooks && moduleSpecifier.match(/^@\/registry\/(.+)\/hooks/) ) { return moduleSpecifier.replace( /^@\/registry\/(.+)\/hooks/, config.aliases.hooks ) } return moduleSpecifier.replace( /^@\/registry\/[^/]+/, config.aliases.components ) }
shadcn-ui/ui/packages/shadcn/src/utils/transformers/transform-import.ts
{ "file_path": "shadcn-ui/ui/packages/shadcn/src/utils/transformers/transform-import.ts", "repo_id": "shadcn-ui/ui", "token_count": 861 }
166
import { Html, Head, Main, NextScript } from 'next/document' export default function Document() { return ( <Html lang="en"> <Head /> <body> <Main /> <NextScript /> </body> </Html> ) }
shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/next-pages-src/src/pages/_document.tsx
{ "file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/next-pages-src/src/pages/_document.tsx", "repo_id": "shadcn-ui/ui", "token_count": 105 }
167
import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, } from "@remix-run/node"; import { json, redirect } from "@remix-run/node"; import { Form, Link, useActionData, useSearchParams } from "@remix-run/react"; import { useEffect, useRef } from "react"; import { verifyLogin } from "~/models/user.server"; import { createUserSession, getUserId } from "~/session.server"; import { safeRedirect, validateEmail } from "~/utils"; export const loader = async ({ request }: LoaderFunctionArgs) => { const userId = await getUserId(request); if (userId) return redirect("/"); return json({}); }; export const action = async ({ request }: ActionFunctionArgs) => { const formData = await request.formData(); const email = formData.get("email"); const password = formData.get("password"); const redirectTo = safeRedirect(formData.get("redirectTo"), "/"); const remember = formData.get("remember"); if (!validateEmail(email)) { return json( { errors: { email: "Email is invalid", password: null } }, { status: 400 }, ); } if (typeof password !== "string" || password.length === 0) { return json( { errors: { email: null, password: "Password is required" } }, { status: 400 }, ); } if (password.length < 8) { return json( { errors: { email: null, password: "Password is too short" } }, { status: 400 }, ); } const user = await verifyLogin(email, password); if (!user) { return json( { errors: { email: "Invalid email or password", password: null } }, { status: 400 }, ); } return createUserSession({ redirectTo, remember: remember === "on" ? true : false, request, userId: user.id, }); }; export const meta: MetaFunction = () => [{ title: "Login" }]; export default function LoginPage() { const [searchParams] = useSearchParams(); const redirectTo = searchParams.get("redirectTo") || "/notes"; const actionData = useActionData<typeof action>(); const emailRef = useRef<HTMLInputElement>(null); const passwordRef = useRef<HTMLInputElement>(null); useEffect(() => { if (actionData?.errors?.email) { emailRef.current?.focus(); } else if (actionData?.errors?.password) { passwordRef.current?.focus(); } }, [actionData]); return ( <div className="flex min-h-full flex-col justify-center"> <div className="mx-auto w-full max-w-md px-8"> <Form method="post" className="space-y-6"> <div> <label htmlFor="email" className="block text-sm font-medium text-gray-700" > Email address </label> <div className="mt-1"> <input ref={emailRef} id="email" required // eslint-disable-next-line jsx-a11y/no-autofocus autoFocus={true} name="email" type="email" autoComplete="email" aria-invalid={actionData?.errors?.email ? true : undefined} aria-describedby="email-error" className="w-full rounded border border-gray-500 px-2 py-1 text-lg" /> {actionData?.errors?.email ? ( <div className="pt-1 text-red-700" id="email-error"> {actionData.errors.email} </div> ) : null} </div> </div> <div> <label htmlFor="password" className="block text-sm font-medium text-gray-700" > Password </label> <div className="mt-1"> <input id="password" ref={passwordRef} name="password" type="password" autoComplete="current-password" aria-invalid={actionData?.errors?.password ? true : undefined} aria-describedby="password-error" className="w-full rounded border border-gray-500 px-2 py-1 text-lg" /> {actionData?.errors?.password ? ( <div className="pt-1 text-red-700" id="password-error"> {actionData.errors.password} </div> ) : null} </div> </div> <input type="hidden" name="redirectTo" value={redirectTo} /> <button type="submit" className="w-full rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600 focus:bg-blue-400" > Log in </button> <div className="flex items-center justify-between"> <div className="flex items-center"> <input id="remember" name="remember" type="checkbox" className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" /> <label htmlFor="remember" className="ml-2 block text-sm text-gray-900" > Remember me </label> </div> <div className="text-center text-sm text-gray-500"> Don&apos;t have an account?{" "} <Link className="text-blue-500 underline" to={{ pathname: "/join", search: searchParams.toString(), }} > Sign up </Link> </div> </div> </Form> </div> </div> ); }
shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/routes/login.tsx
{ "file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/routes/login.tsx", "repo_id": "shadcn-ui/ui", "token_count": 2741 }
168
// Use this to create a new user and login with that user // Simply call this with: // npx ts-node -r tsconfig-paths/register ./cypress/support/create-user.ts [email protected], // and it will log out the cookie value you can use to interact with the server // as that new user. import { installGlobals } from "@remix-run/node"; import { parse } from "cookie"; import { createUser } from "~/models/user.server"; import { createUserSession } from "~/session.server"; installGlobals(); async function createAndLogin(email: string) { if (!email) { throw new Error("email required for login"); } if (!email.endsWith("@example.com")) { throw new Error("All test emails must end in @example.com"); } const user = await createUser(email, "myreallystrongpassword"); const response = await createUserSession({ request: new Request("test://test"), userId: user.id, remember: false, redirectTo: "/", }); const cookieValue = response.headers.get("Set-Cookie"); if (!cookieValue) { throw new Error("Cookie missing from createUserSession response"); } const parsedCookie = parse(cookieValue); // we log it like this so our cypress command can parse it out and set it as // the cookie value. console.log( ` <cookie> ${parsedCookie.__session} </cookie> `.trim(), ); } createAndLogin(process.argv[2]);
shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/cypress/support/create-user.ts
{ "file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/cypress/support/create-user.ts", "repo_id": "shadcn-ui/ui", "token_count": 431 }
169
/// <reference types="@remix-run/dev" /> /// <reference types="@remix-run/node" />
shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/remix.env.d.ts
{ "file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/remix.env.d.ts", "repo_id": "shadcn-ui/ui", "token_count": 30 }
170
/** * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful * for Docker builds. */ await import("./src/env.mjs"); /** @type {import("next").NextConfig} */ const config = { reactStrictMode: true, /** * If you have `experimental: { appDir: true }` set, then you must comment the below `i18n` config * out. * * @see https://github.com/vercel/next.js/issues/41980 */ i18n: { locales: ["en"], defaultLocale: "en", }, }; export default config;
shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/t3-pages/next.config.mjs
{ "file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/t3-pages/next.config.mjs", "repo_id": "shadcn-ui/ui", "token_count": 193 }
171
import { expect, test } from "vitest" import { transform } from "../../src/utils/transformers" import stone from "../fixtures/colors/stone.json" test("transform css vars", async () => { expect( await transform({ filename: "test.ts", raw: `import * as React from "react" export function Foo() { return <div className="bg-background hover:bg-muted text-primary-foreground sm:focus:text-accent-foreground">foo</div> }" `, config: { tsx: true, tailwind: { baseColor: "stone", cssVariables: true, }, aliases: { components: "@/components", utils: "@/lib/utils", }, }, baseColor: stone, }) ).toMatchSnapshot() expect( await transform({ filename: "test.ts", raw: `import * as React from "react" export function Foo() { return <div className="bg-background hover:bg-muted text-primary-foreground sm:focus:text-accent-foreground">foo</div> }" `, config: { tsx: true, tailwind: { baseColor: "stone", cssVariables: false, }, aliases: { components: "@/components", utils: "@/lib/utils", }, }, baseColor: stone, }) ).toMatchSnapshot() expect( await transform({ filename: "test.ts", raw: `import * as React from "react" export function Foo() { return <div className={cn("bg-background hover:bg-muted", true && "text-primary-foreground sm:focus:text-accent-foreground")}>foo</div> }" `, config: { tsx: true, tailwind: { baseColor: "stone", cssVariables: false, }, aliases: { components: "@/components", utils: "@/lib/utils", }, }, baseColor: stone, }) ).toMatchSnapshot() expect( await transform({ filename: "test.ts", raw: `import * as React from "react" export function Foo() { return <div className={cn("bg-background border border-input")}>foo</div> }" `, config: { tsx: true, tailwind: { baseColor: "stone", cssVariables: false, }, aliases: { components: "@/components", utils: "@/lib/utils", }, }, baseColor: stone, }) ).toMatchSnapshot() })
shadcn-ui/ui/packages/shadcn/test/utils/transform-css-vars.test.ts
{ "file_path": "shadcn-ui/ui/packages/shadcn/test/utils/transform-css-vars.test.ts", "repo_id": "shadcn-ui/ui", "token_count": 1083 }
172
/** @type {import('prettier').Config} */ module.exports = { endOfLine: "lf", semi: false, singleQuote: false, tabWidth: 2, trailingComma: "es5", importOrder: [ "^(react/(.*)$)|^(react$)", "^(next/(.*)$)|^(next$)", "<THIRD_PARTY_MODULES>", "", "^types$", "^@/types/(.*)$", "^@/config/(.*)$", "^@/lib/(.*)$", "^@/hooks/(.*)$", "^@/components/ui/(.*)$", "^@/components/(.*)$", "^@/registry/(.*)$", "^@/styles/(.*)$", "^@/app/(.*)$", "", "^[./]", ], importOrderSeparation: false, importOrderSortSpecifiers: true, importOrderBuiltinModulesToTop: true, importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"], importOrderMergeDuplicateImports: true, importOrderCombineTypeAndValueImports: true, plugins: ["@ianvs/prettier-plugin-sort-imports"], }
shadcn-ui/ui/prettier.config.cjs
{ "file_path": "shadcn-ui/ui/prettier.config.cjs", "repo_id": "shadcn-ui/ui", "token_count": 391 }
173
export function TailwindIndicator() { if (process.env.NODE_ENV === "production") return null return ( <div className="fixed bottom-1 left-1 z-50 flex h-6 w-6 items-center justify-center rounded-full bg-gray-800 p-3 font-mono text-xs text-white"> <div className="block sm:hidden">xs</div> <div className="hidden sm:block md:hidden">sm</div> <div className="hidden md:block lg:hidden">md</div> <div className="hidden lg:block xl:hidden">lg</div> <div className="hidden xl:block 2xl:hidden">xl</div> <div className="hidden 2xl:block">2xl</div> </div> ) }
shadcn-ui/ui/templates/next-template/components/tailwind-indicator.tsx
{ "file_path": "shadcn-ui/ui/templates/next-template/components/tailwind-indicator.tsx", "repo_id": "shadcn-ui/ui", "token_count": 243 }
174
@tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 100%; --foreground: 222.2 47.4% 11.2%; --muted: 210 40% 96.1%; --muted-foreground: 215.4 16.3% 46.9%; --popover: 0 0% 100%; --popover-foreground: 222.2 47.4% 11.2%; --border: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%; --card: 0 0% 100%; --card-foreground: 222.2 47.4% 11.2%; --primary: 222.2 47.4% 11.2%; --primary-foreground: 210 40% 98%; --secondary: 210 40% 96.1%; --secondary-foreground: 222.2 47.4% 11.2%; --accent: 210 40% 96.1%; --accent-foreground: 222.2 47.4% 11.2%; --destructive: 0 100% 50%; --destructive-foreground: 210 40% 98%; --ring: 215 20.2% 65.1%; --radius: 0.5rem; } .dark { --background: 224 71% 4%; --foreground: 213 31% 91%; --muted: 223 47% 11%; --muted-foreground: 215.4 16.3% 56.9%; --accent: 216 34% 17%; --accent-foreground: 210 40% 98%; --popover: 224 71% 4%; --popover-foreground: 215 20.2% 65.1%; --border: 216 34% 17%; --input: 216 34% 17%; --card: 224 71% 4%; --card-foreground: 213 31% 91%; --primary: 210 40% 98%; --primary-foreground: 222.2 47.4% 1.2%; --secondary: 222.2 47.4% 11.2%; --secondary-foreground: 210 40% 98%; --destructive: 0 63% 31%; --destructive-foreground: 210 40% 98%; --ring: 216 34% 17%; --radius: 0.5rem; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; font-feature-settings: "rlig" 1, "calt" 1; } }
shadcn-ui/ui/templates/next-template/styles/globals.css
{ "file_path": "shadcn-ui/ui/templates/next-template/styles/globals.css", "repo_id": "shadcn-ui/ui", "token_count": 737 }
175
"use client" import React from "react" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { Card, CardDescription, CardTitle } from "@/components/ui/card" import { Icons } from "@/components/icons" import AdBanner from "@/components/ad-banner" import { BellRing, ClipboardList, Flag, Folder, StickyNote, Trophy } from "lucide-react" import CreateNewComponent from "@/components/easyui/create-new" import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs" import { RotateCcw } from "lucide-react" import { CopyIcon } from "@radix-ui/react-icons" import LaunchPad from "@/components/easyui/launchpad" import KeyButton from "@/components/easyui/key-button" function KeyButtonComponent() { const [key, setKey] = React.useState(0); // State to trigger re-render return ( <div className="flex flex-wrap justify-start gap-4 pb-10 max-w-full min-w-full px-0 lg:px-20"> <div className="w-full sm:w-1/2 p-2 mt-3 space-y-4 lg:mt-5 md:lg-5"> <CardTitle className="text-3xl tracking-tight leading-7">Key Button</CardTitle> <CardDescription className="text-balance text-lg text-muted-foreground">Click or Hover</CardDescription> </div> <Tabs defaultValue="preview" className="relative mr-auto w-full"> <div className="flex items-center justify-between pb-3"> <TabsList className="w-full justify-start rounded-none bg-transparent p-0"> <TabsTrigger value="preview" className="relative h-9 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none"> Preview </TabsTrigger> <TabsTrigger value="code" className="relative h-9 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none"> Code </TabsTrigger> </TabsList> </div> <TabsContent value="preview" className="relative rounded-md" key={key}> <div className="flex items-center justify-center max-w-full mx-auto px-4 py-0.5 border rounded-lg h-[400px]"> <Button onClick={() => setKey((prev) => prev + 1)} className="absolute right-0 top-0 z-10 ml-4 flex items-center rounded-lg px-3 py-1" variant="ghost"> <RotateCcw size={16} /> </Button> {/* @ts-ignore */} <KeyButton text="Key Button" size="lg" /> </div> </TabsContent> <TabsContent value="code"> <div className="flex flex-col space-y-4 ml-3 lg:ml-4 md:lg-3"> <h2 className="font-semibold mt-12 scroll-m-20 border-b pb-2 text-2xl tracking-tight first:mt-0 leading-7"> Installation </h2> <p className="font-semibold mt-5 tracking-tight leading-7">Step 1: Copy and paste the following code into your<span className="font-normal italic"> components/key-button.tsx</span></p> <div className="w-full rounded-md [&_pre]:my-0 [&_pre]:max-h-[350px] [&_pre]:overflow-auto relative bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 font-sm"> <button onClick={() => { const codeElement = document.getElementById('codeBlock'); const codeToCopy = codeElement ? codeElement.textContent : ''; // @ts-ignore navigator.clipboard.writeText(codeToCopy).then(() => { alert('Code copied to clipboard!'); }); }} className="absolute right-0 top-0 z-10 m-4 flex items-center rounded-lg px-3 py-1 text-white" title="Copy code to clipboard"> {/* <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2"> <path strokeLinecap="round" strokeLinejoin="round" d="M8 5C6.895 5 6 5.895 6 7v10c0 1.105.895 2 2 2h8c1.105 0 2-.895 2-2V7c0-1.105-.895-2-2-2H8zm0 0V3c0-1.105.895-2 2-2h4c1.105 0 2 .895 2 2v2m-6 4h4" /> </svg> */} <CopyIcon className="text-black hover:text-gray-400 active:text-blue-700 h-4 dark:text-white" style={{ backdropFilter: 'blur(20px)' }} /> </button> <pre className="ml-2 py-2 pb-2 pl-2 font-sm min-h-[600px] lg:min-h-[600px] sm:min-h-[300px]"><code id="codeBlock" className="text-left language-js text-sm "> {`"use client" import React from "react" import { Button } from "../ui/button" interface KeyButtonProps { text: string size: string variant: string } function KeyButton({ text, size, variant }: KeyButtonProps) { return ( <div className="flex mx-auto justify-center text-center items-center align-center py-20"> <Button className="group relative inline-flex items-center justify-center rounded-full bg-neutral-950 pl-6 pr-12 font-medium text-neutral-50 transform-gpu transition-transform duration-300 ease-in-out active:translate-y-[1px] before:absolute before:inset-0 before:-z-10 before:block before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent before:animate-shimmer_3s_linear_infinite border-2 border-transparent border-l-neutral-700 border-r-neutral-700 hover:border-transparent hover:border-l-white hover:border-r-white hover:bg-black hover:animate-none" variant={variant} size={size} > <span className="z-10 ">{text}</span> <div className="absolute right-1 inline-flex h-10 w-10 items-center py-1 justify-end rounded-full bg-neutral-700 transition-[width] group-hover:w-[calc(100%-8px)]"> <div className="mr-2 flex items-center justify-center"> <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-neutral-50" style={ { "--svg-animation": "spin-around 2s infinite linear", } as React.CSSProperties } > <path d="M8.14645 3.14645C8.34171 2.95118 8.65829 2.95118 8.85355 3.14645L12.8536 7.14645C13.0488 7.34171 13.0488 7.65829 12.8536 7.85355L8.85355 11.8536C8.65829 12.0488 8.34171 12.0488 8.14645 11.8536C7.95118 11.6583 7.95118 11.3417 8.14645 11.1464L11.2929 8H2.5C2.22386 8 2 7.77614 2 7.5C2 7.22386 2.22386 7 2.5 7H11.2929L8.14645 3.85355C7.95118 3.65829 7.95118 3.34171 8.14645 3.14645Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" ></path> </svg> </div> </div> </Button> </div> ) } export default KeyButton `} </code></pre> </div> </div> <div className="flex flex-col space-y-4 ml-3 lg:ml-4 md:lg-3"> <p className="font-semibold mt-5 tracking-tight leading-7">Step 2: Update the import paths and run this code.</p> <div className="w-full rounded-md [&_pre]:my-0 [&_pre]:max-h-[350px] [&_pre]:overflow-auto relative bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700"> <button onClick={() => { const codeElement = document.getElementById('codeBlock2'); const copycode2 = codeElement ? codeElement.textContent : ''; if (copycode2) { navigator.clipboard.writeText(copycode2).then(() => { alert('Code copied to clipboard!'); }); } }} className="absolute right-0 top-0 z-10 m-4 flex items-center rounded-lg bg-transparent px-3 py-1 text-white" title="Copy code to clipboard"> <CopyIcon className="text-black hover:text-gray-400 active:text-blue-700 h-4 dark:text-white" /> </button> <pre className="ml-2 py-2 pb-2 pl-2 font-sm"><code id="codeBlock2" className="text-left language-js text-sm"> {`"use client" import KeyButton from "@/components/easyui/key-button" import React from "react" function Home() { return ( <div className="flex flex-col mx-auto justify-center text-center items-center align-center py-20"> <KeyButton text="Key Button" size="lg" /> </div> ) } export default Home `} {/* </div> */} </code></pre> </div> </div> {/* <div className="mt-5 px-4 ml-3 lg:ml-1 md:lg-3"> */} {/* <h2 className="text-2xl font-semibold mb-5 tracking-tight leading-7 border-b dark:border-gray-700 pb-2 scroll-m-20">Props</h2> <table className="min-w-full table-auto border-collapse border border-gray-300 dark:border-gray-700"> <thead> <tr className="bg-gray-100 dark:bg-gray-900"> <th className="border border-gray-300 px-4 py-2 dark:border-gray-700">Prop Name</th> <th className="border border-gray-300 px-4 py-2 dark:border-gray-700">Type</th> <th className="border border-gray-300 px-4 py-2 dark:border-gray-700">Description</th> <th className="border border-gray-300 px-4 py-2 dark:border-gray-700">Default Value</th> </tr> </thead> <tbody> <tr> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">id</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">Number</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700"> Unique identifier for each application. </td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">-</td> </tr> <tr> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">name</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">String</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700"> Name of the application. </td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">-</td> </tr> <tr> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">icon</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">String</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700"> URL or path to the application&apos;s icon image. </td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">-</td> </tr> <tr> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">category</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">String</td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700"> Category to which the application belongs. </td> <td className="border border-gray-300 px-4 py-2 dark:border-gray-700">-</td> </tr> </tbody> </table> */} {/* </div> */} </TabsContent> </Tabs> {/* <div className="py-10 ml-3"> <h2 className="font-heading mt-12 scroll-m-20 border-b pb-2 text-2xl font-semibold tracking-tight first:mt-0">Credits</h2> <p className="leading-7 [&:not(:first-child)]:mt-6 tracking tight">Credit to <a href="https://github.com/vaunblu/lab/blob/main/src/app/create-new/page.tsx" className="underline italic font-semibold" target="_blank" rel="noopener noreferrer">@vaunblu</a> for the inspiration behind this component.</p> </div> */} </div> ) } export default KeyButtonComponent
DarkInventor/easy-ui/app/(docs)/key-button-component/page.tsx
{ "file_path": "DarkInventor/easy-ui/app/(docs)/key-button-component/page.tsx", "repo_id": "DarkInventor/easy-ui", "token_count": 5622 }
0
import { ImageResponse } from 'next/server' import { allPosts } from 'contentlayer/generated' export const size = { width: 1200, height: 630, } export const contentType = 'image/png' export default async function Image({ params }: { params: { slug: string } }) { const post = allPosts.find((post) => post._raw.flattenedPath === params.slug) // @ts-ignore if (!post) return new ImageResponse('Post not found') // @ts-ignore return new ImageResponse( // @ts-ignore ( <div style={{ fontSize: 48, background: 'white', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', }} > {post.title} </div> ), { ...size } ) }
DarkInventor/easy-ui/app/posts/[slug]/opengraph-image.tsx
{ "file_path": "DarkInventor/easy-ui/app/posts/[slug]/opengraph-image.tsx", "repo_id": "DarkInventor/easy-ui", "token_count": 341 }
1
"use client" import React from "react" import { Button } from "@/components/ui/button" interface KeyButtonProps { text: string size: any variant: any } function KeyButton({ text, size, variant }: KeyButtonProps) { return ( <div className="flex mx-auto justify-center text-center items-center align-center py-20"> <Button className="group relative inline-flex items-center justify-center rounded-full bg-neutral-950 pl-6 pr-12 font-medium text-neutral-50 transform-gpu transition-transform duration-300 ease-in-out active:translate-y-[1px] before:absolute before:inset-0 before:-z-10 before:block before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent before:animate-shimmer_3s_linear_infinite border-2 border-transparent border-l-neutral-700 border-r-neutral-700 hover:border-transparent hover:border-l-white hover:border-r-white hover:bg-black hover:animate-none" variant={variant} size={size} > <span className="z-10 ">{text}</span> <div className="absolute right-1 inline-flex h-10 w-10 items-center py-1 justify-end rounded-full bg-neutral-700 transition-[width] group-hover:w-[calc(100%-8px)]"> <div className="mr-2 flex items-center justify-center"> <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-neutral-50" style={ { "--svg-animation": "spin-around 2s infinite linear", } as React.CSSProperties } > <path d="M8.14645 3.14645C8.34171 2.95118 8.65829 2.95118 8.85355 3.14645L12.8536 7.14645C13.0488 7.34171 13.0488 7.65829 12.8536 7.85355L8.85355 11.8536C8.65829 12.0488 8.34171 12.0488 8.14645 11.8536C7.95118 11.6583 7.95118 11.3417 8.14645 11.1464L11.2929 8H2.5C2.22386 8 2 7.77614 2 7.5C2 7.22386 2.22386 7 2.5 7H11.2929L8.14645 3.85355C7.95118 3.65829 7.95118 3.34171 8.14645 3.14645Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" ></path> </svg> </div> </div> </Button> </div> ) } export default KeyButton
DarkInventor/easy-ui/components/easyui/key-button.tsx
{ "file_path": "DarkInventor/easy-ui/components/easyui/key-button.tsx", "repo_id": "DarkInventor/easy-ui", "token_count": 1114 }
2
import { cn } from "@/lib/utils"; export default function OrbitingCircles({ className, children, reverse, duration = 20, delay = 10, radius = 50, path = true, }: { className?: string; children?: React.ReactNode; reverse?: boolean; duration?: number; delay?: number; radius?: number; path?: boolean; }) { return ( <> {path && ( <svg xmlns="http://www.w3.org/2000/svg" version="1.1" className="pointer-events-none absolute inset-0 h-full w-full" > <circle className="stroke-black/10 stroke-1 dark:stroke-white/10" cx="50%" cy="50%" r={radius} fill="none" strokeDasharray={"4 4"} /> </svg> )} <div style={ { "--duration": duration, "--radius": radius, "--delay": -delay, } as React.CSSProperties } className={cn( "absolute flex h-full w-full transform-gpu animate-orbit items-center justify-center rounded-full border bg-black/10 [animation-delay:calc(var(--delay)*1000ms)] dark:bg-white/10", { "[animation-direction:reverse]": reverse }, className, )} > {children} </div> </> ); }
DarkInventor/easy-ui/components/magicui/orbiting-circles.tsx
{ "file_path": "DarkInventor/easy-ui/components/magicui/orbiting-circles.tsx", "repo_id": "DarkInventor/easy-ui", "token_count": 657 }
3
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 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", icon: "h-10 w-10", }, }, 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 }
DarkInventor/easy-ui/components/ui/button.tsx
{ "file_path": "DarkInventor/easy-ui/components/ui/button.tsx", "repo_id": "DarkInventor/easy-ui", "token_count": 718 }
4
export function estimateReadingTime(text: string): number { const wordsPerMinute = 200; const numberOfWords = text.split(/\s/g).length; return Math.ceil(numberOfWords / wordsPerMinute); }
DarkInventor/easy-ui/lib/blog-utils.ts
{ "file_path": "DarkInventor/easy-ui/lib/blog-utils.ts", "repo_id": "DarkInventor/easy-ui", "token_count": 67 }
5
"use client"; import { navConfig } from "@/config/nav"; import { usePathname } from "next/navigation"; import { cn } from "@/lib/utils"; import Link from "next/link"; export function MainNav() { const pathname = usePathname(); return ( <section className="hidden gap-6 sm:flex sm:items-center"> <nav className="flex items-center gap-2"> <ul className="flex items-center gap-5"> {navConfig.items.map((item) => ( <li key={item.label}> <Link href={item.href} className={cn( " text-sm text-muted-foreground hover:text-foreground/80", { "text-foreground": pathname === item.href, }, item.disabled && "pointer-events-none opacity-60", )} > {item.label} </Link> </li> ))} </ul> </nav> </section> ); }
alifarooq9/rapidlaunch/apps/www/src/app/(app)/_components/main-nav.tsx
{ "file_path": "alifarooq9/rapidlaunch/apps/www/src/app/(app)/_components/main-nav.tsx", "repo_id": "alifarooq9/rapidlaunch", "token_count": 880 }
6
import * as React from "react"; import { cn } from "@/lib/utils"; export type InputProps = React.InputHTMLAttributes<HTMLInputElement>; const Input = React.forwardRef<HTMLInputElement, InputProps>( ({ className, type, ...props }, ref) => { return ( <input type={type} className={cn( "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", className, )} ref={ref} {...props} /> ); }, ); Input.displayName = "Input"; export { Input };
alifarooq9/rapidlaunch/apps/www/src/components/ui/input.tsx
{ "file_path": "alifarooq9/rapidlaunch/apps/www/src/components/ui/input.tsx", "repo_id": "alifarooq9/rapidlaunch", "token_count": 399 }
7
"use client"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { removeUserFeedbackMutation } from "@/server/actions/feedback/mutations"; import { useMutation } from "@tanstack/react-query"; import { MoreVerticalIcon } from "lucide-react"; import { toast } from "sonner"; import { type feedbackSelectSchema } from "@/server/db/schema"; import type { z } from "zod"; import { useRouter } from "next/navigation"; type FeedbackDropdownProps = z.infer<typeof feedbackSelectSchema>; export function FeedbackDropdown(props: FeedbackDropdownProps) { const router = useRouter(); const { mutateAsync: removeFeedbackMutate, isPending: isRemoveFeedbackPending, } = useMutation({ mutationFn: () => removeUserFeedbackMutation({ id: props.id }), onSettled: () => { router.refresh(); }, }); const handleRemoveFeedback = async () => { toast.promise(async () => removeFeedbackMutate(), { loading: "Removing feedback...", success: "Feedback removed successfully", error: "Failed to remove feedback", }); }; return ( <DropdownMenu modal={false}> <DropdownMenuTrigger asChild> <Button variant="ghost" className="absolute right-3 top-3 h-8 w-8 p-0" > <span className="sr-only">Open menu</span> <MoreVerticalIcon className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="w-screen max-w-[12rem]"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuSeparator /> <DropdownMenuItem disabled={isRemoveFeedbackPending} onClick={handleRemoveFeedback} className="text-red-600" > Remove </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ); }
alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/feedback/_components/feedback-dropdown.tsx
{ "file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/feedback/_components/feedback-dropdown.tsx", "repo_id": "alifarooq9/rapidlaunch", "token_count": 1039 }
8
"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 MembersData } from "./columns"; import { membersToOrganizationsRoleEnum } from "@/server/db/schema"; import { useDataTable } from "@/hooks/use-data-table"; import type { DataTableFilterableColumn, DataTableSearchableColumn, } from "@/types/data-table"; import { type getPaginatedOrgMembersQuery } from "@/server/actions/organization/queries"; /** @learn more about data-table at shadcn ui website @see https://ui.shadcn.com/docs/components/data-table */ const filterableColumns: DataTableFilterableColumn<MembersData>[] = [ { id: "role", title: "Role", options: membersToOrganizationsRoleEnum.enumValues.map((v) => ({ label: v, value: v, })), }, ]; type MembersTableProps = { membersPromise: ReturnType<typeof getPaginatedOrgMembersQuery>; }; const searchableColumns: DataTableSearchableColumn<MembersData>[] = [ { id: "email", placeholder: "Search email..." }, ]; export function MembersTable({ membersPromise }: MembersTableProps) { const { data, pageCount, total } = React.use(membersPromise); const columns = useMemo<ColumnDef<MembersData, unknown>[]>( () => getColumns(), [], ); const membersData: MembersData[] = data.map((member) => { return { id: member.id!, role: member.role, createdAt: member.createdAt, email: member.member.email, name: member.member.name, memberId: member.memberId, }; }); const { table } = useDataTable({ data: membersData, columns, pageCount, searchableColumns, filterableColumns, }); return ( <> <DataTable table={table} columns={columns} filterableColumns={filterableColumns} searchableColumns={searchableColumns} totalRows={total} /> </> ); }
alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/members/_components/members-table.tsx
{ "file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/members/_components/members-table.tsx", "repo_id": "alifarooq9/rapidlaunch", "token_count": 914 }
9
"use client"; import { Button } from "@/components/ui/button"; import { Card, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { cn } from "@/lib/utils"; import { useTheme } from "next-themes"; import Image from "next/image"; export function UserAppearanceForm() { const { themes, theme, setTheme } = useTheme(); return ( <Dialog> <Card> <CardHeader> <CardTitle>Appearance</CardTitle> <CardDescription> Customize your app appearance </CardDescription> </CardHeader> <CardFooter> <DialogTrigger asChild> <Button className="gap-2"> <span>Personalize</span> </Button> </DialogTrigger> </CardFooter> </Card> <DialogContent> <DialogHeader> <DialogTitle>Personalize your app appearance</DialogTitle> <DialogDescription> Choose your app theme, color, and more </DialogDescription> </DialogHeader> <div className="flex flex-wrap items-center gap-4"> {themes.map((t) => ( <button onClick={() => setTheme(t)} key={t} className={cn( "relative h-32 w-32 overflow-hidden rounded-md border-2 border-border", t === theme && "outline outline-2 outline-offset-2 outline-primary", )} > <Image src={`/${t}.png`} alt={t} fill /> <span className="absolute bottom-0 left-0 right-0 bg-background bg-opacity-50 p-2 text-center text-sm font-medium capitalize text-foreground "> {t} </span> </button> ))} </div> </DialogContent> </Dialog> ); }
alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/profile/settings/_components/user-appearance-form.tsx
{ "file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/profile/settings/_components/user-appearance-form.tsx", "repo_id": "alifarooq9/rapidlaunch", "token_count": 1419 }
10