UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.
feat: added code comparison component (#347)
Arghya Dasdff8cf4e2a01
diff --git a/__registry__/index.tsx b/__registry__/index.tsxindex 8bbddec7..f1e3d229 100644--- a/__registry__/index.tsx+++ b/__registry__/index.tsx@@ -96,6 +96,19 @@ export const Index: Record<string, any> = {subcategory: "undefined",chunks: [],},+ "code-comparison": {+ name: "code-comparison",+ type: "registry:ui",+ registryDependencies: undefined,+ files: ["registry/default/magicui/code-comparison.tsx"],+ component: React.lazy(+ () => import("@/registry/default/magicui/code-comparison.tsx"),+ ),+ source: "",+ category: "undefined",+ subcategory: "undefined",+ chunks: [],+ },marquee: {name: "marquee",type: "registry:ui",@@ -862,6 +875,19 @@ export const Index: Record<string, any> = {subcategory: "undefined",chunks: [],},+ "code-comparison-demo": {+ name: "code-comparison-demo",+ type: "registry:example",+ registryDependencies: undefined,+ files: ["registry/default/example/code-comparison-demo.tsx"],+ component: React.lazy(+ () => import("@/registry/default/example/code-comparison-demo.tsx"),+ ),+ source: "",+ category: "undefined",+ subcategory: "undefined",+ chunks: [],+ },"marquee-demo": {name: "marquee-demo",type: "registry:example",diff --git a/config/docs.ts b/config/docs.tsindex f02e9aee..51848053 100644--- a/config/docs.ts+++ b/config/docs.ts@@ -187,6 +187,12 @@ export const docsConfig: DocsConfig = {items: [],label: "",},+ {+ title: "Code Comparison",+ href: `/docs/components/code-comparison`,+ items: [],+ label: "New",+ },],},{diff --git a/content/docs/components/code-comparison.mdx b/content/docs/components/code-comparison.mdxnew file mode 100644index 00000000..95cb659a--- /dev/null+++ b/content/docs/components/code-comparison.mdx@@ -0,0 +1,51 @@+---+title: Code Comparison+date: 2024-10-02+description: A component which compares two code snippets.+author: dillionverma+published: true+---++<ComponentPreview name="code-comparison-demo" />++## Installation++<Tabs defaultValue="cli">++<TabsList>+ <TabsTrigger value="cli">CLI</TabsTrigger>+ <TabsTrigger value="manual">Manual</TabsTrigger>+</TabsList>+<TabsContent value="cli">++```bash+npx shadcn@latest add "https://magicui.design/r/code-comparison"+```++</TabsContent>++<TabsContent value="manual">++<Steps>++<Step>Copy and paste the following code into your project.</Step>++<ComponentSource name="code-comparison" />++</Steps>++</TabsContent>++</Tabs>++## Props++| Prop | Type | Description | Default |+| ---------- | -------- | ------------------------------------------------------ | -------------- |+| className | `string` | The class name to be applied to the component | |+| beforeCode | `string` | The code snippet to display in the "before" section | |+| afterCode | `string` | The code snippet to display in the "after" section | |+| language | `string` | The language of the code snippets (e.g., "typescript") | |+| filename | `string` | The filename to display for the code snippets | |+| lightTheme | `string` | The theme to use for light mode | "github-light" |+| darkTheme | `string` | The theme to use for dark mode | "github-dark" |diff --git a/public/r/index.json b/public/r/index.jsonindex b17d8bff..0ff58d7b 100644--- a/public/r/index.json+++ b/public/r/index.json@@ -99,6 +99,16 @@}]},+ {+ "name": "code-comparison",+ "type": "registry:ui",+ "files": [+ {+ "path": "magicui/code-comparison.tsx",+ "type": "registry:ui"+ }+ ]+ },{"name": "marquee","type": "registry:ui",diff --git a/public/r/styles/default/code-comparison.json b/public/r/styles/default/code-comparison.jsonnew file mode 100644index 00000000..b51269ac--- /dev/null+++ b/public/r/styles/default/code-comparison.json@@ -0,0 +1,12 @@+{+ "name": "code-comparison",+ "type": "registry:ui",+ "files": [+ {+ "path": "magicui/code-comparison.tsx",+ "content": "\"use client\";\n\nimport React, { useState, useEffect } from \"react\";\nimport { codeToHtml } from \"shiki\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { useTheme } from \"next-themes\";\n\ninterface CodeComparisonProps {\n beforeCode: string;\n afterCode: string;\n language: string;\n filename: string;\n lightTheme: string;\n darkTheme: string;\n}\n\nexport default function CodeComparison({\n beforeCode,\n afterCode,\n language,\n filename,\n lightTheme,\n darkTheme,\n}: CodeComparisonProps) {\n const { theme, systemTheme } = useTheme();\n const [highlightedBefore, setHighlightedBefore] = useState(\"\");\n const [highlightedAfter, setHighlightedAfter] = useState(\"\");\n\n useEffect(() => {\n const currentTheme = theme === \"system\" ? systemTheme : theme;\n const selectedTheme = currentTheme === \"dark\" ? darkTheme : lightTheme;\n\n async function highlightCode() {\n const before = await codeToHtml(beforeCode, {\n lang: language,\n theme: selectedTheme,\n });\n const after = await codeToHtml(afterCode, {\n lang: language,\n theme: selectedTheme,\n });\n setHighlightedBefore(before);\n setHighlightedAfter(after);\n }\n\n highlightCode();\n }, [\n theme,\n systemTheme,\n beforeCode,\n afterCode,\n language,\n lightTheme,\n darkTheme,\n ]);\n\n const renderCode = (code: string, highlighted: string) => {\n if (highlighted) {\n return (\n <div\n className=\"h-full font-mono text-sm [&>pre]:h-full [&>pre]:bg-[#1e1e1e] [&>pre]:p-4 [&_code]:whitespace-pre-wrap [&_code]:break-all\"\n dangerouslySetInnerHTML={{ __html: highlighted }}\n />\n );\n } else {\n return (\n <pre className=\"h-full whitespace-pre-wrap break-all bg-background p-4 font-mono text-sm text-foreground\">\n {code}\n </pre>\n );\n }\n };\n\n return (\n <div className=\"mx-auto w-full max-w-5xl\">\n <Card className=\"w-full\">\n <CardContent className=\"h-full p-0\">\n <div className=\"relative grid h-full overflow-hidden rounded-md md:grid-cols-2\">\n <div className=\"h-full border-r border-neutral-200 dark:border-neutral-800\">\n <div className=\"flex items-center bg-[#1e1e1e] p-2 font-mono text-sm text-white\">\n <svg\n className=\"mr-2 h-4 w-4\"\n fill=\"currentColor\"\n viewBox=\"0 0 24 24\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M3 3h18v18H3V3zm16 16V5H5v14h14zM7 7h4v4H7V7zm6 0h4v4h-4V7zm-6 6h4v4H7v-4zm6 0h4v4h-4v-4z\" />\n </svg>\n {filename}\n <span className=\"ml-auto\">before</span>\n </div>\n {renderCode(beforeCode, highlightedBefore)}\n </div>\n <div className=\"h-full\">\n <div className=\"flex items-center bg-[#1e1e1e] p-2 font-mono text-sm text-white\">\n <svg\n className=\"mr-2 h-4 w-4\"\n fill=\"currentColor\"\n viewBox=\"0 0 24 24\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M3 3h18v18H3V3zm16 16V5H5v14h14zM7 7h4v4H7V7zm6 0h4v4h-4V7zm-6 6h4v4H7v-4zm6 0h4v4h-4v-4z\" />\n </svg>\n {filename}\n <span className=\"ml-auto\">after</span>\n </div>\n {renderCode(afterCode, highlightedAfter)}\n </div>\n <div className=\"absolute left-1/2 top-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-md bg-neutral-700 text-sm text-white\">\n VS\n </div>\n </div>\n </CardContent>\n </Card>\n </div>\n );\n}\n",+ "type": "registry:ui",+ "target": ""+ }+ ]+}\ No newline at end of filediff --git a/registry/default/example/code-comparison-demo.tsx b/registry/default/example/code-comparison-demo.tsxnew file mode 100644index 00000000..fa39600a--- /dev/null+++ b/registry/default/example/code-comparison-demo.tsx@@ -0,0 +1,66 @@+import CodeComparison from "@/registry/default/magicui/code-comparison";++const beforeCode = `import { NextRequest } from 'next/server';++export const middleware = async (req: NextRequest) => {+ let user = undefined;+ let team = undefined;+ const token = req.headers.get('token');++ if(req.nextUrl.pathname.startsWith('/auth')) {+ user = await getUserByToken(token);++ if(!user) {+ return NextResponse.redirect('/login');+ }+ }++ if(req.nextUrl.pathname.startsWith('/team')) {+ user = await getUserByToken(token);++ if(!user) {+ return NextResponse.redirect('/login');+ }++ const slug = req.nextUrl.query.slug;+ team = await getTeamBySlug(slug);++ if(!team) {+ return NextResponse.redirect('/');+ }+ }++ return NextResponse.next();+}++export const config = {+ matcher: ['/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'],+};`;++const afterCode = `import { createMiddleware, type MiddlewareFunctionProps } from '@app/(auth)/auth/_middleware';+import { auth } from '@app/(auth)/auth/_middleware';+import { team } from '@app/(team)/team/_middleware';++const middlewares = {+ '/auth{/:path?}': auth,+ '/team{/:slug?}': [ auth, team ],+};++export const middleware = createMiddleware(middlewares);++export const config = {+ matcher: ['/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'],+};`;++export default function CodeComparisonDemo() {+ return (+ <CodeComparison+ beforeCode={beforeCode}+ afterCode={afterCode}+ language="typescript"+ filename="middleware.ts"+ lightTheme="github-light"+ darkTheme="github-dark"+ />+ );+}diff --git a/registry/default/magicui/code-comparison.tsx b/registry/default/magicui/code-comparison.tsxnew file mode 100644index 00000000..ac9076dd--- /dev/null+++ b/registry/default/magicui/code-comparison.tsx@@ -0,0 +1,100 @@+"use client";++import { FileIcon } from "lucide-react";+import { useTheme } from "next-themes";+import { useEffect, useState } from "react";+import { codeToHtml } from "shiki";++interface CodeComparisonProps {+ beforeCode: string;+ afterCode: string;+ language: string;+ filename: string;+ lightTheme: string;+ darkTheme: string;+}++export default function CodeComparison({+ beforeCode,+ afterCode,+ language,+ filename,+ lightTheme,+ darkTheme,+}: CodeComparisonProps) {+ const { theme, systemTheme } = useTheme();+ const [highlightedBefore, setHighlightedBefore] = useState("");+ const [highlightedAfter, setHighlightedAfter] = useState("");++ useEffect(() => {+ const currentTheme = theme === "system" ? systemTheme : theme;+ const selectedTheme = currentTheme === "dark" ? darkTheme : lightTheme;++ async function highlightCode() {+ const before = await codeToHtml(beforeCode, {+ lang: language,+ theme: selectedTheme,+ });+ const after = await codeToHtml(afterCode, {+ lang: language,+ theme: selectedTheme,+ });+ setHighlightedBefore(before);+ setHighlightedAfter(after);+ }++ highlightCode();+ }, [+ theme,+ systemTheme,+ beforeCode,+ afterCode,+ language,+ lightTheme,+ darkTheme,+ ]);++ const renderCode = (code: string, highlighted: string) => {+ if (highlighted) {+ return (+ <div+ className="h-full overflow-auto bg-background font-mono text-xs [&>pre]:h-full [&>pre]:!bg-transparent [&>pre]:p-4 [&_code]:break-all"+ dangerouslySetInnerHTML={{ __html: highlighted }}+ />+ );+ } else {+ return (+ <pre className="h-full overflow-auto break-all bg-background p-4 font-mono text-xs text-foreground">+ {code}+ </pre>+ );+ }+ };+ return (+ <div className="mx-auto w-full max-w-5xl">+ <div className="relative w-full overflow-hidden rounded-xl border border-border">+ <div className="relative grid md:grid-cols-2 md:divide-x md:divide-border">+ <div>+ <div className="flex items-center bg-accent p-2 text-sm text-foreground">+ <FileIcon className="mr-2 h-4 w-4" />+ {filename}+ <span className="ml-auto">before</span>+ </div>+ {renderCode(beforeCode, highlightedBefore)}+ </div>+ <div>+ <div className="flex items-center bg-accent p-2 text-sm text-foreground">+ <FileIcon className="mr-2 h-4 w-4" />+ {filename}+ <span className="ml-auto">after</span>+ </div>+ {renderCode(afterCode, highlightedAfter)}+ </div>+ </div>+ <div className="absolute left-1/2 top-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-md bg-accent text-xs text-foreground">+ VS+ </div>+ </div>+ </div>+ );+}diff --git a/registry/registry-examples.ts b/registry/registry-examples.tsindex a616ebe2..76ef554a 100644--- a/registry/registry-examples.ts+++ b/registry/registry-examples.ts@@ -68,6 +68,11 @@ export const examples: Registry = [type: "registry:example",files: ["example/hero-video-dialog-demo-top-in-bottom-out.tsx"],},+ {+ name: "code-comparison-demo",+ type: "registry:example",+ files: ["example/code-comparison-demo.tsx"],+ },{name: "marquee-demo",type: "registry:example",diff --git a/registry/registry-ui.ts b/registry/registry-ui.tsindex 2066f83f..62f65263 100644--- a/registry/registry-ui.ts+++ b/registry/registry-ui.ts@@ -57,6 +57,12 @@ export const ui: Registry = [dependencies: ["framer-motion"],files: ["magicui/hero-video-dialog.tsx"],},+ {+ name: "code-comparison",+ type: "registry:ui",+ dependencies: ["shiki", "next-themes"],+ files: ["magicui/code-comparison.tsx"],+ },{name: "marquee",type: "registry:ui",