text
stringlengths 21
253k
| id
stringlengths 25
123
| metadata
dict | __index_level_0__
int64 0
181
|
---|---|---|---|
import { GitHubLogoIcon, TwitterLogoIcon } from '@radix-ui/react-icons';
import { useTranslations } from 'next-intl';
import { buttonVariants } from '@/components/ui/buttonVariants';
import { CenteredHero } from '@/features/landing/CenteredHero';
import { Section } from '@/features/landing/Section';
export const Hero = () => {
const t = useTranslations('Hero');
return (
<Section className="py-36">
<CenteredHero
banner={{
href: 'https://twitter.com/ixartz',
text: (
<>
<TwitterLogoIcon className="mr-1 size-5" />
{' '}
{t('follow_twitter')}
</>
),
}}
title={t.rich('title', {
important: chunks => (
<span className="bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 bg-clip-text text-transparent">
{chunks}
</span>
),
})}
description={t('description')}
buttons={(
<>
<a
className={buttonVariants({ size: 'lg' })}
href="https://github.com/ixartz/SaaS-Boilerplate"
>
{t('primary_button')}
</a>
<a
className={buttonVariants({ variant: 'outline', size: 'lg' })}
href="https://github.com/ixartz/SaaS-Boilerplate"
>
<GitHubLogoIcon className="mr-2 size-5" />
{t('secondary_button')}
</a>
</>
)}
/>
</Section>
);
};
| ixartz/SaaS-Boilerplate/src/templates/Hero.tsx | {
"file_path": "ixartz/SaaS-Boilerplate/src/templates/Hero.tsx",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 815
} | 32 |
import { eventHandler, setResponseHeader, defaultContentType } from 'h3';
import { renderToString } from 'react-dom/server';
import { createElement } from 'react';
import SvgPreview from '../../../lib/SvgPreview/index.tsx';
import createLucideIcon, { IconNode } from 'lucide-react/src/createLucideIcon';
import { parseSync } from 'svgson';
export default eventHandler((event) => {
const { params } = event.context;
const [strokeWidth, svgData] = params.data.split('/');
const data = svgData.slice(0, -4);
const src = Buffer.from(data, 'base64').toString('utf8');
const Icon = createLucideIcon(
'icon',
parseSync(src.includes('<svg') ? src : `<svg>${src}</svg>`).children.map(
({ name, attributes }) => [name, attributes],
) as IconNode,
);
const svg = Buffer.from(
// We can't use jsx here, is not supported here by nitro.
renderToString(createElement(Icon, { strokeWidth }))
.replace(/fill\="none"/, 'fill="#fff"')
.replace(
/>/,
`><style>
@media screen and (prefers-color-scheme: light) {
svg { fill: transparent !important; }
}
@media screen and (prefers-color-scheme: dark) {
svg { stroke: #fff; fill: transparent !important; }
}
</style>`,
),
).toString('utf8');
defaultContentType(event, 'image/svg+xml');
setResponseHeader(event, 'Cache-Control', 'public,max-age=31536000');
return svg;
});
| lucide-icons/lucide/docs/.vitepress/api/gh-icon/stroke-width/[...data].get.ts | {
"file_path": "lucide-icons/lucide/docs/.vitepress/api/gh-icon/stroke-width/[...data].get.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 553
} | 33 |
import { INode, parseSync } from 'svgson';
import toPath from 'element-to-path';
import { SVGPathData, encodeSVGPath } from 'svg-pathdata';
import { Path, Point } from './types';
function assertNever(x: never): never {
throw new Error('Unknown type: ' + x['type']);
}
export function assert(value: unknown): asserts value {
if (value === undefined) {
throw new Error('value must be defined');
}
}
const convertToPathNode = (node: INode): { d: string; name: typeof node.name } => {
if (node.name === 'path') {
return { d: node.attributes.d, name: node.name };
}
if (node.name === 'circle') {
const cx = parseFloat(node.attributes.cx);
const cy = parseFloat(node.attributes.cy);
const r = parseFloat(node.attributes.r);
return {
d: [
`M ${cx} ${cy - r}`,
`a ${r} ${r} 0 0 1 ${r} ${r}`,
`a ${r} ${r} 0 0 1 ${0 - r} ${r}`,
`a ${r} ${r} 0 0 1 ${0 - r} ${0 - r}`,
`a ${r} ${r} 0 0 1 ${r} ${0 - r}`,
].join(''),
name: node.name,
};
}
return { d: toPath(node).replace(/z$/i, ''), name: node.name };
};
const extractNodes = (node: INode): INode[] => {
if (['rect', 'circle', 'ellipse', 'polygon', 'polyline', 'line', 'path'].includes(node.name)) {
return [node];
} else if (node.children && Array.isArray(node.children)) {
return node.children.flatMap(extractNodes);
}
return [];
};
export const getNodes = (src: string) =>
extractNodes(parseSync(src.includes('<svg') ? src : `<svg>${src}</svg>`));
export const getCommands = (src: string) =>
getNodes(src)
.map(convertToPathNode)
.flatMap(({ d, name }, idx) =>
new SVGPathData(d).toAbs().commands.map((c, cIdx) => ({ ...c, id: idx, idx: cIdx, name })),
);
export const getPaths = (src: string) => {
const commands = getCommands(src.includes('<svg') ? src : `<svg>${src}</svg>`);
const paths: Path[] = [];
let prev: Point | undefined = undefined;
let start: Point | undefined = undefined;
const addPath = (
c: (typeof commands)[number],
next: Point,
d?: string,
extras?: { circle?: Path['circle']; cp1?: Path['cp1']; cp2?: Path['cp2'] },
) => {
assert(prev);
paths.push({
c,
d: d || `M ${prev.x} ${prev.y} L ${next.x} ${next.y}`,
prev,
next,
...extras,
isStart: start === prev,
});
prev = next;
};
let prevCP: Point | undefined = undefined;
for (let i = 0; i < commands.length; i++) {
const previousCommand = commands[i - 1];
const c = commands[i];
switch (c.type) {
case SVGPathData.MOVE_TO: {
prev = c;
start = c;
break;
}
case SVGPathData.LINE_TO: {
assert(prev);
addPath(c, c);
break;
}
case SVGPathData.HORIZ_LINE_TO: {
assert(prev);
addPath(c, { x: c.x, y: prev.y });
break;
}
case SVGPathData.VERT_LINE_TO: {
assert(prev);
addPath(c, { x: prev.x, y: c.y });
break;
}
case SVGPathData.CLOSE_PATH: {
assert(prev);
assert(start);
addPath(c, start);
start = undefined;
break;
}
case SVGPathData.CURVE_TO: {
assert(prev);
addPath(c, c, `M ${prev.x} ${prev.y} ${encodeSVGPath(c)}`, {
cp1: { x: c.x1, y: c.y1 },
cp2: { x: c.x2, y: c.y2 },
});
break;
}
case SVGPathData.SMOOTH_CURVE_TO: {
assert(prev);
assert(previousCommand);
const reflectedCp1 = {
x:
previousCommand &&
(previousCommand.type === SVGPathData.SMOOTH_CURVE_TO ||
previousCommand.type === SVGPathData.CURVE_TO)
? previousCommand.relative
? previousCommand.x2 - previousCommand.x
: previousCommand.x2 - prev.x
: 0,
y:
previousCommand &&
(previousCommand.type === SVGPathData.SMOOTH_CURVE_TO ||
previousCommand.type === SVGPathData.CURVE_TO)
? previousCommand.relative
? previousCommand.y2 - previousCommand.y
: previousCommand.y2 - prev.y
: 0,
};
addPath(
c,
c,
`M ${prev.x} ${prev.y} ${encodeSVGPath({
type: SVGPathData.CURVE_TO,
relative: false,
x: c.x,
y: c.y,
x1: prev.x - reflectedCp1.x,
y1: prev.y - reflectedCp1.y,
x2: c.x2,
y2: c.y2,
})}`,
{
cp1: { x: prev.x - reflectedCp1.x, y: prev.y - reflectedCp1.y },
cp2: { x: c.x2, y: c.y2 },
},
);
break;
}
case SVGPathData.QUAD_TO: {
assert(prev);
addPath(c, c, `M ${prev.x} ${prev.y} ${encodeSVGPath(c)}`, {
cp1: { x: c.x1, y: c.y1 },
cp2: { x: c.x1, y: c.y1 },
});
break;
}
case SVGPathData.SMOOTH_QUAD_TO: {
assert(prev);
const backTrackCP = (
index: number,
currentPoint: { x: number; y: number },
): { x: number; y: number } => {
const previousCommand = commands[index - 1];
if (!previousCommand) {
return currentPoint;
}
if (previousCommand.type === SVGPathData.QUAD_TO) {
return {
x: previousCommand.relative
? currentPoint.x - (previousCommand.x1 - previousCommand.x)
: currentPoint.x - (previousCommand.x1 - currentPoint.x),
y: previousCommand.relative
? currentPoint.y - (previousCommand.y1 - previousCommand.y)
: currentPoint.y - (previousCommand.y1 - currentPoint.y),
};
}
if (previousCommand.type === SVGPathData.SMOOTH_QUAD_TO) {
if (!prevCP) {
return currentPoint;
}
return {
x: currentPoint.x - (prevCP.x - currentPoint.x),
y: currentPoint.y - (prevCP.y - currentPoint.y),
};
}
return currentPoint;
};
prevCP = backTrackCP(i, prev);
addPath(
c,
c,
`M ${prev.x} ${prev.y} ${encodeSVGPath({
type: SVGPathData.QUAD_TO,
relative: false,
x: c.x,
y: c.y,
x1: prevCP.x,
y1: prevCP.y,
})}`,
{
cp1: { x: prevCP.x, y: prevCP.y },
cp2: { x: prevCP.x, y: prevCP.y },
},
);
break;
}
case SVGPathData.ARC: {
assert(prev);
const center = arcEllipseCenter(
prev.x,
prev.y,
c.rX,
c.rY,
c.xRot,
c.lArcFlag,
c.sweepFlag,
c.x,
c.y,
);
addPath(
c,
c,
`M ${prev.x} ${prev.y} A${c.rX} ${c.rY} ${c.xRot} ${c.lArcFlag} ${c.sweepFlag} ${c.x} ${c.y}`,
{ circle: c.rX === c.rY ? { ...center, r: c.rX } : undefined },
);
break;
}
default: {
assertNever(c);
}
}
}
return paths;
};
export const arcEllipseCenter = (
x1: number,
y1: number,
rx: number,
ry: number,
a: number,
fa: number,
fs: number,
x2: number,
y2: number,
) => {
const phi = (a * Math.PI) / 180;
const M = [
[Math.cos(phi), Math.sin(phi)],
[-Math.sin(phi), Math.cos(phi)],
];
const V = [(x1 - x2) / 2, (y1 - y2) / 2];
const [x1p, y1p] = [M[0][0] * V[0] + M[0][1] * V[1], M[1][0] * V[0] + M[1][1] * V[1]];
rx = Math.abs(rx);
ry = Math.abs(ry);
const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
if (lambda > 1) {
rx = Math.sqrt(lambda) * rx;
ry = Math.sqrt(lambda) * ry;
}
const sign = fa === fs ? -1 : 1;
const co =
sign *
Math.sqrt(
Math.max(rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p, 0) /
(rx * rx * y1p * y1p + ry * ry * x1p * x1p),
);
const V2 = [(rx * y1p) / ry, (-ry * x1p) / rx];
const Cp = [V2[0] * co, V2[1] * co];
const M2 = [
[Math.cos(phi), -Math.sin(phi)],
[Math.sin(phi), Math.cos(phi)],
];
const V3 = [(x1 + x2) / 2, (y1 + y2) / 2];
const C = [
M2[0][0] * Cp[0] + M2[0][1] * Cp[1] + V3[0],
M2[1][0] * Cp[0] + M2[1][1] * Cp[1] + V3[1],
];
return { x: C[0], y: C[1] };
};
| lucide-icons/lucide/docs/.vitepress/lib/SvgPreview/utils.ts | {
"file_path": "lucide-icons/lucide/docs/.vitepress/lib/SvgPreview/utils.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 4513
} | 34 |
import { ref } from 'vue';
export default function useConfetti() {
const animate = ref(false);
const confettiText = ref('confetti!');
function confetti() {
animate.value = true;
setTimeout(function () {
animate.value = false;
}, 1000);
}
return {
animate,
confetti,
confettiText,
};
}
| lucide-icons/lucide/docs/.vitepress/theme/composables/useConfetti.ts | {
"file_path": "lucide-icons/lucide/docs/.vitepress/theme/composables/useConfetti.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 121
} | 35 |
const allowedAttrs = [
'xmlns',
'width',
'height',
'viewBox',
'fill',
'stroke',
'stroke-width',
'stroke-linecap',
'stroke-linejoin',
'class',
];
export default function getSVGIcon(element?: HTMLElement, attrs?: Record<string, string>) {
const svg = element ?? document.querySelector('#previewer svg');
if (!svg) return;
const clonedSvg = svg.cloneNode(true) as SVGElement;
// Filter out attributes that are not allowed in SVGs
for (const attr of Array.from(clonedSvg.attributes)) {
if (!allowedAttrs.includes(attr.name)) {
clonedSvg.removeAttribute(attr.name);
}
}
for (const [key, value] of Object.entries(attrs ?? {})) {
clonedSvg.setAttribute(key, value);
}
const svgString = new XMLSerializer().serializeToString(clonedSvg);
return svgString;
}
| lucide-icons/lucide/docs/.vitepress/theme/utils/getSVGIcon.ts | {
"file_path": "lucide-icons/lucide/docs/.vitepress/theme/utils/getSVGIcon.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 297
} | 36 |
.my-icon {
/* Icon size will relative to font-size of .text-wrapper */
width: 1em;
height: 1em;
}
.text-wrapper {
/* Change this! */
font-size: 96px;
/* layout stuff */
display: flex;
gap: 0.25em;
align-items: center;
}
| lucide-icons/lucide/docs/guide/basics/examples/size-icon-font-example/icon.css | {
"file_path": "lucide-icons/lucide/docs/guide/basics/examples/size-icon-font-example/icon.css",
"repo_id": "lucide-icons/lucide",
"token_count": 93
} | 37 |
import iconNodes from '../.vitepress/data/iconNodes';
export default {
async load() {
return {
icons: Object.entries(iconNodes).map(([name, iconNode]) => ({ name, iconNode })),
};
},
};
| lucide-icons/lucide/docs/icons/icons.data.ts | {
"file_path": "lucide-icons/lucide/docs/icons/icons.data.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 80
} | 38 |
import copy from 'rollup-plugin-copy';
import replace from '@rollup/plugin-replace';
export default defineNitroConfig({
preset: 'vercel_edge',
srcDir: '.vitepress',
routeRules: {
'/api/**': { cors: false },
},
rollupConfig: {
external: ['@resvg/resvg-wasm/index_bg.wasm', './index_bg.wasm?module'],
plugins: [
copy({
targets: [
{
src: './node_modules/@resvg/resvg-wasm/index_bg.wasm',
dest: './.vercel/output/functions/__nitro.func',
},
],
}),
replace({
include: ['./**/*.ts'],
'/* WASM_IMPORT */': 'import resvg_wasm from "./index_bg.wasm?module";',
delimiters: ['', ''],
preventAssignment: false,
}),
],
},
esbuild: {
options: {
jsxFactory: 'React.createElement',
jsxFragment: 'React.Fragment',
},
},
});
| lucide-icons/lucide/docs/nitro.config.ts | {
"file_path": "lucide-icons/lucide/docs/nitro.config.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 420
} | 39 |
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LucideAngularModule } from './lucide-angular.module';
import { formatFixed, LucideAngularComponent } from './lucide-angular.component';
import defaultAttributes from '../icons/constants/default-attributes';
import { LucideIcons } from '../icons/types';
describe('LucideAngularComponent', () => {
let testHostComponent: TestHostComponent;
let testHostFixture: ComponentFixture<TestHostComponent>;
const getSvgAttribute = (attr: string) =>
testHostFixture.nativeElement.querySelector('svg').getAttribute(attr);
const testIcons: LucideIcons = {
Demo: [['polyline', { points: '1 1 22 22' }]],
};
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [LucideAngularComponent, TestHostComponent],
imports: [LucideAngularModule.pick(testIcons)],
}).compileComponents();
testHostFixture = TestBed.createComponent(TestHostComponent);
testHostComponent = testHostFixture.componentInstance;
});
it('should create', () => {
testHostFixture.detectChanges();
expect(testHostComponent).toBeTruthy();
});
it('should add all classes', () => {
testHostFixture.detectChanges();
expect(getSvgAttribute('class')).toBe('lucide lucide-demo my-icon');
});
it('should set color', () => {
const color = 'red';
testHostComponent.setColor(color);
testHostFixture.detectChanges();
expect(getSvgAttribute('stroke')).toBe(color);
});
it('should set size', () => {
const size = 12;
testHostComponent.setSize(size);
testHostFixture.detectChanges();
expect(getSvgAttribute('width')).toBe(size.toString(10));
});
it('should set stroke width', () => {
const strokeWidth = 1.41;
testHostComponent.setStrokeWidth(strokeWidth);
testHostFixture.detectChanges();
expect(getSvgAttribute('stroke-width')).toBe(strokeWidth.toString(10));
});
it('should adjust stroke width', () => {
const strokeWidth = 2;
const size = 12;
testHostComponent.setStrokeWidth(strokeWidth);
testHostComponent.setSize(12);
testHostComponent.setAbsoluteStrokeWidth(true);
testHostFixture.detectChanges();
expect(getSvgAttribute('stroke-width')).toBe(
formatFixed(strokeWidth / (size / defaultAttributes.height)),
);
});
@Component({
selector: 'lucide-spec-host-component',
template: ` <i-lucide
name="demo"
class="my-icon"
[color]="color"
[size]="size"
[strokeWidth]="strokeWidth"
[absoluteStrokeWidth]="absoluteStrokeWidth"
></i-lucide>`,
})
class TestHostComponent {
color?: string;
size?: number;
strokeWidth?: number;
absoluteStrokeWidth = true;
setColor(color: string): void {
this.color = color;
}
setSize(size: number): void {
this.size = size;
}
setStrokeWidth(strokeWidth: number): void {
this.strokeWidth = strokeWidth;
}
setAbsoluteStrokeWidth(absoluteStrokeWidth: boolean): void {
this.absoluteStrokeWidth = absoluteStrokeWidth;
}
}
});
| lucide-icons/lucide/packages/lucide-angular/src/lib/lucide-angular.component.spec.ts | {
"file_path": "lucide-icons/lucide/packages/lucide-angular/src/lib/lucide-angular.component.spec.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 1125
} | 40 |
import { h, type JSX } from 'preact';
import { mergeClasses, toKebabCase } from '@lucide/shared';
import Icon from './Icon';
import type { IconNode, LucideIcon, LucideProps } from './types';
/**
* Create a Lucide icon component
* @param {string} iconName
* @param {array} iconNode
* @returns {FunctionComponent} LucideIcon
*/
const createLucideIcon = (iconName: string, iconNode: IconNode): LucideIcon => {
const Component = ({ class: classes = '', children, ...props }: LucideProps) =>
h(
Icon,
{
...props,
iconNode,
class: mergeClasses<string | JSX.SignalLike<string | undefined>>(
`lucide-${toKebabCase(iconName)}`,
classes,
),
},
children,
);
Component.displayName = `${iconName}`;
return Component;
};
export default createLucideIcon;
| lucide-icons/lucide/packages/lucide-preact/src/createLucideIcon.ts | {
"file_path": "lucide-icons/lucide/packages/lucide-preact/src/createLucideIcon.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 326
} | 41 |
// https://github.com/FormidableLabs/react-native-svg-mock
import React from 'react';
import type { LucideProps } from '../../src/createReactComponent';
export type { SvgProps } from 'react-native-svg';
const createComponent = function (name: string) {
const component = (props: LucideProps) => {
return React.createElement(name, props, props.children);
};
component.displayName = name;
return component;
};
// Mock all react-native-svg exports
// from https://github.com/magicismight/react-native-svg/blob/master/index.js
const Svg = createComponent('svg');
const Circle = createComponent('circle');
const Ellipse = createComponent('ellipse');
const G = createComponent('g');
const Text = createComponent('text');
const TextPath = createComponent('textPath');
const TSpan = createComponent('tSpan');
const Path = createComponent('path');
const Polygon = createComponent('polygon');
const Polyline = createComponent('polyline');
const Line = createComponent('line');
const Rect = createComponent('rect');
const Use = createComponent('use');
const Image = createComponent('image');
const Symbol = createComponent('symbol');
const Defs = createComponent('defs');
const LinearGradient = createComponent('linearGradient');
const RadialGradient = createComponent('radialGradient');
const Stop = createComponent('stop');
const ClipPath = createComponent('clipPath');
const Pattern = createComponent('pattern');
const Mask = createComponent('mask');
export {
Svg,
Circle,
Ellipse,
G,
Text,
TextPath,
TSpan,
Path,
Polygon,
Polyline,
Line,
Rect,
Use,
Image,
Symbol,
Defs,
LinearGradient,
RadialGradient,
Stop,
ClipPath,
Pattern,
Mask,
};
export default Svg;
| lucide-icons/lucide/packages/lucide-react-native/__mocks__/react-native-svg/index.ts | {
"file_path": "lucide-icons/lucide/packages/lucide-react-native/__mocks__/react-native-svg/index.ts",
"repo_id": "lucide-icons/lucide",
"token_count": 518
} | 42 |
import fs from 'fs';
import path from 'path';
import getArgumentOptions from 'minimist';
import { parseSync } from 'svgson';
import { readSvgDirectory, getCurrentDirPath } from '@lucide/helpers';
import readSvgs from './readSvgs.mjs';
import generateSprite from './generateSprite.mjs';
import generateIconNodes from './generateIconNodes.mjs';
import copyIcons from './copyIcons.mjs';
import pkg from '../package.json' with { type: 'json' };
const cliArguments = getArgumentOptions(process.argv.slice(2));
const createDirectory = (dir) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
};
const currentDir = getCurrentDirPath(import.meta.url);
const PACKAGE_DIR = path.resolve(currentDir, '../');
const ICONS_DIR = path.join(PACKAGE_DIR, '../../icons');
const LIB_DIR = path.join(PACKAGE_DIR, cliArguments.output || 'lib');
const ICON_MODULE_DIR = path.join(LIB_DIR, 'icons');
const license = `@license ${pkg.name} v${pkg.version} - ${pkg.license}`;
createDirectory(LIB_DIR);
createDirectory(ICON_MODULE_DIR);
const svgFiles = readSvgDirectory(ICONS_DIR);
const svgs = readSvgs(svgFiles, ICONS_DIR);
const parsedSvgs = svgs.map(({ name, contents }) => ({
name,
contents,
parsedSvg: parseSync(contents),
}));
generateSprite(parsedSvgs, PACKAGE_DIR, license);
generateIconNodes(parsedSvgs, PACKAGE_DIR);
copyIcons(parsedSvgs, PACKAGE_DIR, license);
| lucide-icons/lucide/packages/lucide-static/scripts/buildLib.mjs | {
"file_path": "lucide-icons/lucide/packages/lucide-static/scripts/buildLib.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 503
} | 43 |
/* 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 createLucideIcon from '../createLucideIcon';
/**
* @component @name ${componentName}
* @description Lucide SVG icon component, renders SVG Element with children.
*
* @preview  - https://lucide.dev/icons/${iconName}
* @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation
*
* @param {Object} props - Lucide icons props and any valid SVG attribute
* @returns {FunctionalComponent} Vue component
* ${deprecated ? `@deprecated ${deprecationReason}` : ''}
*/
const ${componentName} = createLucideIcon('${componentName}Icon', ${JSON.stringify(children)});
export default ${componentName};
`;
};
| lucide-icons/lucide/packages/lucide-vue-next/scripts/exportTemplate.mjs | {
"file_path": "lucide-icons/lucide/packages/lucide-vue-next/scripts/exportTemplate.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 311
} | 44 |
import { join } from 'path';
export default function LucideNuxtPlugin() {
this.nuxt.hook('components:dirs', (dirs) => {
dirs.push({
path: join(__dirname, 'dist', 'esm', 'icons'),
prefix: 'Icon',
ignore: ['**/index.js'],
});
});
}
| lucide-icons/lucide/packages/lucide-vue/nuxt.js | {
"file_path": "lucide-icons/lucide/packages/lucide-vue/nuxt.js",
"repo_id": "lucide-icons/lucide",
"token_count": 112
} | 45 |
const githubApi = async (endpoint) => {
const headers = new Headers();
const username = 'ericfennis';
const password = process.env.GITHUB_API_KEY;
headers.set(
'Authorization',
`Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
);
const res = await fetch(endpoint, {
method: 'GET',
headers,
});
return res.json();
};
export default githubApi;
| lucide-icons/lucide/scripts/githubApi.mjs | {
"file_path": "lucide-icons/lucide/scripts/githubApi.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 141
} | 46 |
/* eslint-disable import/prefer-default-export */
/**
* @param {array} array
* @returns {array}
*/
export const shuffleArray = (array) => {
// eslint-disable-next-line no-plusplus
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};
| lucide-icons/lucide/tools/build-helpers/src/shuffleArray.mjs | {
"file_path": "lucide-icons/lucide/tools/build-helpers/src/shuffleArray.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 139
} | 47 |
import { basename } from 'path';
import { parseSync } from 'svgson';
import { generateHashedKey, readSvg, hasDuplicatedChildren } from '@lucide/helpers';
/**
* Build an object in the format: `{ <name>: <contents> }`.
* @param {string[]} svgFiles - A list of filenames.
* @param {Function} getSvg - A function that returns the contents of an SVG file given a filename.
* @returns {Object}
*/
export default (svgFiles, iconsDirectory, renderUniqueKey = false) =>
svgFiles
.map((svgFile) => {
const name = basename(svgFile, '.svg');
const svg = readSvg(svgFile, iconsDirectory);
const contents = parseSync(svg);
if (!(contents.children && contents.children.length)) {
throw new Error(`${name}.svg has no children!`);
}
if (hasDuplicatedChildren(contents.children)) {
throw new Error(`Duplicated children in ${name}.svg`);
}
if (renderUniqueKey) {
contents.children = contents.children.map((child) => {
child.attributes.key = generateHashedKey(child);
return child;
});
}
return { name, contents };
})
.reduce((icons, icon) => {
icons[icon.name] = icon.contents;
return icons;
}, {});
| lucide-icons/lucide/tools/build-icons/render/renderIconsObject.mjs | {
"file_path": "lucide-icons/lucide/tools/build-icons/render/renderIconsObject.mjs",
"repo_id": "lucide-icons/lucide",
"token_count": 476
} | 48 |
import { type Project } from "@prisma/client";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
import DeleteCard from "./delete-card";
import EditableDetails from "./editable-details";
export default function TabSections({ project }: { project: Project }) {
return (
<Tabs defaultValue="details">
<TabsList>
<TabsTrigger value="details">Details</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
</TabsList>
<TabsContent value="details">
<EditableDetails initialValues={project} />
</TabsContent>
<TabsContent value="settings">
<DeleteCard id={project.id} />
</TabsContent>
</Tabs>
);
}
| moinulmoin/chadnext/src/app/[locale]/dashboard/projects/[projectId]/tab-sections.tsx | {
"file_path": "moinulmoin/chadnext/src/app/[locale]/dashboard/projects/[projectId]/tab-sections.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 267
} | 49 |
import { cookies } from "next/headers";
import { verifyVerificationCode } from "~/actions/auth";
import { lucia } from "~/lib/lucia";
import prisma from "~/lib/prisma";
export const POST = async (req: Request) => {
const body = await req.json();
try {
const user = await prisma.user.findFirst({
where: {
email: body.email,
},
select: {
id: true,
email: true,
emailVerified: true,
},
});
if (!user) {
return new Response(null, {
status: 400,
});
}
const isValid = await verifyVerificationCode(
{ id: user.id, email: body.email },
body.code
);
if (!isValid) {
return new Response(null, {
status: 400,
});
}
await lucia.invalidateUserSessions(user.id);
if (!user.emailVerified) {
await prisma.user.update({
where: {
id: user.id,
},
data: {
emailVerified: true,
},
});
}
const session = await lucia.createSession(user.id, {});
const sessionCookie = lucia.createSessionCookie(session.id);
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
return new Response(null, {
status: 200,
});
} catch (error) {
console.log(error);
return new Response(null, {
status: 500,
});
}
};
| moinulmoin/chadnext/src/app/api/auth/login/verify-otp/route.ts | {
"file_path": "moinulmoin/chadnext/src/app/api/auth/login/verify-otp/route.ts",
"repo_id": "moinulmoin/chadnext",
"token_count": 624
} | 50 |
import Link from "next/link";
import { validateRequest } from "~/actions/auth";
import { getUserSubscriptionPlan } from "~/actions/subscription";
import { cn } from "~/lib/utils";
import { Badge } from "../ui/badge";
import { buttonVariants } from "../ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "../ui/card";
export default async function Pricing() {
const { user } = await validateRequest();
const subscription = user ? await getUserSubscriptionPlan(user.id) : null;
return (
<section>
<div className="container space-y-6 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">Pricing</h2>
<p className="max-w-[85%] text-balance leading-normal text-muted-foreground sm:text-lg sm:leading-7">
Choose the plan thats right for you and start enjoying it all.
</p>
</div>
<div className="flex flex-col justify-center gap-8 md:flex-row">
<Card
className={cn(
"relative w-full transition duration-200 ease-in-out hover:shadow-lg xl:w-[300px]"
)}
>
<CardHeader>
<CardTitle>
Free Plan{" "}
{subscription && !subscription?.isPro && (
<Badge className="absolute right-0 top-0 m-4">Current</Badge>
)}
</CardTitle>
<CardDescription>Up to 3 projects</CardDescription>
</CardHeader>
<CardContent>
<p className="my-6 flex items-baseline justify-center gap-x-2">
<span className="text-5xl font-bold tracking-tight text-primary">
$0
</span>
<span className="text-sm font-semibold leading-6 tracking-wide text-muted-foreground">
/month
</span>
</p>
</CardContent>
<CardFooter className="justify-center">
{!subscription ? (
<Link href="/login" className={buttonVariants()}>
Get Started
</Link>
) : (
""
)}
</CardFooter>
</Card>
<Card
className={cn(
"relative w-full transition duration-200 ease-in-out hover:shadow-lg xl:w-[300px]"
)}
>
<CardHeader>
<CardTitle>
Pro Plan{" "}
{subscription && subscription?.isPro && (
<Badge className="absolute right-0 top-0 m-4">Current</Badge>
)}
</CardTitle>
<CardDescription>Unlimited projects</CardDescription>
</CardHeader>
<CardContent>
<p className="my-6 flex items-baseline justify-center gap-x-2">
<span className="text-5xl font-bold tracking-tight text-primary">
$10
</span>
<span className="text-sm font-semibold leading-6 tracking-wide text-muted-foreground">
/month
</span>
</p>
</CardContent>
<CardFooter className="justify-center">
<Link href="/login" className={buttonVariants()}>
{!subscription
? "Get Started"
: subscription?.isPro
? "Manage Plan"
: "Upgrade Plan"}
</Link>
</CardFooter>
</Card>
</div>
</div>
</section>
);
}
| moinulmoin/chadnext/src/components/sections/pricing.tsx | {
"file_path": "moinulmoin/chadnext/src/components/sections/pricing.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 1926
} | 51 |
"use client";
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { Dot } from "lucide-react";
import { cn } from "~/lib/utils";
const InputOTP = React.forwardRef<
React.ElementRef<typeof OTPInput>,
React.ComponentPropsWithoutRef<typeof OTPInput>
>(({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn(
"flex items-center gap-2 has-[:disabled]:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
));
InputOTP.displayName = "InputOTP";
const InputOTPGroup = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center", className)} {...props} />
));
InputOTPGroup.displayName = "InputOTPGroup";
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index];
return (
<div
ref={ref}
className={cn(
"relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-2 ring-ring ring-offset-background",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
</div>
)}
</div>
);
});
InputOTPSlot.displayName = "InputOTPSlot";
const InputOTPSeparator = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Dot />
</div>
));
InputOTPSeparator.displayName = "InputOTPSeparator";
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
| moinulmoin/chadnext/src/components/ui/input-otp.tsx | {
"file_path": "moinulmoin/chadnext/src/components/ui/input-otp.tsx",
"repo_id": "moinulmoin/chadnext",
"token_count": 844
} | 52 |
"use client";
import { createI18nClient } from "next-international/client";
export const {
useI18n,
useScopedI18n,
I18nProviderClient,
useCurrentLocale,
useChangeLocale,
} = createI18nClient({
en: () => import("./en"),
fr: () => import("./fr"),
});
| moinulmoin/chadnext/src/locales/client.ts | {
"file_path": "moinulmoin/chadnext/src/locales/client.ts",
"repo_id": "moinulmoin/chadnext",
"token_count": 100
} | 53 |
"use client";
import { ChevronsDown, Github, Menu } from "lucide-react";
import React from "react";
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "../ui/sheet";
import { Separator } from "../ui/separator";
import {
NavigationMenu,
NavigationMenuContent,
NavigationMenuItem,
NavigationMenuLink,
NavigationMenuList,
NavigationMenuTrigger,
} from "../ui/navigation-menu";
import { Button } from "../ui/button";
import Link from "next/link";
import Image from "next/image";
import { ToggleTheme } from "./toogle-theme";
interface RouteProps {
href: string;
label: string;
}
interface FeatureProps {
title: string;
description: string;
}
const routeList: RouteProps[] = [
{
href: "#testimonials",
label: "Testimonials",
},
{
href: "#team",
label: "Team",
},
{
href: "#contact",
label: "Contact",
},
{
href: "#faq",
label: "FAQ",
},
];
const featureList: FeatureProps[] = [
{
title: "Showcase Your Value ",
description: "Highlight how your product solves user problems.",
},
{
title: "Build Trust",
description:
"Leverages social proof elements to establish trust and credibility.",
},
{
title: "Capture Leads",
description:
"Make your lead capture form visually appealing and strategically.",
},
];
export const Navbar = () => {
const [isOpen, setIsOpen] = React.useState(false);
return (
<header className="shadow-inner bg-opacity-15 w-[90%] md:w-[70%] lg:w-[75%] lg:max-w-screen-xl top-5 mx-auto sticky border border-secondary z-40 rounded-2xl flex justify-between items-center p-2 bg-card">
<Link href="/" className="font-bold text-lg flex items-center">
<ChevronsDown className="bg-gradient-to-tr border-secondary from-primary via-primary/70 to-primary rounded-lg w-9 h-9 mr-2 border text-white" />
Shadcn
</Link>
{/* <!-- Mobile --> */}
<div className="flex items-center lg:hidden">
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetTrigger asChild>
<Menu
onClick={() => setIsOpen(!isOpen)}
className="cursor-pointer lg:hidden"
/>
</SheetTrigger>
<SheetContent
side="left"
className="flex flex-col justify-between rounded-tr-2xl rounded-br-2xl bg-card border-secondary"
>
<div>
<SheetHeader className="mb-4 ml-4">
<SheetTitle className="flex items-center">
<Link href="/" className="flex items-center">
<ChevronsDown className="bg-gradient-to-tr border-secondary from-primary via-primary/70 to-primary rounded-lg w-9 h-9 mr-2 border text-white" />
Shadcn
</Link>
</SheetTitle>
</SheetHeader>
<div className="flex flex-col gap-2">
{routeList.map(({ href, label }) => (
<Button
key={href}
onClick={() => setIsOpen(false)}
asChild
variant="ghost"
className="justify-start text-base"
>
<Link href={href}>{label}</Link>
</Button>
))}
</div>
</div>
<SheetFooter className="flex-col sm:flex-col justify-start items-start">
<Separator className="mb-2" />
<ToggleTheme />
</SheetFooter>
</SheetContent>
</Sheet>
</div>
{/* <!-- Desktop --> */}
<NavigationMenu className="hidden lg:block mx-auto">
<NavigationMenuList>
<NavigationMenuItem>
<NavigationMenuTrigger className="bg-card text-base">
Features
</NavigationMenuTrigger>
<NavigationMenuContent>
<div className="grid w-[600px] grid-cols-2 gap-5 p-4">
<Image
src="https://avatars.githubusercontent.com/u/75042455?v=4"
alt="RadixLogo"
className="h-full w-full rounded-md object-cover"
width={600}
height={600}
/>
<ul className="flex flex-col gap-2">
{featureList.map(({ title, description }) => (
<li
key={title}
className="rounded-md p-3 text-sm hover:bg-muted"
>
<p className="mb-1 font-semibold leading-none text-foreground">
{title}
</p>
<p className="line-clamp-2 text-muted-foreground">
{description}
</p>
</li>
))}
</ul>
</div>
</NavigationMenuContent>
</NavigationMenuItem>
<NavigationMenuItem>
{routeList.map(({ href, label }) => (
<NavigationMenuLink key={href} asChild>
<Link href={href} className="text-base px-2">
{label}
</Link>
</NavigationMenuLink>
))}
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
<div className="hidden lg:flex">
<ToggleTheme />
<Button asChild size="sm" variant="ghost" aria-label="View on GitHub">
<Link
aria-label="View on GitHub"
href="https://github.com/nobruf/shadcn-landing-page.git"
target="_blank"
>
<Github className="size-5" />
</Link>
</Button>
</div>
</header>
);
};
| nobruf/shadcn-landing-page/components/layout/navbar.tsx | {
"file_path": "nobruf/shadcn-landing-page/components/layout/navbar.tsx",
"repo_id": "nobruf/shadcn-landing-page",
"token_count": 2928
} | 54 |
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
| nobruf/shadcn-landing-page/lib/utils.ts | {
"file_path": "nobruf/shadcn-landing-page/lib/utils.ts",
"repo_id": "nobruf/shadcn-landing-page",
"token_count": 64
} | 55 |
import { Metadata } from "next"
import Link from "next/link"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
import { Icons } from "@/components/icons"
import { UserAuthForm } from "@/components/user-auth-form"
export const metadata: Metadata = {
title: "Login",
description: "Login to your account",
}
export default function LoginPage() {
return (
<div className="container flex h-screen w-screen flex-col items-center justify-center">
<Link
href="/"
className={cn(
buttonVariants({ variant: "ghost" }),
"absolute left-4 top-4 md:left-8 md:top-8"
)}
>
<>
<Icons.chevronLeft className="mr-2 h-4 w-4" />
Back
</>
</Link>
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
<div className="flex flex-col space-y-2 text-center">
<Icons.logo className="mx-auto h-6 w-6" />
<h1 className="text-2xl font-semibold tracking-tight">
Welcome back
</h1>
<p className="text-sm text-muted-foreground">
Enter your email to sign in to your account
</p>
</div>
<UserAuthForm />
<p className="px-8 text-center text-sm text-muted-foreground">
<Link
href="/register"
className="hover:text-brand underline underline-offset-4"
>
Don't have an account? Sign Up
</Link>
</p>
</div>
</div>
)
}
| shadcn-ui/taxonomy/app/(auth)/login/page.tsx | {
"file_path": "shadcn-ui/taxonomy/app/(auth)/login/page.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 724
} | 56 |
import Link from "next/link"
import { buttonVariants } from "@/components/ui/button"
import { EmptyPlaceholder } from "@/components/empty-placeholder"
export default function NotFound() {
return (
<EmptyPlaceholder className="mx-auto max-w-[800px]">
<EmptyPlaceholder.Icon name="warning" />
<EmptyPlaceholder.Title>Uh oh! Not Found</EmptyPlaceholder.Title>
<EmptyPlaceholder.Description>
This post cound not be found. Please try again.
</EmptyPlaceholder.Description>
<Link href="/dashboard" className={buttonVariants({ variant: "ghost" })}>
Go to Dashboard
</Link>
</EmptyPlaceholder>
)
}
| shadcn-ui/taxonomy/app/(editor)/editor/[postId]/not-found.tsx | {
"file_path": "shadcn-ui/taxonomy/app/(editor)/editor/[postId]/not-found.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 231
} | 57 |
import { Inter as FontSans } from "next/font/google"
import localFont from "next/font/local"
import "@/styles/globals.css"
import { siteConfig } from "@/config/site"
import { absoluteUrl, cn } from "@/lib/utils"
import { Toaster } from "@/components/ui/toaster"
import { Analytics } from "@/components/analytics"
import { TailwindIndicator } from "@/components/tailwind-indicator"
import { ThemeProvider } from "@/components/theme-provider"
const fontSans = FontSans({
subsets: ["latin"],
variable: "--font-sans",
})
// Font files can be colocated inside of `pages`
const fontHeading = localFont({
src: "../assets/fonts/CalSans-SemiBold.woff2",
variable: "--font-heading",
})
interface RootLayoutProps {
children: React.ReactNode
}
export const metadata = {
title: {
default: siteConfig.name,
template: `%s | ${siteConfig.name}`,
},
description: siteConfig.description,
keywords: [
"Next.js",
"React",
"Tailwind CSS",
"Server Components",
"Radix UI",
],
authors: [
{
name: "shadcn",
url: "https://shadcn.com",
},
],
creator: "shadcn",
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "white" },
{ media: "(prefers-color-scheme: dark)", color: "black" },
],
openGraph: {
type: "website",
locale: "en_US",
url: siteConfig.url,
title: siteConfig.name,
description: siteConfig.description,
siteName: siteConfig.name,
},
twitter: {
card: "summary_large_image",
title: siteConfig.name,
description: siteConfig.description,
images: [`${siteConfig.url}/og.jpg`],
creator: "@shadcn",
},
icons: {
icon: "/favicon.ico",
shortcut: "/favicon-16x16.png",
apple: "/apple-touch-icon.png",
},
manifest: `${siteConfig.url}/site.webmanifest`,
}
export default function RootLayout({ children }: RootLayoutProps) {
return (
<html lang="en" suppressHydrationWarning>
<head />
<body
className={cn(
"min-h-screen bg-background font-sans antialiased",
fontSans.variable,
fontHeading.variable
)}
>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
{children}
<Analytics />
<Toaster />
<TailwindIndicator />
</ThemeProvider>
</body>
</html>
)
}
| shadcn-ui/taxonomy/app/layout.tsx | {
"file_path": "shadcn-ui/taxonomy/app/layout.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 949
} | 58 |
"use client"
import * as React from "react"
import Link from "next/link"
import { useSelectedLayoutSegment } from "next/navigation"
import { MainNavItem } from "types"
import { siteConfig } from "@/config/site"
import { cn } from "@/lib/utils"
import { Icons } from "@/components/icons"
import { MobileNav } from "@/components/mobile-nav"
interface MainNavProps {
items?: MainNavItem[]
children?: React.ReactNode
}
export function MainNav({ items, children }: MainNavProps) {
const segment = useSelectedLayoutSegment()
const [showMobileMenu, setShowMobileMenu] = React.useState<boolean>(false)
return (
<div className="flex gap-6 md:gap-10">
<Link href="/" className="hidden items-center space-x-2 md:flex">
<Icons.logo />
<span className="hidden font-bold sm:inline-block">
{siteConfig.name}
</span>
</Link>
{items?.length ? (
<nav className="hidden gap-6 md:flex">
{items?.map((item, index) => (
<Link
key={index}
href={item.disabled ? "#" : item.href}
className={cn(
"flex items-center text-lg font-medium transition-colors hover:text-foreground/80 sm:text-sm",
item.href.startsWith(`/${segment}`)
? "text-foreground"
: "text-foreground/60",
item.disabled && "cursor-not-allowed opacity-80"
)}
>
{item.title}
</Link>
))}
</nav>
) : null}
<button
className="flex items-center space-x-2 md:hidden"
onClick={() => setShowMobileMenu(!showMobileMenu)}
>
{showMobileMenu ? <Icons.close /> : <Icons.logo />}
<span className="font-bold">Menu</span>
</button>
{showMobileMenu && items && (
<MobileNav items={items}>{children}</MobileNav>
)}
</div>
)
}
| shadcn-ui/taxonomy/components/main-nav.tsx | {
"file_path": "shadcn-ui/taxonomy/components/main-nav.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 882
} | 59 |
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import { ThemeProviderProps } from "next-themes/dist/types"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}
| shadcn-ui/taxonomy/components/theme-provider.tsx | {
"file_path": "shadcn-ui/taxonomy/components/theme-provider.tsx",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 97
} | 60 |
import { createEnv } from "@t3-oss/env-nextjs"
import { z } from "zod"
export const env = createEnv({
server: {
// This is optional because it's only used in development.
// See https://next-auth.js.org/deployment.
NEXTAUTH_URL: z.string().url().optional(),
NEXTAUTH_SECRET: z.string().min(1),
GITHUB_CLIENT_ID: z.string().min(1),
GITHUB_CLIENT_SECRET: z.string().min(1),
GITHUB_ACCESS_TOKEN: z.string().min(1),
DATABASE_URL: z.string().min(1),
SMTP_FROM: z.string().min(1),
POSTMARK_API_TOKEN: z.string().min(1),
POSTMARK_SIGN_IN_TEMPLATE: z.string().min(1),
POSTMARK_ACTIVATION_TEMPLATE: z.string().min(1),
STRIPE_API_KEY: z.string().min(1),
STRIPE_WEBHOOK_SECRET: z.string().min(1),
STRIPE_PRO_MONTHLY_PLAN_ID: z.string().min(1),
},
client: {
NEXT_PUBLIC_APP_URL: z.string().min(1),
},
runtimeEnv: {
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET,
GITHUB_ACCESS_TOKEN: process.env.GITHUB_ACCESS_TOKEN,
DATABASE_URL: process.env.DATABASE_URL,
SMTP_FROM: process.env.SMTP_FROM,
POSTMARK_API_TOKEN: process.env.POSTMARK_API_TOKEN,
POSTMARK_SIGN_IN_TEMPLATE: process.env.POSTMARK_SIGN_IN_TEMPLATE,
POSTMARK_ACTIVATION_TEMPLATE: process.env.POSTMARK_ACTIVATION_TEMPLATE,
STRIPE_API_KEY: process.env.STRIPE_API_KEY,
STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,
STRIPE_PRO_MONTHLY_PLAN_ID: process.env.STRIPE_PRO_MONTHLY_PLAN_ID,
NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
},
})
| shadcn-ui/taxonomy/env.mjs | {
"file_path": "shadcn-ui/taxonomy/env.mjs",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 792
} | 61 |
import { withContentlayer } from "next-contentlayer"
import "./env.mjs"
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: ["avatars.githubusercontent.com"],
},
experimental: {
appDir: true,
serverComponentsExternalPackages: ["@prisma/client"],
},
}
export default withContentlayer(nextConfig)
| shadcn-ui/taxonomy/next.config.mjs | {
"file_path": "shadcn-ui/taxonomy/next.config.mjs",
"repo_id": "shadcn-ui/taxonomy",
"token_count": 124
} | 62 |
import { notFound } from "next/navigation"
import { allDocs } from "contentlayer/generated"
import "@/styles/mdx.css"
import type { Metadata } from "next"
import Link from "next/link"
import { ChevronRightIcon, ExternalLinkIcon } from "@radix-ui/react-icons"
import Balancer from "react-wrap-balancer"
import { siteConfig } from "@/config/site"
import { getTableOfContents } from "@/lib/toc"
import { absoluteUrl, cn } from "@/lib/utils"
import { Mdx } from "@/components/mdx-components"
import { OpenInV0Cta } from "@/components/open-in-v0-cta"
import { DocsPager } from "@/components/pager"
import { DashboardTableOfContents } from "@/components/toc"
import { badgeVariants } from "@/registry/new-york/ui/badge"
import { ScrollArea } from "@/registry/new-york/ui/scroll-area"
interface DocPageProps {
params: {
slug: string[]
}
}
async function getDocFromParams({ params }: DocPageProps) {
const slug = params.slug?.join("/") || ""
const doc = allDocs.find((doc) => doc.slugAsParams === slug)
if (!doc) {
return null
}
return doc
}
export async function generateMetadata({
params,
}: DocPageProps): Promise<Metadata> {
const doc = await getDocFromParams({ params })
if (!doc) {
return {}
}
return {
title: doc.title,
description: doc.description,
openGraph: {
title: doc.title,
description: doc.description,
type: "article",
url: absoluteUrl(doc.slug),
images: [
{
url: siteConfig.ogImage,
width: 1200,
height: 630,
alt: siteConfig.name,
},
],
},
twitter: {
card: "summary_large_image",
title: doc.title,
description: doc.description,
images: [siteConfig.ogImage],
creator: "@shadcn",
},
}
}
export async function generateStaticParams(): Promise<
DocPageProps["params"][]
> {
return allDocs.map((doc) => ({
slug: doc.slugAsParams.split("/"),
}))
}
export default async function DocPage({ params }: DocPageProps) {
const doc = await getDocFromParams({ params })
if (!doc) {
notFound()
}
const toc = await getTableOfContents(doc.body.raw)
return (
<main className="relative py-6 lg:gap-10 lg:py-8 xl:grid xl:grid-cols-[1fr_300px]">
<div className="mx-auto w-full min-w-0">
<div className="mb-4 flex items-center space-x-1 text-sm leading-none text-muted-foreground">
<div className="truncate">Docs</div>
<ChevronRightIcon className="h-3.5 w-3.5" />
<div className="text-foreground">{doc.title}</div>
</div>
<div className="space-y-2">
<h1 className={cn("scroll-m-20 text-3xl font-bold tracking-tight")}>
{doc.title}
</h1>
{doc.description && (
<p className="text-base text-muted-foreground">
<Balancer>{doc.description}</Balancer>
</p>
)}
</div>
{doc.links ? (
<div className="flex items-center space-x-2 pt-4">
{doc.links?.doc && (
<Link
href={doc.links.doc}
target="_blank"
rel="noreferrer"
className={cn(badgeVariants({ variant: "secondary" }), "gap-1")}
>
Docs
<ExternalLinkIcon className="h-3 w-3" />
</Link>
)}
{doc.links?.api && (
<Link
href={doc.links.api}
target="_blank"
rel="noreferrer"
className={cn(badgeVariants({ variant: "secondary" }), "gap-1")}
>
API Reference
<ExternalLinkIcon className="h-3 w-3" />
</Link>
)}
</div>
) : null}
<div className="pb-12 pt-8">
<Mdx code={doc.body.code} />
</div>
<DocsPager doc={doc} />
</div>
<div className="hidden text-sm xl:block">
<div className="sticky top-16 -mt-10 h-[calc(100vh-3.5rem)] pt-4">
<ScrollArea className="h-full pb-10">
{doc.toc && <DashboardTableOfContents toc={toc} />}
<OpenInV0Cta className="mt-6 max-w-[80%]" />
</ScrollArea>
</div>
</div>
</main>
)
}
| shadcn-ui/ui/apps/www/app/(app)/docs/[[...slug]]/page.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/docs/[[...slug]]/page.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 2045
} | 63 |
"use client"
import { Bar, BarChart, ResponsiveContainer, XAxis, YAxis } from "recharts"
const data = [
{
name: "Jan",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Feb",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Mar",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Apr",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "May",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Jun",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Jul",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Aug",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Sep",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Oct",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Nov",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Dec",
total: Math.floor(Math.random() * 5000) + 1000,
},
]
export function Overview() {
return (
<ResponsiveContainer width="100%" height={350}>
<BarChart data={data}>
<XAxis
dataKey="name"
stroke="#888888"
fontSize={12}
tickLine={false}
axisLine={false}
/>
<YAxis
stroke="#888888"
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={(value) => `$${value}`}
/>
<Bar
dataKey="total"
fill="currentColor"
radius={[4, 4, 0, 0]}
className="fill-primary"
/>
</BarChart>
</ResponsiveContainer>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/dashboard/components/overview.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/dashboard/components/overview.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 819
} | 64 |
import { Separator } from "@/registry/new-york/ui/separator"
import { ProfileForm } from "@/app/(app)/examples/forms/profile-form"
export default function SettingsProfilePage() {
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-medium">Profile</h3>
<p className="text-sm text-muted-foreground">
This is how others will see you on the site.
</p>
</div>
<Separator />
<ProfileForm />
</div>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/forms/page.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/forms/page.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 208
} | 65 |
export type Playlist = (typeof playlists)[number]
export const playlists = [
"Recently Added",
"Recently Played",
"Top Songs",
"Top Albums",
"Top Artists",
"Logic Discography",
"Bedtime Beats",
"Feeling Happy",
"I miss Y2K Pop",
"Runtober",
"Mellow Days",
"Eminem Essentials",
]
| shadcn-ui/ui/apps/www/app/(app)/examples/music/data/playlists.ts | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/music/data/playlists.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 110
} | 66 |
import * as React from "react"
import { CheckIcon, PlusCircledIcon } from "@radix-ui/react-icons"
import { Column } from "@tanstack/react-table"
import { cn } from "@/lib/utils"
import { Badge } from "@/registry/new-york/ui/badge"
import { Button } from "@/registry/new-york/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/registry/new-york/ui/command"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/registry/new-york/ui/popover"
import { Separator } from "@/registry/new-york/ui/separator"
interface DataTableFacetedFilterProps<TData, TValue> {
column?: Column<TData, TValue>
title?: string
options: {
label: string
value: string
icon?: React.ComponentType<{ className?: string }>
}[]
}
export function DataTableFacetedFilter<TData, TValue>({
column,
title,
options,
}: DataTableFacetedFilterProps<TData, TValue>) {
const facets = column?.getFacetedUniqueValues()
const selectedValues = new Set(column?.getFilterValue() as string[])
return (
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="h-8 border-dashed">
<PlusCircledIcon className="mr-2 h-4 w-4" />
{title}
{selectedValues?.size > 0 && (
<>
<Separator orientation="vertical" className="mx-2 h-4" />
<Badge
variant="secondary"
className="rounded-sm px-1 font-normal lg:hidden"
>
{selectedValues.size}
</Badge>
<div className="hidden space-x-1 lg:flex">
{selectedValues.size > 2 ? (
<Badge
variant="secondary"
className="rounded-sm px-1 font-normal"
>
{selectedValues.size} selected
</Badge>
) : (
options
.filter((option) => selectedValues.has(option.value))
.map((option) => (
<Badge
variant="secondary"
key={option.value}
className="rounded-sm px-1 font-normal"
>
{option.label}
</Badge>
))
)}
</div>
</>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0" align="start">
<Command>
<CommandInput placeholder={title} />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup>
{options.map((option) => {
const isSelected = selectedValues.has(option.value)
return (
<CommandItem
key={option.value}
onSelect={() => {
if (isSelected) {
selectedValues.delete(option.value)
} else {
selectedValues.add(option.value)
}
const filterValues = Array.from(selectedValues)
column?.setFilterValue(
filterValues.length ? filterValues : undefined
)
}}
>
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
isSelected
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
>
<CheckIcon className={cn("h-4 w-4")} />
</div>
{option.icon && (
<option.icon className="mr-2 h-4 w-4 text-muted-foreground" />
)}
<span>{option.label}</span>
{facets?.get(option.value) && (
<span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs">
{facets.get(option.value)}
</span>
)}
</CommandItem>
)
})}
</CommandGroup>
{selectedValues.size > 0 && (
<>
<CommandSeparator />
<CommandGroup>
<CommandItem
onSelect={() => column?.setFilterValue(undefined)}
className="justify-center text-center"
>
Clear filters
</CommandItem>
</CommandGroup>
</>
)}
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
| shadcn-ui/ui/apps/www/app/(app)/examples/tasks/components/data-table-faceted-filter.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/examples/tasks/components/data-table-faceted-filter.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 2834
} | 67 |
import * as React from "react"
import Link from "next/link"
import { cn } from "@/lib/utils"
import AccordionDemo from "@/registry/default/example/accordion-demo"
import AlertDialogDemo from "@/registry/default/example/alert-dialog-demo"
import AspectRatioDemo from "@/registry/default/example/aspect-ratio-demo"
import AvatarDemo from "@/registry/default/example/avatar-demo"
import BadgeDemo from "@/registry/default/example/badge-demo"
import BadgeDestructive from "@/registry/default/example/badge-destructive"
import BadgeOutline from "@/registry/default/example/badge-outline"
import BadgeSecondary from "@/registry/default/example/badge-secondary"
import ButtonDemo from "@/registry/default/example/button-demo"
import ButtonDestructive from "@/registry/default/example/button-destructive"
import ButtonGhost from "@/registry/default/example/button-ghost"
import ButtonLink from "@/registry/default/example/button-link"
import ButtonLoading from "@/registry/default/example/button-loading"
import ButtonOutline from "@/registry/default/example/button-outline"
import ButtonSecondary from "@/registry/default/example/button-secondary"
import ButtonWithIcon from "@/registry/default/example/button-with-icon"
import CardDemo from "@/registry/default/example/card-demo"
import CheckboxDemo from "@/registry/default/example/checkbox-demo"
import CollapsibleDemo from "@/registry/default/example/collapsible-demo"
import CommandDemo from "@/registry/default/example/command-demo"
import ContextMenuDemo from "@/registry/default/example/context-menu-demo"
import DatePickerDemo from "@/registry/default/example/date-picker-demo"
import DialogDemo from "@/registry/default/example/dialog-demo"
import DropdownMenuDemo from "@/registry/default/example/dropdown-menu-demo"
import HoverCardDemo from "@/registry/default/example/hover-card-demo"
import MenubarDemo from "@/registry/default/example/menubar-demo"
import NavigationMenuDemo from "@/registry/default/example/navigation-menu-demo"
import PopoverDemo from "@/registry/default/example/popover-demo"
import ProgressDemo from "@/registry/default/example/progress-demo"
import RadioGroupDemo from "@/registry/default/example/radio-group-demo"
import ScrollAreaDemo from "@/registry/default/example/scroll-area-demo"
import SelectDemo from "@/registry/default/example/select-demo"
import SeparatorDemo from "@/registry/default/example/separator-demo"
import SheetDemo from "@/registry/default/example/sheet-demo"
import SkeletonDemo from "@/registry/default/example/skeleton-demo"
import SliderDemo from "@/registry/default/example/slider-demo"
import SwitchDemo from "@/registry/default/example/switch-demo"
import TabsDemo from "@/registry/default/example/tabs-demo"
import ToastDemo from "@/registry/default/example/toast-demo"
import ToggleDemo from "@/registry/default/example/toggle-demo"
import ToggleDisabled from "@/registry/default/example/toggle-disabled"
import ToggleGroupDemo from "@/registry/default/example/toggle-group-demo"
import ToggleOutline from "@/registry/default/example/toggle-outline"
import ToggleWithText from "@/registry/default/example/toggle-with-text"
import TooltipDemo from "@/registry/default/example/tooltip-demo"
import { Button } from "@/registry/default/ui/button"
export default function KitchenSinkPage() {
return (
<div className="container">
<div className="grid gap-4">
<div className="grid grid-cols-3 items-start gap-4">
<div className="grid gap-4">
<ComponentWrapper>
<CardDemo className="w-full" />
</ComponentWrapper>
<ComponentWrapper>
<SliderDemo className="w-full" />
</ComponentWrapper>
<ComponentWrapper
className="spa flex-col items-start space-x-0
space-y-2"
>
<p className="text-sm text-muted-foreground">Documentation</p>
<p className="text-sm font-medium leading-none">
You can customize the theme using{" "}
<code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold text-foreground">
CSS variables
</code>
.{" "}
<Link
href="#"
className="font-medium text-primary underline underline-offset-4"
>
Click here
</Link>{" "}
to learn more.
</p>
</ComponentWrapper>
<ComponentWrapper>
<CheckboxDemo />
<HoverCardDemo />
</ComponentWrapper>
<ComponentWrapper className="[&>div]:w-full">
<TabsDemo />
</ComponentWrapper>
</div>
<div className="grid gap-4">
<ComponentWrapper>
<MenubarDemo />
<AvatarDemo />
</ComponentWrapper>
<ComponentWrapper className="flex-col items-start space-x-0 space-y-2">
<div className="flex space-x-2">
<ButtonDemo />
<ButtonSecondary />
<ButtonDestructive />
</div>
<div className="flex space-x-2">
<ButtonOutline />
<ButtonLink />
<ButtonGhost />
</div>
<div className="flex space-x-2">
<ButtonWithIcon />
<ButtonLoading />
</div>
<div className="flex space-x-2">
<Button size="lg">Large</Button>
<Button size="sm">Small</Button>
</div>
</ComponentWrapper>
<ComponentWrapper>
<DatePickerDemo />
</ComponentWrapper>
<ComponentWrapper>
<AccordionDemo />
</ComponentWrapper>
<ComponentWrapper className="[&_ul>li:last-child]:hidden">
<NavigationMenuDemo />
</ComponentWrapper>
<ComponentWrapper className="justify-between">
<SwitchDemo />
<SelectDemo />
</ComponentWrapper>
<ComponentWrapper>
<ToggleGroupDemo />
</ComponentWrapper>
<ComponentWrapper>
<SeparatorDemo />
</ComponentWrapper>
<ComponentWrapper>
<AspectRatioDemo />
</ComponentWrapper>
<ComponentWrapper>
<PopoverDemo />
<ToastDemo />
</ComponentWrapper>
</div>
<div className="grid gap-4">
<ComponentWrapper>
<TooltipDemo />
<SheetDemo />
<ProgressDemo />
</ComponentWrapper>
<ComponentWrapper>
<CommandDemo />
</ComponentWrapper>
<ComponentWrapper className="[&>span]:h-[80px] [&>span]:w-[200px]">
<RadioGroupDemo />
<ContextMenuDemo />
</ComponentWrapper>
<ComponentWrapper>
<div className="flex space-x-2">
<DropdownMenuDemo />
<AlertDialogDemo />
<DialogDemo />
</div>
</ComponentWrapper>
<ComponentWrapper>
<div className="flex space-x-2">
<BadgeDemo />
<BadgeSecondary />
<BadgeDestructive />
<BadgeOutline />
</div>
</ComponentWrapper>
<ComponentWrapper>
<SkeletonDemo />
</ComponentWrapper>
<ComponentWrapper className="[&>div]:w-full">
<CollapsibleDemo />
</ComponentWrapper>
<ComponentWrapper>
<div className="flex space-x-2">
<ToggleDemo />
<ToggleOutline />
<ToggleDisabled />
<ToggleWithText />
</div>
</ComponentWrapper>
<ComponentWrapper>
<ScrollAreaDemo />
</ComponentWrapper>
</div>
</div>
</div>
</div>
)
}
function ComponentWrapper({
className,
children,
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn(
"flex items-center justify-between space-x-4 rounded-md p-4",
className
)}
>
{children}
</div>
)
}
| shadcn-ui/ui/apps/www/app/(app)/sink/page.tsx | {
"file_path": "shadcn-ui/ui/apps/www/app/(app)/sink/page.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 3974
} | 68 |
import * as React from "react"
import { cn } from "@/lib/utils"
import { useMediaQuery } from "@/hooks/use-media-query"
import { useThemesConfig } from "@/hooks/use-themes-config"
import { BlockCopyButton } from "@/components/block-copy-button"
import { V0Button } from "@/components/v0-button"
import { Button } from "@/registry/new-york/ui/button"
import {
Drawer,
DrawerContent,
DrawerTrigger,
} from "@/registry/new-york/ui/drawer"
import { Sheet, SheetContent, SheetTrigger } from "@/registry/new-york/ui/sheet"
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from "@/registry/new-york/ui/tabs"
import { Block } from "@/registry/schema"
export function ChartCodeViewer({
chart,
className,
children,
}: { chart: Block } & React.ComponentProps<"div">) {
const [tab, setTab] = React.useState("code")
const { themesConfig } = useThemesConfig()
const isDesktop = useMediaQuery("(min-width: 768px)")
const themeCode = React.useMemo(() => {
return `\
@layer base {
:root {
${Object.entries(themesConfig?.activeTheme.cssVars.light || {})
.map(([key, value]) => ` ${key}: ${value};`)
.join("\n")}
}
.dark {
${Object.entries(themesConfig?.activeTheme.cssVars.dark || {})
.map(([key, value]) => ` ${key}: ${value};`)
.join("\n")}
}
}
`
}, [themesConfig])
const button = (
<Button
size="sm"
variant="outline"
className="h-6 rounded-[6px] border bg-transparent px-2 text-xs text-foreground shadow-none hover:bg-muted dark:text-foreground"
>
View Code
</Button>
)
const content = (
<>
<div className="chart-wrapper hidden sm:block [&>div]:rounded-none [&>div]:border-0 [&>div]:border-b [&>div]:shadow-none [&_[data-chart]]:mx-auto [&_[data-chart]]:max-h-[35vh]">
{children}
</div>
<Tabs
defaultValue="code"
className="relative flex h-full flex-1 flex-col overflow-hidden p-4"
value={tab}
onValueChange={setTab}
>
<div className="flex w-full items-center">
<TabsList className="h-7 w-auto rounded-md p-0 px-[calc(theme(spacing.1)_-_2px)] py-[theme(spacing.1)]">
<TabsTrigger
value="code"
className="h-[1.45rem] rounded-sm px-2 text-xs"
>
Code
</TabsTrigger>
<TabsTrigger
value="theme"
className="h-[1.45rem] rounded-sm px-2 text-xs"
>
Theme
</TabsTrigger>
</TabsList>
{tab === "code" && (
<div className="ml-auto flex items-center justify-center gap-2">
<BlockCopyButton
event="copy_chart_code"
name={chart.name}
code={chart.code}
/>
<V0Button
id={`v0-button-${chart.name}`}
block={{
name: chart.name,
description: chart.description || "Edit in v0",
code: chart.code,
style: "default",
}}
className="h-7"
/>
</div>
)}
{tab === "theme" && (
<BlockCopyButton
event="copy_chart_theme"
name={chart.name}
code={themeCode}
className="ml-auto"
/>
)}
</div>
<TabsContent
value="code"
className="h-full flex-1 flex-col overflow-hidden data-[state=active]:flex"
>
<div className="relative overflow-auto rounded-lg bg-black">
<div
data-rehype-pretty-code-fragment
dangerouslySetInnerHTML={{
__html: chart.highlightedCode,
}}
className="w-full overflow-hidden [&_pre]:overflow-auto [&_pre]:!bg-black [&_pre]:py-6 [&_pre]:font-mono [&_pre]:text-sm [&_pre]:leading-relaxed"
/>
</div>
</TabsContent>
<TabsContent
value="theme"
className="h-full flex-1 flex-col overflow-hidden data-[state=active]:flex"
>
<div
data-rehype-pretty-code-fragment
className="relative overflow-auto rounded-lg bg-black py-6"
>
<pre className="bg-black font-mono text-sm leading-relaxed">
<code data-line-numbers="">
<span className="line text-zinc-700">{`/* ${themesConfig?.activeTheme.name} */`}</span>
{themeCode.split("\n").map((line, index) => (
<span key={index} className="line">
{line}
</span>
))}
</code>
</pre>
</div>
</TabsContent>
</Tabs>
</>
)
if (!isDesktop) {
return (
<Drawer>
<DrawerTrigger asChild>{button}</DrawerTrigger>
<DrawerContent
className={cn(
"flex max-h-[80vh] flex-col sm:max-h-[90vh] [&>div.bg-muted]:shrink-0",
className
)}
>
<div className="flex h-full flex-col overflow-auto">{content}</div>
</DrawerContent>
</Drawer>
)
}
return (
<Sheet>
<SheetTrigger asChild>{button}</SheetTrigger>
<SheetContent
side="right"
className={cn(
"flex flex-col gap-0 border-l-0 p-0 dark:border-l sm:max-w-sm md:w-[700px] md:max-w-[700px]",
className
)}
>
{content}
</SheetContent>
</Sheet>
)
}
| shadcn-ui/ui/apps/www/components/chart-code-viewer.tsx | {
"file_path": "shadcn-ui/ui/apps/www/components/chart-code-viewer.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 2840
} | 69 |
"use client"
import * as React from "react"
import { allDocs } from "contentlayer/generated"
import { Mdx } from "./mdx-components"
interface FrameworkDocsProps extends React.HTMLAttributes<HTMLDivElement> {
data: string
}
export function FrameworkDocs({ ...props }: FrameworkDocsProps) {
const frameworkDoc = allDocs.find(
(doc) => doc.slug === `/docs/installation/${props.data}`
)
if (!frameworkDoc) {
return null
}
return <Mdx code={frameworkDoc.body.code} />
}
| shadcn-ui/ui/apps/www/components/framework-docs.tsx | {
"file_path": "shadcn-ui/ui/apps/www/components/framework-docs.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 168
} | 70 |
// import { JetBrains_Mono as FontMono, Inter as FontSans } from "next/font/google"
import { JetBrains_Mono as FontMono } from "next/font/google"
// import { GeistMono } from "geist/font/mono"
import { GeistSans } from "geist/font/sans"
// export const fontSans = FontSans({
// subsets: ["latin"],
// variable: "--font-sans",
// })
export const fontSans = GeistSans
export const fontMono = FontMono({
subsets: ["latin"],
variable: "--font-mono",
})
| shadcn-ui/ui/apps/www/lib/fonts.ts | {
"file_path": "shadcn-ui/ui/apps/www/lib/fonts.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 171
} | 71 |
import { NextApiRequest, NextApiResponse } from "next"
import components from "./components.json"
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== "GET") {
return res.status(405).end()
}
return res.status(200).json(components)
}
| shadcn-ui/ui/apps/www/pages/api/components.ts | {
"file_path": "shadcn-ui/ui/apps/www/pages/api/components.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 102
} | 72 |
"use client"
import { TrendingUp } from "lucide-react"
import { Bar, BarChart, CartesianGrid, Cell, LabelList } 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 negative values"
const chartData = [
{ month: "January", visitors: 186 },
{ month: "February", visitors: 205 },
{ month: "March", visitors: -207 },
{ month: "April", visitors: 173 },
{ month: "May", visitors: -209 },
{ month: "June", visitors: 214 },
]
const chartConfig = {
visitors: {
label: "Visitors",
},
} satisfies ChartConfig
export default function Component() {
return (
<Card>
<CardHeader>
<CardTitle>Bar Chart - Negative</CardTitle>
<CardDescription>January - June 2024</CardDescription>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig}>
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<ChartTooltip
cursor={false}
content={<ChartTooltipContent hideLabel hideIndicator />}
/>
<Bar dataKey="visitors">
<LabelList position="top" dataKey="month" fillOpacity={1} />
{chartData.map((item) => (
<Cell
key={item.month}
fill={
item.visitors > 0
? "hsl(var(--chart-1))"
: "hsl(var(--chart-2))"
}
/>
))}
</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-negative.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/block/chart-bar-negative.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 993
} | 73 |
"use client"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/registry/default/ui/card"
import { Progress } from "@/registry/default/ui/progress"
export default function Component() {
return (
<Card x-chunk="dashboard-05-chunk-2">
<CardHeader className="pb-2">
<CardDescription>This Month</CardDescription>
<CardTitle className="text-4xl">$5,329</CardTitle>
</CardHeader>
<CardContent>
<div className="text-xs text-muted-foreground">
+10% from last month
</div>
</CardContent>
<CardFooter>
<Progress value={12} aria-label="12% increase" />
</CardFooter>
</Card>
)
}
| shadcn-ui/ui/apps/www/registry/default/block/dashboard-05-chunk-2.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/block/dashboard-05-chunk-2.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 304
} | 74 |
"use client"
import Link from "next/link"
import { ChevronRight, Search, type LucideIcon } from "lucide-react"
import { useIsMobile } from "@/registry/default/hooks/use-mobile"
import { cn } from "@/registry/default/lib/utils"
import { Button } from "@/registry/default/ui/button"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/registry/default/ui/collapsible"
import {
Drawer,
DrawerContent,
DrawerTrigger,
} from "@/registry/default/ui/drawer"
import { Input } from "@/registry/default/ui/input"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/registry/default/ui/popover"
import { Separator } from "@/registry/default/ui/separator"
export function NavMain({
className,
items,
searchResults,
}: {
items: {
title: string
url: string
icon: LucideIcon
isActive?: boolean
items?: {
title: string
url: string
}[]
}[]
searchResults: React.ComponentProps<typeof SidebarSearch>["results"]
} & React.ComponentProps<"ul">) {
return (
<ul className={cn("grid gap-0.5", className)}>
<li>
<SidebarSearch results={searchResults} />
</li>
{items.map((item) => (
<Collapsible key={item.title} asChild defaultOpen={item.isActive}>
<li>
<div className="relative flex items-center">
<Link
href={item.url}
className="min-w-8 flex h-8 flex-1 items-center gap-2 overflow-hidden rounded-md px-1.5 text-sm font-medium outline-none ring-ring transition-all hover:bg-accent hover:text-accent-foreground focus-visible:ring-2"
>
<item.icon className="h-4 w-4 shrink-0" />
<div className="flex flex-1 overflow-hidden">
<div className="line-clamp-1 pr-6">{item.title}</div>
</div>
</Link>
<CollapsibleTrigger asChild>
<Button
variant="ghost"
className="absolute right-1 h-6 w-6 rounded-md p-0 ring-ring transition-all focus-visible:ring-2 data-[state=open]:rotate-90"
>
<ChevronRight className="h-4 w-4 text-muted-foreground" />
<span className="sr-only">Toggle</span>
</Button>
</CollapsibleTrigger>
</div>
<CollapsibleContent className="px-4 py-0.5">
<ul className="grid border-l px-2">
{item.items?.map((subItem) => (
<li key={subItem.title}>
<Link
href={subItem.url}
className="min-w-8 flex h-8 items-center gap-2 overflow-hidden rounded-md px-2 text-sm font-medium text-muted-foreground ring-ring transition-all hover:bg-accent hover:text-accent-foreground focus-visible:ring-2"
>
<div className="line-clamp-1">{subItem.title}</div>
</Link>
</li>
))}
</ul>
</CollapsibleContent>
</li>
</Collapsible>
))}
</ul>
)
}
function SidebarSearch({
results,
}: {
results: {
title: string
teaser: string
url: string
}[]
}) {
const isMobile = useIsMobile()
if (isMobile) {
return (
<Drawer>
<DrawerTrigger className="min-w-8 flex h-8 w-full flex-1 items-center gap-2 overflow-hidden rounded-md px-1.5 text-sm font-medium outline-none ring-ring transition-all hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground">
<Search className="h-4 w-4 shrink-0" />
<div className="flex flex-1 overflow-hidden">
<div className="line-clamp-1 pr-6">Search</div>
</div>
</DrawerTrigger>
<DrawerContent>
<form>
<div className="border-b p-2.5">
<Input
type="search"
placeholder="Search..."
className="h-8 rounded-sm shadow-none focus-visible:ring-0"
/>
</div>
</form>
<div className="grid gap-1 p-1.5 text-sm">
{results.map((result) => (
<Link
href={result.url}
key={result.title}
className="rounded-md p-2.5 outline-none ring-ring hover:bg-accent hover:text-accent-foreground focus-visible:ring-2"
>
<div className="font-medium">{result.title}</div>
<div className="line-clamp-2 text-muted-foreground">
{result.teaser}
</div>
</Link>
))}
<Separator className="my-1.5" />
<Link
href="#"
className="rounded-md px-2.5 py-1 text-muted-foreground outline-none ring-ring hover:text-foreground focus-visible:ring-2"
>
See all results
</Link>
</div>
</DrawerContent>
</Drawer>
)
}
return (
<Popover>
<PopoverTrigger className="min-w-8 flex h-8 w-full flex-1 items-center gap-2 overflow-hidden rounded-md px-1.5 text-sm font-medium outline-none ring-ring transition-all hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground">
<Search className="h-4 w-4 shrink-0" />
<div className="flex flex-1 overflow-hidden">
<div className="line-clamp-1 pr-6">Search</div>
</div>
</PopoverTrigger>
<PopoverContent
side="right"
align="start"
sideOffset={4}
className="w-96 p-0"
>
<form>
<div className="border-b p-2.5">
<Input
type="search"
placeholder="Search..."
className="h-8 rounded-sm shadow-none focus-visible:ring-0"
/>
</div>
</form>
<div className="grid gap-1 p-1.5 text-sm">
{results.map((result) => (
<Link
href={result.url}
key={result.title}
className="rounded-md p-2.5 outline-none ring-ring hover:bg-accent hover:text-accent-foreground focus-visible:ring-2"
>
<div className="font-medium">{result.title}</div>
<div className="line-clamp-2 text-muted-foreground">
{result.teaser}
</div>
</Link>
))}
<Separator className="my-1.5" />
<Link
href="#"
className="rounded-md px-2.5 py-1 text-muted-foreground outline-none ring-ring hover:text-foreground focus-visible:ring-2"
>
See all results
</Link>
</div>
</PopoverContent>
</Popover>
)
}
| shadcn-ui/ui/apps/www/registry/default/block/sidebar-01/components/nav-main.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/block/sidebar-01/components/nav-main.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 3447
} | 75 |
import { Badge } from "@/registry/default/ui/badge"
export default function BadgeDestructive() {
return <Badge variant="destructive">Destructive</Badge>
}
| shadcn-ui/ui/apps/www/registry/default/example/badge-destructive.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/badge-destructive.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 49
} | 76 |
import { Button } from "@/registry/default/ui/button"
export default function ButtonOutline() {
return <Button variant="outline">Outline</Button>
}
| shadcn-ui/ui/apps/www/registry/default/example/button-outline.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/button-outline.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 44
} | 77 |
"use client"
import { Icons } from "@/components/icons"
import { Button } from "@/registry/default/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/registry/default/ui/card"
import { Input } from "@/registry/default/ui/input"
import { Label } from "@/registry/default/ui/label"
import { RadioGroup, RadioGroupItem } from "@/registry/default/ui/radio-group"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/registry/default/ui/select"
export function CardsPaymentMethod() {
return (
<Card>
<CardHeader>
<CardTitle>Payment Method</CardTitle>
<CardDescription>
Add a new payment method to your account.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-6">
<RadioGroup defaultValue="card" className="grid grid-cols-3 gap-4">
<div>
<RadioGroupItem
value="card"
id="card"
className="peer sr-only"
aria-label="Card"
/>
<Label
htmlFor="card"
className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-transparent p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
className="mb-3 h-6 w-6"
>
<rect width="20" height="14" x="2" y="5" rx="2" />
<path d="M2 10h20" />
</svg>
Card
</Label>
</div>
<div>
<RadioGroupItem
value="paypal"
id="paypal"
className="peer sr-only"
aria-label="Paypal"
/>
<Label
htmlFor="paypal"
className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-transparent p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
>
<Icons.paypal className="mb-3 h-6 w-6" />
Paypal
</Label>
</div>
<div>
<RadioGroupItem
value="apple"
id="apple"
className="peer sr-only"
aria-label="Apple"
/>
<Label
htmlFor="apple"
className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-transparent p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
>
<Icons.apple className="mb-3 h-6 w-6" />
Apple
</Label>
</div>
</RadioGroup>
<div className="grid gap-2">
<Label htmlFor="name">Name</Label>
<Input id="name" placeholder="First Last" />
</div>
<div className="grid gap-2">
<Label htmlFor="city">City</Label>
<Input id="city" placeholder="" />
</div>
<div className="grid gap-2">
<Label htmlFor="number">Card number</Label>
<Input id="number" placeholder="" />
</div>
<div className="grid grid-cols-3 gap-4">
<div className="grid gap-2">
<Label htmlFor="month">Expires</Label>
<Select>
<SelectTrigger id="month" aria-label="Month">
<SelectValue placeholder="Month" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">January</SelectItem>
<SelectItem value="2">February</SelectItem>
<SelectItem value="3">March</SelectItem>
<SelectItem value="4">April</SelectItem>
<SelectItem value="5">May</SelectItem>
<SelectItem value="6">June</SelectItem>
<SelectItem value="7">July</SelectItem>
<SelectItem value="8">August</SelectItem>
<SelectItem value="9">September</SelectItem>
<SelectItem value="10">October</SelectItem>
<SelectItem value="11">November</SelectItem>
<SelectItem value="12">December</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="year">Year</Label>
<Select>
<SelectTrigger id="year" aria-label="Year">
<SelectValue placeholder="Year" />
</SelectTrigger>
<SelectContent>
{Array.from({ length: 10 }, (_, i) => (
<SelectItem key={i} value={`${new Date().getFullYear() + i}`}>
{new Date().getFullYear() + i}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="cvc">CVC</Label>
<Input id="cvc" placeholder="CVC" />
</div>
</div>
</CardContent>
<CardFooter>
<Button className="w-full">Continue</Button>
</CardFooter>
</Card>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/cards/payment-method.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/cards/payment-method.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 2873
} | 78 |
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
export default function Component() {
return (
<div className="grid aspect-video w-full max-w-md justify-center text-foreground md:grid-cols-2 [&>div]:relative [&>div]:flex [&>div]:h-[137px] [&>div]:w-[224px] [&>div]:items-center [&>div]:justify-center [&>div]:p-4">
<div>
<div className="absolute left-[-35px] top-[45px] z-10 text-sm font-medium">
Label
</div>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 193 40"
width="50"
height="12"
fill="none"
className="absolute left-[5px] top-[50px] z-10"
>
<g clip-path="url(#a)">
<path
fill="currentColor"
d="M173.928 21.13C115.811 44.938 58.751 45.773 0 26.141c4.227-4.386 7.82-2.715 10.567-1.88 21.133 5.64 42.9 6.266 64.457 7.101 31.066 1.253 60.441-5.848 89.183-17.335 1.268-.418 2.325-1.253 4.861-2.924-14.582-2.924-29.165 2.089-41.845-3.76.212-.835.212-1.879.423-2.714 9.51-.627 19.231-1.253 28.742-2.089 9.51-.835 18.808-1.88 28.318-2.506 6.974-.418 9.933 2.924 7.397 9.19-3.17 8.145-7.608 15.664-11.623 23.391-.423.836-1.057 1.88-1.902 2.298-2.325.835-4.65 1.044-7.186 1.67-.422-2.088-1.479-4.386-1.268-6.265.423-2.506 1.902-4.595 3.804-9.19Z"
/>
</g>
<defs>
<clipPath id="a">
<path fill="currentColor" d="M0 0h193v40H0z" />
</clipPath>
</defs>
</svg>
<TooltipDemo
label="Page Views"
payload={[
{ name: "Desktop", value: 186, fill: "hsl(var(--chart-1))" },
{ name: "Mobile", value: 80, fill: "hsl(var(--chart-2))" },
]}
className="w-[8rem]"
/>
</div>
<div className="items-end">
<div className="absolute left-[122px] top-[0px] z-10 text-sm font-medium">
Name
</div>
<svg
xmlns="http://www.w3.org/2000/svg"
width="35"
height="42"
fill="none"
viewBox="0 0 122 148"
className="absolute left-[85px] top-[10px] z-10 -scale-x-100"
>
<g clip-path="url(#ab)">
<path
fill="currentColor"
d="M0 2.65c6.15-4.024 12.299-2.753 17.812-.847a115.56 115.56 0 0 1 21.84 10.59C70.4 32.727 88.849 61.744 96.483 97.54c1.908 9.108 2.544 18.639 3.817 29.017 8.481-4.871 12.934-14.402 21.416-19.909 1.061 4.236-1.06 6.989-2.756 9.319-6.998 9.531-14.207 19.062-21.63 28.382-3.604 4.448-6.36 4.871-10.177 1.059-8.058-7.837-12.935-17.368-14.42-28.382 0-.424.636-1.059 1.485-2.118 9.118 2.33 6.997 13.979 14.843 18.215 3.393-14.614.848-28.593-2.969-42.149-4.029-14.19-9.33-27.746-17.812-39.82-8.27-11.86-18.66-21.392-30.11-30.287C26.93 11.758 14.207 6.039 0 2.65Z"
/>
</g>
<defs>
<clipPath id="ab">
<path fill="currentColor" d="M0 0h122v148H0z" />
</clipPath>
</defs>
</svg>
<TooltipDemo
label="Browser"
hideLabel
payload={[
{ name: "Chrome", value: 1286, fill: "hsl(var(--chart-3))" },
{ name: "Firefox", value: 1000, fill: "hsl(var(--chart-4))" },
]}
indicator="dashed"
className="w-[8rem]"
/>
</div>
<div className="!hidden md:!flex">
<TooltipDemo
label="Page Views"
payload={[
{ name: "Desktop", value: 12486, fill: "hsl(var(--chart-3))" },
]}
className="w-[9rem]"
indicator="line"
/>
</div>
<div className="!items-start !justify-start">
<div className="absolute left-[50px] top-[60px] z-10 text-sm font-medium">
Indicator
</div>
<TooltipDemo
label="Browser"
hideLabel
payload={[
{ name: "Chrome", value: 1286, fill: "hsl(var(--chart-1))" },
]}
indicator="dot"
className="w-[8rem]"
/>
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="34"
fill="none"
viewBox="0 0 75 175"
className="absolute left-[30px] top-[38px] z-10 rotate-[-40deg]"
>
<g clip-path="url(#abc)">
<path
fill="currentColor"
d="M20.187 175c-4.439-2.109-7.186-2.531-8.032-4.008-3.17-5.484-6.763-10.968-8.454-17.084-5.073-16.242-4.439-32.694-1.057-49.146 5.707-28.053 18.388-52.942 34.24-76.565 1.692-2.531 3.171-5.063 4.862-7.805 0-.21-.211-.632-.634-1.265-4.65 1.265-9.511 2.53-14.161 3.585-2.537.422-5.496.422-8.032-.421-1.48-.422-3.593-2.742-3.593-4.219 0-1.898 1.48-4.218 2.747-5.906 1.057-1.054 2.96-1.265 4.65-1.687C35.406 7.315 48.088 3.729 60.98.776c10.99-2.53 14.584 1.055 13.95 11.812-.634 11.18-.846 22.358-1.268 33.326-.212 3.375-.846 6.96-1.268 10.757-8.878-4.007-8.878-4.007-12.048-38.177C47.03 33.259 38.153 49.289 29.91 65.741 21.667 82.193 16.17 99.49 13.212 117.84c-2.959 18.984.634 36.912 6.975 57.161Z"
/>
</g>
<defs>
<clipPath id="abc">
<path fill="currentColor" d="M0 0h75v175H0z" />
</clipPath>
</defs>
</svg>
</div>
</div>
)
}
function TooltipDemo({
indicator = "dot",
label,
payload,
hideLabel,
hideIndicator,
className,
}: {
label: string
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
payload: {
name: string
value: number
fill: string
}[]
nameKey?: string
labelKey?: string
} & React.ComponentProps<"div">) {
const tooltipLabel = hideLabel ? null : (
<div className="font-medium">{label}</div>
)
if (!payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl transition-all ease-in-out hover:-translate-y-0.5",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const indicatorColor = item.fill
return (
<div
key={index}
className={cn(
"flex w-full items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
<>
{!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">{item.name}</span>
</div>
<span className="font-mono font-medium tabular-nums text-foreground">
{item.value.toLocaleString()}
</span>
</div>
</>
</div>
)
})}
</div>
</div>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/chart-tooltip-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/chart-tooltip-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 4742
} | 79 |
"use client"
import * as React from "react"
import { format } from "date-fns"
import { Calendar as CalendarIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/registry/default/ui/button"
import { Calendar } from "@/registry/default/ui/calendar"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/registry/default/ui/popover"
export default function DatePickerDemo() {
const [date, setDate] = React.useState<Date>()
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"w-[280px] justify-start text-left font-normal",
!date && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{date ? format(date, "PPP") : <span>Pick a date</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={date}
onSelect={setDate}
initialFocus
/>
</PopoverContent>
</Popover>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/date-picker-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/date-picker-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 498
} | 80 |
"use client"
import * as React from "react"
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@/registry/default/ui/input-otp"
export default function InputOTPControlled() {
const [value, setValue] = React.useState("")
return (
<div className="space-y-2">
<InputOTP
maxLength={6}
value={value}
onChange={(value) => setValue(value)}
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
<div className="text-center text-sm">
{value === "" ? (
<>Enter your one-time password.</>
) : (
<>You entered: {value}</>
)}
</div>
</div>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/input-otp-controlled.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/input-otp-controlled.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 438
} | 81 |
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { toast } from "@/registry/default/hooks/use-toast"
import { Button } from "@/registry/default/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/registry/default/ui/form"
import { RadioGroup, RadioGroupItem } from "@/registry/default/ui/radio-group"
const FormSchema = z.object({
type: z.enum(["all", "mentions", "none"], {
required_error: "You need to select a notification type.",
}),
})
export default function RadioGroupForm() {
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="type"
render={({ field }) => (
<FormItem className="space-y-3">
<FormLabel>Notify me about...</FormLabel>
<FormControl>
<RadioGroup
onValueChange={field.onChange}
defaultValue={field.value}
className="flex flex-col space-y-1"
>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="all" />
</FormControl>
<FormLabel className="font-normal">
All new messages
</FormLabel>
</FormItem>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="mentions" />
</FormControl>
<FormLabel className="font-normal">
Direct messages and mentions
</FormLabel>
</FormItem>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="none" />
</FormControl>
<FormLabel className="font-normal">Nothing</FormLabel>
</FormItem>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/radio-group-form.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/radio-group-form.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 1448
} | 82 |
import { toast } from "sonner"
import { Button } from "@/registry/default/ui/button"
export default function SonnerDemo() {
return (
<Button
variant="outline"
onClick={() =>
toast("Event has been created", {
description: "Sunday, December 03, 2023 at 9:00 AM",
action: {
label: "Undo",
onClick: () => console.log("Undo"),
},
})
}
>
Show Toast
</Button>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/sonner-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/sonner-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 220
} | 83 |
import { Bold } from "lucide-react"
import { Toggle } from "@/registry/default/ui/toggle"
export default function ToggleDemo() {
return (
<Toggle aria-label="Toggle bold">
<Bold className="h-4 w-4" />
</Toggle>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/toggle-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/toggle-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 94
} | 84 |
export default function TypographyH2() {
return (
<h2 className="scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0">
The People of the Kingdom
</h2>
)
}
| shadcn-ui/ui/apps/www/registry/default/example/typography-h2.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/example/typography-h2.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 79
} | 85 |
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }
| shadcn-ui/ui/apps/www/registry/default/ui/alert.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/default/ui/alert.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 595
} | 86 |
"use client"
import Image from "next/image"
import { Upload } from "lucide-react"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/registry/new-york/ui/card"
export default function Component() {
return (
<Card className="overflow-hidden" x-chunk="dashboard-07-chunk-4">
<CardHeader>
<CardTitle>Product Images</CardTitle>
<CardDescription>
Lipsum dolor sit amet, consectetur adipiscing elit
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-2">
<Image
alt="Product image"
className="aspect-square w-full rounded-md object-cover"
height="300"
src="/placeholder.svg"
width="300"
/>
<div className="grid grid-cols-3 gap-2">
<button>
<Image
alt="Product image"
className="aspect-square w-full rounded-md object-cover"
height="84"
src="/placeholder.svg"
width="84"
/>
</button>
<button>
<Image
alt="Product image"
className="aspect-square w-full rounded-md object-cover"
height="84"
src="/placeholder.svg"
width="84"
/>
</button>
<button className="flex aspect-square w-full items-center justify-center rounded-md border border-dashed">
<Upload className="h-4 w-4 text-muted-foreground" />
<span className="sr-only">Upload</span>
</button>
</div>
</div>
</CardContent>
</Card>
)
}
| shadcn-ui/ui/apps/www/registry/new-york/block/dashboard-07-chunk-4.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/block/dashboard-07-chunk-4.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 898
} | 87 |
import { RocketIcon } from "@radix-ui/react-icons"
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/registry/new-york/ui/alert"
export default function AlertDemo() {
return (
<Alert>
<RocketIcon className="h-4 w-4" />
<AlertTitle>Heads up!</AlertTitle>
<AlertDescription>
You can add components to your app using the cli.
</AlertDescription>
</Alert>
)
}
| shadcn-ui/ui/apps/www/registry/new-york/example/alert-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/alert-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 163
} | 88 |
import { Button } from "@/registry/new-york/ui/button"
export default function ButtonDemo() {
return <Button>Button</Button>
}
| shadcn-ui/ui/apps/www/registry/new-york/example/button-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/button-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 42
} | 89 |
"use client"
import { Button } from "@/registry/new-york/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/registry/new-york/ui/card"
import { Label } from "@/registry/new-york/ui/label"
import { Switch } from "@/registry/new-york/ui/switch"
export function CardsCookieSettings() {
return (
<Card>
<CardHeader>
<CardTitle>Cookie Settings</CardTitle>
<CardDescription>Manage your cookie settings here.</CardDescription>
</CardHeader>
<CardContent className="grid gap-6">
<div className="flex items-center justify-between space-x-4">
<Label htmlFor="necessary" className="flex flex-col space-y-1">
<span>Strictly Necessary</span>
<span className="text-xs font-normal leading-snug text-muted-foreground">
These cookies are essential in order to use the website and use
its features.
</span>
</Label>
<Switch id="necessary" defaultChecked aria-label="Necessary" />
</div>
<div className="flex items-center justify-between space-x-4">
<Label htmlFor="functional" className="flex flex-col space-y-1">
<span>Functional Cookies</span>
<span className="text-xs font-normal leading-snug text-muted-foreground">
These cookies allow the website to provide personalized
functionality.
</span>
</Label>
<Switch id="functional" aria-label="Functional" />
</div>
<div className="flex items-center justify-between space-x-4">
<Label htmlFor="performance" className="flex flex-col space-y-1">
<span>Performance Cookies</span>
<span className="text-xs font-normal leading-snug text-muted-foreground">
These cookies help to improve the performance of the website.
</span>
</Label>
<Switch id="performance" aria-label="Performance" />
</div>
</CardContent>
<CardFooter>
<Button variant="outline" className="w-full">
Save preferences
</Button>
</CardFooter>
</Card>
)
}
| shadcn-ui/ui/apps/www/registry/new-york/example/cards/cookie-settings.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/cards/cookie-settings.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 944
} | 90 |
import { CalendarIcon } from "@radix-ui/react-icons"
import {
Avatar,
AvatarFallback,
AvatarImage,
} from "@/registry/new-york/ui/avatar"
import { Button } from "@/registry/new-york/ui/button"
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/registry/new-york/ui/hover-card"
export default function HoverCardDemo() {
return (
<HoverCard>
<HoverCardTrigger asChild>
<Button variant="link">@nextjs</Button>
</HoverCardTrigger>
<HoverCardContent className="w-80">
<div className="flex justify-between space-x-4">
<Avatar>
<AvatarImage src="https://github.com/vercel.png" />
<AvatarFallback>VC</AvatarFallback>
</Avatar>
<div className="space-y-1">
<h4 className="text-sm font-semibold">@nextjs</h4>
<p className="text-sm">
The React Framework created and maintained by @vercel.
</p>
<div className="flex items-center pt-2">
<CalendarIcon className="mr-2 h-4 w-4 opacity-70" />{" "}
<span className="text-xs text-muted-foreground">
Joined December 2021
</span>
</div>
</div>
</div>
</HoverCardContent>
</HoverCard>
)
}
| shadcn-ui/ui/apps/www/registry/new-york/example/hover-card-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/hover-card-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 618
} | 91 |
"use client"
import { useToast } from "@/registry/new-york/hooks/use-toast"
import { Button } from "@/registry/new-york/ui/button"
import { ToastAction } from "@/registry/new-york/ui/toast"
export default function ToastDemo() {
const { toast } = useToast()
return (
<Button
variant="outline"
onClick={() => {
toast({
title: "Scheduled: Catch up ",
description: "Friday, February 10, 2023 at 5:57 PM",
action: (
<ToastAction altText="Goto schedule to undo">Undo</ToastAction>
),
})
}}
>
Add to calendar
</Button>
)
}
| shadcn-ui/ui/apps/www/registry/new-york/example/toast-demo.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/toast-demo.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 282
} | 92 |
import { FontItalicIcon } from "@radix-ui/react-icons"
import { Toggle } from "@/registry/new-york/ui/toggle"
export default function ToggleWithText() {
return (
<Toggle aria-label="Toggle italic">
<FontItalicIcon className="mr-2 h-4 w-4" />
Italic
</Toggle>
)
}
| shadcn-ui/ui/apps/www/registry/new-york/example/toggle-with-text.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/example/toggle-with-text.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 119
} | 93 |
"use client"
import * as React from "react"
import { CheckIcon } from "@radix-ui/react-icons"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { cn } from "@/lib/utils"
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn("grid gap-2", className)}
{...props}
ref={ref}
/>
)
})
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<CheckIcon className="h-3.5 w-3.5 fill-primary" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
})
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
export { RadioGroup, RadioGroupItem }
| shadcn-ui/ui/apps/www/registry/new-york/ui/radio-group.tsx | {
"file_path": "shadcn-ui/ui/apps/www/registry/new-york/ui/radio-group.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 518
} | 94 |
const baseConfig = require("../../tailwind.config.cjs")
/** @type {import('tailwindcss').Config} */
module.exports = {
...baseConfig,
content: [
...baseConfig.content,
"content/**/*.mdx",
"registry/**/*.{ts,tsx}",
],
}
| shadcn-ui/ui/apps/www/tailwind.config.cjs | {
"file_path": "shadcn-ui/ui/apps/www/tailwind.config.cjs",
"repo_id": "shadcn-ui/ui",
"token_count": 94
} | 95 |
import path from "path"
import { resolveImport } from "@/src/utils/resolve-import"
import { cosmiconfig } from "cosmiconfig"
import { loadConfig } from "tsconfig-paths"
import { z } from "zod"
export const DEFAULT_STYLE = "default"
export const DEFAULT_COMPONENTS = "@/components"
export const DEFAULT_UTILS = "@/lib/utils"
export const DEFAULT_TAILWIND_CSS = "app/globals.css"
export const DEFAULT_TAILWIND_CONFIG = "tailwind.config.js"
export const DEFAULT_TAILWIND_BASE_COLOR = "slate"
// TODO: Figure out if we want to support all cosmiconfig formats.
// A simple components.json file would be nice.
const explorer = cosmiconfig("components", {
searchPlaces: ["components.json"],
})
export const rawConfigSchema = z
.object({
$schema: z.string().optional(),
style: z.string(),
rsc: z.coerce.boolean().default(false),
tsx: z.coerce.boolean().default(true),
tailwind: z.object({
config: z.string(),
css: z.string(),
baseColor: z.string(),
cssVariables: z.boolean().default(true),
prefix: z.string().default("").optional(),
}),
aliases: z.object({
components: z.string(),
utils: z.string(),
ui: z.string().optional(),
}),
})
.strict()
export type RawConfig = z.infer<typeof rawConfigSchema>
export const configSchema = rawConfigSchema.extend({
resolvedPaths: z.object({
tailwindConfig: z.string(),
tailwindCss: z.string(),
utils: z.string(),
components: z.string(),
ui: z.string(),
}),
})
export type Config = z.infer<typeof configSchema>
export async function getConfig(cwd: string) {
const config = await getRawConfig(cwd)
if (!config) {
return null
}
return await resolveConfigPaths(cwd, config)
}
export async function resolveConfigPaths(cwd: string, config: RawConfig) {
// Read tsconfig.json.
const tsConfig = await loadConfig(cwd)
if (tsConfig.resultType === "failed") {
throw new Error(
`Failed to load ${config.tsx ? "tsconfig" : "jsconfig"}.json. ${
tsConfig.message ?? ""
}`.trim()
)
}
return configSchema.parse({
...config,
resolvedPaths: {
tailwindConfig: path.resolve(cwd, config.tailwind.config),
tailwindCss: path.resolve(cwd, config.tailwind.css),
utils: await resolveImport(config.aliases["utils"], tsConfig),
components: await resolveImport(config.aliases["components"], tsConfig),
ui: config.aliases["ui"]
? await resolveImport(config.aliases["ui"], tsConfig)
: await resolveImport(config.aliases["components"], tsConfig),
},
})
}
export async function getRawConfig(cwd: string): Promise<RawConfig | null> {
try {
const configResult = await explorer.search(cwd)
if (!configResult) {
return null
}
return rawConfigSchema.parse(configResult.config)
} catch (error) {
throw new Error(`Invalid configuration found in ${cwd}/components.json.`)
}
}
| shadcn-ui/ui/packages/cli/src/utils/get-config.ts | {
"file_path": "shadcn-ui/ui/packages/cli/src/utils/get-config.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 1092
} | 96 |
import fs from "fs"
import path from "path"
import { execa } from "execa"
import { afterEach, expect, test, vi } from "vitest"
import { runInit } from "../../src/commands/init"
import { getConfig } from "../../src/utils/get-config"
import * as getPackageManger from "../../src/utils/get-package-manager"
import * as registry from "../../src/utils/registry"
vi.mock("execa")
vi.mock("fs/promises", () => ({
writeFile: vi.fn(),
mkdir: vi.fn(),
}))
vi.mock("ora")
test("init config-full", async () => {
vi.spyOn(getPackageManger, "getPackageManager").mockResolvedValue("pnpm")
vi.spyOn(registry, "getRegistryBaseColor").mockResolvedValue({
inlineColors: {},
cssVars: {},
inlineColorsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
cssVarsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
})
const mockMkdir = vi.spyOn(fs.promises, "mkdir").mockResolvedValue(undefined)
const mockWriteFile = vi.spyOn(fs.promises, "writeFile").mockResolvedValue()
const targetDir = path.resolve(__dirname, "../fixtures/config-full")
const config = await getConfig(targetDir)
await runInit(targetDir, config)
expect(mockMkdir).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/src\/app$/),
expect.anything()
)
expect(mockMkdir).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/src\/lib$/),
expect.anything()
)
expect(mockMkdir).toHaveBeenNthCalledWith(
3,
expect.stringMatching(/src\/components$/),
expect.anything()
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/tailwind.config.ts$/),
expect.stringContaining(`import type { Config } from "tailwindcss"`),
"utf8"
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/src\/app\/globals.css$/),
expect.stringContaining(`@tailwind base`),
"utf8"
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
3,
expect.stringMatching(/src\/lib\/utils.ts$/),
expect.stringContaining(`import { type ClassValue, clsx } from "clsx"`),
"utf8"
)
expect(execa).toHaveBeenCalledWith(
"pnpm",
[
"add",
"tailwindcss-animate",
"class-variance-authority",
"clsx",
"tailwind-merge",
"@radix-ui/react-icons",
],
{
cwd: targetDir,
}
)
mockMkdir.mockRestore()
mockWriteFile.mockRestore()
})
test("init config-partial", async () => {
vi.spyOn(getPackageManger, "getPackageManager").mockResolvedValue("npm")
vi.spyOn(registry, "getRegistryBaseColor").mockResolvedValue({
inlineColors: {},
cssVars: {},
inlineColorsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
cssVarsTemplate:
"@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",
})
const mockMkdir = vi.spyOn(fs.promises, "mkdir").mockResolvedValue(undefined)
const mockWriteFile = vi.spyOn(fs.promises, "writeFile").mockResolvedValue()
const targetDir = path.resolve(__dirname, "../fixtures/config-partial")
const config = await getConfig(targetDir)
await runInit(targetDir, config)
expect(mockMkdir).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/src\/assets\/css$/),
expect.anything()
)
expect(mockMkdir).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/lib$/),
expect.anything()
)
expect(mockMkdir).toHaveBeenNthCalledWith(
3,
expect.stringMatching(/components$/),
expect.anything()
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/tailwind.config.ts$/),
expect.stringContaining(`import type { Config } from "tailwindcss"`),
"utf8"
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/src\/assets\/css\/tailwind.css$/),
expect.stringContaining(`@tailwind base`),
"utf8"
)
expect(mockWriteFile).toHaveBeenNthCalledWith(
3,
expect.stringMatching(/utils.ts$/),
expect.stringContaining(`import { type ClassValue, clsx } from "clsx"`),
"utf8"
)
expect(execa).toHaveBeenCalledWith(
"npm",
[
"install",
"tailwindcss-animate",
"class-variance-authority",
"clsx",
"tailwind-merge",
"lucide-react",
],
{
cwd: targetDir,
}
)
mockMkdir.mockRestore()
mockWriteFile.mockRestore()
})
afterEach(() => {
vi.resetAllMocks()
})
| shadcn-ui/ui/packages/cli/test/commands/init.test.ts | {
"file_path": "shadcn-ui/ui/packages/cli/test/commands/init.test.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 1851
} | 97 |
import { describe, expect, test } from "vitest"
import { applyPrefix } from "../../src/utils/transformers/transform-tw-prefix"
describe("apply tailwind prefix", () => {
test.each([
{
input: "bg-slate-800 text-gray-500",
output: "tw-bg-slate-800 tw-text-gray-500",
},
{
input: "hover:dark:bg-background dark:text-foreground",
output: "hover:dark:tw-bg-background dark:tw-text-foreground",
},
{
input:
"rounded-lg border border-slate-200 bg-white text-slate-950 shadow-sm dark:border-slate-800 dark:bg-slate-950 dark:text-slate-50",
output:
"tw-rounded-lg tw-border tw-border-slate-200 tw-bg-white tw-text-slate-950 tw-shadow-sm dark:tw-border-slate-800 dark:tw-bg-slate-950 dark:tw-text-slate-50",
},
{
input:
"text-red-500 border-red-500/50 dark:border-red-500 [&>svg]:text-red-500 text-red-500 dark:text-red-900 dark:border-red-900/50 dark:dark:border-red-900 dark:[&>svg]:text-red-900 dark:text-red-900",
output:
"tw-text-red-500 tw-border-red-500/50 dark:tw-border-red-500 [&>svg]:tw-text-red-500 tw-text-red-500 dark:tw-text-red-900 dark:tw-border-red-900/50 dark:dark:tw-border-red-900 dark:[&>svg]:tw-text-red-900 dark:tw-text-red-900",
},
{
input:
"flex h-full w-full items-center justify-center rounded-full bg-muted",
output:
"tw-flex tw-h-full tw-w-full tw-items-center tw-justify-center tw-rounded-full tw-bg-muted",
},
{
input:
"absolute right-4 top-4 bg-primary rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",
output:
"tw-absolute tw-right-4 tw-top-4 tw-bg-primary tw-rounded-sm tw-opacity-70 tw-ring-offset-background tw-transition-opacity hover:tw-opacity-100 focus:tw-outline-none focus:tw-ring-2 focus:tw-ring-ring focus:tw-ring-offset-2 disabled:tw-pointer-events-none data-[state=open]:tw-bg-secondary",
},
])(`applyTwPrefix($input) -> $output`, ({ input, output }) => {
expect(applyPrefix(input, "tw-")).toBe(output)
})
})
| shadcn-ui/ui/packages/cli/test/utils/apply-prefix.test.ts | {
"file_path": "shadcn-ui/ui/packages/cli/test/utils/apply-prefix.test.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 927
} | 98 |
import path from "path"
import fs from "fs-extra"
import { type PackageJson } from "type-fest"
export function getPackageInfo(
cwd: string = "",
shouldThrow: boolean = true
): PackageJson | null {
const packageJsonPath = path.join(cwd, "package.json")
return fs.readJSONSync(packageJsonPath, {
throws: shouldThrow,
}) as PackageJson
}
| shadcn-ui/ui/packages/shadcn/src/utils/get-package-info.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/src/utils/get-package-info.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 116
} | 99 |
body {
background-color: red;
}
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/next-app-src/other.css | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/next-app-src/other.css",
"repo_id": "shadcn-ui/ui",
"token_count": 13
} | 100 |
body {
background-color: red;
}
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/next-pages-src/src/pages/other.css | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/next-pages-src/src/pages/other.css",
"repo_id": "shadcn-ui/ui",
"token_count": 13
} | 101 |
import { Link } from "@remix-run/react";
export default function NoteIndexPage() {
return (
<p>
No note selected. Select a note on the left, or{" "}
<Link to="new" className="text-blue-500 underline">
create a new note.
</Link>
</p>
);
}
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/routes/notes._index.tsx | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/app/routes/notes._index.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 113
} | 102 |
import { defineConfig } from "vite"
import tsconfigPaths from "vite-tsconfig-paths"
export default defineConfig({
plugins: [tsconfigPaths()],
})
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix/vite.config.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/remix/vite.config.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 48
} | 103 |
import { type AppType } from "next/dist/shared/lib/utils";
import "~/styles/globals.css";
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default MyApp;
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/t3-pages/src/pages/_app.tsx | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/t3-pages/src/pages/_app.tsx",
"repo_id": "shadcn-ui/ui",
"token_count": 72
} | 104 |
/// <reference types="vite/client" />
| shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/vite/src/vite-env.d.ts | {
"file_path": "shadcn-ui/ui/packages/shadcn/test/fixtures/frameworks/vite/src/vite-env.d.ts",
"repo_id": "shadcn-ui/ui",
"token_count": 12
} | 105 |
"use client";
import Image from "next/image"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
export default function LoginForm() {
return (
<div className="w-full lg:grid lg:min-h-[600px] lg:grid-cols-0 xl:min-h-[800px] px-6 ">
<div className="flex items-center justify-center py-12">
<div className="mx-auto grid w-[400px] gap-6">
<div className="grid gap-2 text-center">
<img src="https://pub-0cd6f9d4131f4f79ac40219248ae64db.r2.dev/logo.svg" className="mx-auto size-8" alt="Logo" />
<h1 className="text-2xl font-semibold">Create an account</h1>
<p className="text-balance text-muted-foreground text-md">
Enter your email below to create your account
</p>
</div>
<div className="grid gap-4">
<div className="grid gap-2">
<Input
id="email"
type="email"
placeholder="m@example.com"
className="h-9"
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="h-9">
Register with Email
</Button>
{/* <Button variant="outline" className="w-full">
Login with Google
</Button> */}
</div>
<div className="mt-0 text-center text-sm">
<Link href="/login" className="underline underline-offset-4">
Don't have an account? Login
</Link>
</div>
</div>
</div>
<div className="hidden bg-transparent lg:block ">
{/* <Image
src="/placeholder.svg"
width="1920"
height="1080"
className="h-full w-full object-cover dark:brightness-[0.2] dark:grayscale"
/> */}
</div>
</div>
)
} | DarkInventor/easy-ui/app/(auth)/register/page.tsx | {
"file_path": "DarkInventor/easy-ui/app/(auth)/register/page.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 1282
} | 0 |
'use client'
import { useState, useEffect } from 'react'
import { ScrollArea } from "@/components/ui/scroll-area"
import { Menu, FileText, MessageSquare, LayoutDashboard, Palette, Book, Grid, Rocket, ShoppingCart, Mail, Box, Briefcase, Zap, Camera, BookOpen, List, Clock, Quote, ChevronRight, StickyNoteIcon, PaintBucketIcon, PuzzleIcon, Airplay, CloudMoonRain } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Button } from "@/components/ui/button"
import EzBlog from '../(docs)/ez-blog/page'
import EzChatbot from '../(docs)/ez-chatbot/page'
import EzDocs from '../(docs)/ez-dashboard/page'
import DesignPage from '../(docs)/ez-design/page'
import GridsPage from '../(docs)/ez-grids/page'
import EzNextUI from '../(docs)/ez-landing-docs/page'
import MarketplacePage from '../(docs)/ez-marketplace/page'
import StoryPage from '../(docs)/ez-newsletter/page'
import NotesPage from '../(docs)/ez-notes/page'
import EzPortfolio from '../(docs)/ez-portfolio/page'
import EzRed from '../(docs)/ez-red/page'
import EzShots from '../(docs)/ez-shots/page'
import EzPage from '../(docs)/ez-tmp/page'
import EzPage2 from '../(docs)/ez-tmp2/page'
import EzPage3 from '../(docs)/ez-tmp3/page'
import EzPage4 from '../(docs)/ez-tmp4/page'
import EzPage5 from '../(docs)/ez-tmp5/page'
import EzWaitlist from '../(docs)/ez-waitlist/page'
import QuotesAI from '../(docs)/quotesai/page'
import EzLandingDocs from '../(docs)/ez-landing-docs/page'
import EzNextUII from '../(docs)/ez-nextui/page'
import IntroductionPage from '../(docs)/introduction/page'
import DesignfastPage from '../(docs)/designfast/page'
import Retro from '../(docs)/retro/page'
import NewsletterPage from '../(docs)/ez-newsletter/page'
import EasyStory from '../(docs)/ez-story/page'
import EzDashboard from '../(docs)/ez-dashboard/page'
import EzDocss from '../(docs)/ez-docs/page'
import EzAI from '../(docs)/ez-ai/page'
import EzBeautiful from '../(docs)/ez-beautiful/page'
import { ShadowInnerIcon } from '@radix-ui/react-icons'
import EzIndigo from '../(docs)/ez-indigo/page'
interface Item {
name: string;
isNew?: boolean;
isPaid?: boolean;
}
const components: Item[] = [
{ name: 'introduction' },
{ name: 'ez-blog', isNew: true },
{ name: 'ez-chatbot' },
{ name: 'ez-dashboard' },
{ name: 'ez-design' },
{ name: 'ez-docs' },
{ name: 'ez-grids', isNew: true },
{ name: 'ez-landing-docs', isNew: true },
{ name: 'ez-marketplace' },
{ name: 'ez-newsletter', isNew: true },
{ name: 'ez-nextui' },
{ name: 'ez-notes', isNew: true },
{ name: 'ez-portfolio', isNew: true },
{ name: 'ez-red' },
{ name: 'ez-shots' },
{ name: 'ez-story', isNew: true },
{ name: 'ez-tmp', isNew: true },
{ name: 'ez-tmp2' },
{ name: 'ez-tmp3', isNew: true },
{ name: 'ez-tmp4', isNew: true },
{ name: 'ez-tmp5' },
{ name: 'ez-waitlist' },
{ name: 'quotesai' },
{ name: 'designfast'},
{ name: 'retro'},
{ name: 'ez-ai', isNew: true},
{ name: 'ez-beautiful', isNew: true},
{ name: 'ez-indigo', isNew: true},
]
export default function TemplatePage() {
const [selectedItem, setSelectedItem] = useState('introduction')
const [isLargeScreen, setIsLargeScreen] = useState(true)
useEffect(() => {
const checkScreenSize = () => {
setIsLargeScreen(window.innerWidth >= 1024)
}
checkScreenSize()
window.addEventListener('resize', checkScreenSize)
return () => window.removeEventListener('resize', checkScreenSize)
}, [])
const handleItemClick = (item: string) => {
setSelectedItem(item)
}
const renderComponent = (componentName: string) => {
switch (componentName) {
case 'introduction':
return <IntroductionPage />
case 'ez-blog':
return <EzBlog />
case 'ez-chatbot':
return <EzChatbot />
case 'ez-dashboard':
return <EzDashboard />
case 'ez-design':
return <DesignPage />
case 'ez-docs':
return <EzDocss />
case 'ez-grids':
return <GridsPage />
case 'ez-landing-docs':
return <EzLandingDocs />
case 'ez-marketplace':
return <MarketplacePage />
case 'ez-newsletter':
return <NewsletterPage />
case 'ez-nextui':
return <EzNextUII />
case 'ez-notes':
return <NotesPage />
case 'ez-portfolio':
return <EzPortfolio />
case 'ez-red':
return <EzRed />
case 'ez-shots':
return <EzShots />
case 'ez-story':
return <EasyStory />
case 'ez-tmp':
return <EzPage />
case 'ez-tmp2':
return <EzPage2 />
case 'ez-tmp3':
return <EzPage3 />
case 'ez-tmp4':
return <EzPage4 />
case 'ez-tmp5':
return <EzPage5 />
case 'ez-waitlist':
return <EzWaitlist />
case 'quotesai':
return <QuotesAI />
case 'designfast':
return <DesignfastPage />
case 'retro':
return <Retro />
case 'ez-ai':
return <EzAI />
case 'ez-beautiful':
return <EzBeautiful />
case 'ez-indigo':
return <EzIndigo />
default:
return <div>Component not found</div>
}
}
const getIcon = (name: string) => {
switch (name) {
case 'ez-blog': return <FileText className="mr-2 h-4 w-4" />
case 'ez-chatbot': return <MessageSquare className="mr-2 h-4 w-4" />
case 'ez-dashboard': return <LayoutDashboard className="mr-2 h-4 w-4" />
case 'ez-design': return <Palette className="mr-2 h-4 w-4" />
case 'ez-docs': return <Book className="mr-2 h-4 w-4" />
case 'ez-grids': return <Grid className="mr-2 h-4 w-4" />
case 'ez-landing-docs': return <Rocket className="mr-2 h-4 w-4" />
case 'ez-marketplace': return <ShoppingCart className="mr-2 h-4 w-4" />
case 'ez-newsletter': return <Mail className="mr-2 h-4 w-4" />
case 'ez-nextui': return <Box className="mr-2 h-4 w-4" />
case 'ez-notes': return <StickyNoteIcon className="mr-2 h-4 w-4" />
case 'ez-portfolio': return <Briefcase className="mr-2 h-4 w-4" />
case 'ez-red': return <Zap className="mr-2 h-4 w-4" />
case 'ez-shots': return <Camera className="mr-2 h-4 w-4" />
case 'ez-story': return <BookOpen className="mr-2 h-4 w-4" />
case 'ez-tmp': return <List className="mr-2 h-4 w-4" />
case 'ez-tmp2': return <List className="mr-2 h-4 w-4" />
case 'ez-tmp3': return <List className="mr-2 h-4 w-4" />
case 'ez-tmp4': return <List className="mr-2 h-4 w-4" />
case 'ez-tmp5': return <List className="mr-2 h-4 w-4" />
case 'ez-waitlist': return <Clock className="mr-2 h-4 w-4" />
case 'quotesai': return <Quote className="mr-2 h-4 w-4" />
case 'introduction': return <ChevronRight className="mr-2 h-4 w-4" />
case 'designfast': return <PaintBucketIcon className="mr-2 h-4 w-4" />
case 'retro': return <PuzzleIcon className="mr-2 h-4 w-4" />
case 'ez-ai': return <Airplay className="mr-2 h-4 w-4" />
case 'ez-beautiful': return <ShadowInnerIcon className="mr-2 h-4 w-4" />
case 'ez-indigo': return <CloudMoonRain className="mr-2 h-4 w-4" />
default: return <ChevronRight className="mr-2 h-4 w-4" />
}
}
const renderPaidBadge = (isNew?: boolean) => {
if (isNew) {
return <span className="ml-2 rounded-full bg-green-100 px-2 py-1 text-xs font-medium text-green-800">New</span>
}
return null
}
return (
<div className="flex flex h-screen">
{isLargeScreen ? (
<>
<ScrollArea className="w-64">
<div className="p-4">
<h2 className="mb-2 px-4 text-lg font-semibold tracking-tight">
Getting Started
</h2>
{components.map((item) => (
<Button
key={item.name}
variant={selectedItem === item.name ? 'secondary' : 'ghost'}
className="w-full justify-start"
onClick={() => handleItemClick(item.name)}
>
{getIcon(item.name)}
{item.name}
{renderPaidBadge(item.isNew)}
</Button>
))}
</div>
</ScrollArea>
<div className="flex-1 overflow-auto">
{renderComponent(selectedItem)}
</div>
</>
) : (
<div className="flex flex-col flex-1 overflow-auto h-screen">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full justify-between px-4 py-2">
<span className="flex items-center">
{getIcon(selectedItem)}
{selectedItem}
</span>
<Menu className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-screen max-h-[calc(100vh-200px)] overflow-auto h-screen">
{components.map((item) => (
<DropdownMenuItem key={item.name} onSelect={() => handleItemClick(item.name)}>
<span className="flex items-center w-full">
{getIcon(item.name)}
{item.name}
{renderPaidBadge(item.isNew)}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<div className="flex-1 px-1 overflow-auto">
{renderComponent(selectedItem)}
</div>
</div>
)}
{/* <footer className="py-4 px-6 bg-gray-100 dark:bg-gray-800">
<p className="text-center text-sm text-gray-600 dark:text-gray-400">
2024 Your Company. All rights reserved.
</p>
</footer> */}
</div>
)
} | DarkInventor/easy-ui/app/templates/page.tsx | {
"file_path": "DarkInventor/easy-ui/app/templates/page.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 4340
} | 1 |
import React, { CSSProperties, useEffect, useRef, useState } from "react"
import { Button } from "../ui/button"
const RANDOM = (min: number, max: number) =>
Math.floor(Math.random() * (max - min + 1) + min)
interface SparkleProps {
text: string
size: any
variant: any
}
const SparkleButton = ({ text, size, variant }: SparkleProps) => {
const [isActive, setIsActive] = useState(false)
const particlesRef = useRef<Array<HTMLDivElement | null>>([])
useEffect(() => {
particlesRef.current.forEach((P) => {
if (P) {
P.style.setProperty("--x", `${RANDOM(20, 80)}`)
P.style.setProperty("--y", `${RANDOM(20, 80)}`)
P.style.setProperty("--duration", `${RANDOM(6, 20)}`)
P.style.setProperty("--delay", `${RANDOM(1, 10)}`)
P.style.setProperty("--alpha", `${RANDOM(40, 90) / 100}`)
P.style.setProperty(
"--origin-x",
`${Math.random() > 0.5 ? RANDOM(300, 800) * -1 : RANDOM(300, 800)}%`
)
P.style.setProperty(
"--origin-y",
`${Math.random() > 0.5 ? RANDOM(300, 800) * -1 : RANDOM(300, 800)}%`
)
P.style.setProperty("--size", `${RANDOM(40, 90) / 100}`)
}
})
}, [])
return (
// @ts-ignore
<div className="flex h-full w-full items-center justify-center overflow-hidden bg-transparent">
<div className="sparkle-button relative">
<Button
className="relative text-sm py-3 px-5 rounded-full flex items-center gap-1 whitespace-nowrap transition-all duration-250 cursor-pointer"
onMouseEnter={() => setIsActive(true)}
onMouseLeave={() => setIsActive(false)}
size={size}
variant={variant}
style={
{
"--active": isActive ? "1" : "0",
"--cut": "0.1em",
background: `
radial-gradient(
40% 50% at center 100%,
hsl(270 calc(var(--active) * 97%) 72% / var(--active)),
transparent
),
radial-gradient(
80% 100% at center 120%,
hsl(260 calc(var(--active) * 97%) 70% / var(--active)),
transparent
),
hsl(260 calc(var(--active) * 97%) calc((var(--active) * 44%) + 12%))
`,
boxShadow: `
0 0 calc(var(--active) * 6em) calc(var(--active) * 3em) hsl(260 97% 61% / 0.75),
0 0.05em 0 0 hsl(260 calc(var(--active) * 97%) calc((var(--active) * 50%) + 30%)) inset,
0 -0.05em 0 0 hsl(260 calc(var(--active) * 97%) calc(var(--active) * 60%)) inset
`,
transform: `scale(calc(1 + (var(--active) * 0.1)))`,
} as CSSProperties
}
>
<span
className="text relative z-10 translate-x-[2%] -translate-y-[6%] "
style={{
background: `linear-gradient(90deg, hsl(0 0% calc((var(--active) * 100%) + 65%)), hsl(0 0% calc((var(--active) * 100%) + 26%)))`,
WebkitBackgroundClip: "text",
color: "transparent",
}}
>
{text}
</span>
<svg
className="sparkle w-6 h-6 ml-3 relative z-10 -translate-x-[25%] -translate-y-[5%]"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M10 7L15 12L10 17"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
style={{
color: `hsl(0 0% calc((var(--active, 0) * 70%) + 20%))`,
// animation: isActive ? 'bounce 0.6s' : 'none',
animationDelay: "calc((0.25s * 1.5) + (0.1s * 1s))",
// @ts-ignore
"--scale": "0.5",
}}
/>
<path
d="M15 12H3"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
style={{
color: `hsl(0 0% calc((var(--active, 0) * 70%) + 20%))`,
// animation: isActive ? 'bounce 0.6s' : 'none',
animationDelay: "calc((0.25s * 1.5) + (0.2s * 1s))",
// @ts-ignore
"--scale": "1.5",
}}
/>
</svg>
<div
className="spark absolute inset-0 rounded-full rotate-0 overflow-hidden"
style={{
mask: "linear-gradient(white, transparent 50%)",
animation: "flip 3.6s infinite steps(2, end)",
}}
>
<div
className="spark-rotate absolute w-[200%] aspect-square top-0 left-1/2 -translate-x-1/2 -translate-y-[15%] -rotate-90 animate-rotate"
style={{
opacity: `calc((var(--active)) + 0.4)`,
background:
"conic-gradient(from 0deg, transparent 0 340deg, white 360deg)",
}}
/>
</div>
<div
className="backdrop absolute rounded-full transition-all duration-250"
style={{
inset: "var(--cut)",
background: `
radial-gradient(
40% 50% at center 100%,
hsl(270 calc(var(--active) * 97%) 72% / var(--active)),
transparent
),
radial-gradient(
80% 100% at center 120%,
hsl(260 calc(var(--active) * 97%) 70% / var(--active)),
transparent
),
hsl(260 calc(var(--active) * 97%) calc((var(--active) * 44%) + 12%))
`,
}}
/>
</Button>
<div
className="particle-pen absolute w-[200%] aspect-square top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[-1]"
style={{
WebkitMask: "radial-gradient(white, transparent 65%)",
opacity: isActive ? "1" : "0",
transition: "opacity 0.25s",
}}
>
{[...Array(20)].map((_, index) => (
<div
key={index}
// @ts-ignore
ref={(el) => (particlesRef.current[index] = el)}
className="particle absolute animate-float-out"
style={
{
"--duration": `calc(var(--duration, 1) * 1s)`,
"--delay": `calc(var(--delay, 0) * -1s)`,
width: "calc(var(--size, 0.25) * 1rem)",
aspectRatio: "1",
top: "calc(var(--y, 50) * 1%)",
left: "calc(var(--x, 50) * 1%)",
opacity: "var(--alpha, 1)",
animationDirection: index % 2 === 0 ? "reverse" : "normal",
animationPlayState: isActive ? "running" : "paused",
transformOrigin:
"var(--origin-x, 1000%) var(--origin-y, 1000%)",
} as CSSProperties
}
>
<svg
width="100%"
height="100%"
viewBox="0 0 15 15"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M7.5 0L9.08257 5.17647L13.5 7.5L9.08257 9.82353L7.5 15L5.91743 9.82353L1.5 7.5L5.91743 5.17647L7.5 0Z"
fill="hsl(260, 97%, 61%)"
/>
</svg>
</div>
))}
</div>
</div>
</div>
)
}
export default SparkleButton
| DarkInventor/easy-ui/components/easyui/sparkle-button.tsx | {
"file_path": "DarkInventor/easy-ui/components/easyui/sparkle-button.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 4408
} | 2 |
import Link from "next/link"
import { cn } from "@/lib/utils"
interface CardProps extends React.HTMLAttributes<HTMLDivElement> {
href?: string
disabled?: boolean
}
export default function MdxCard({
href,
className,
children,
disabled,
...props
}: CardProps) {
return (
<div
className={cn(
"group relative rounded-lg border p-6 shadow-md transition-shadow hover:shadow-lg",
disabled && "cursor-not-allowed opacity-60",
className
)}
{...props}
>
<div className="flex flex-col justify-between space-y-4">
<div className="[&>p]:text-muted-foreground space-y-2 [&>h3]:!mt-0 [&>h4]:!mt-0">
{children}
</div>
</div>
{href && (
<Link href={disabled ? "#" : href} className="absolute inset-0">
<span className="sr-only">View</span>
</Link>
)}
</div>
)
} | DarkInventor/easy-ui/components/mdx-card.tsx | {
"file_path": "DarkInventor/easy-ui/components/mdx-card.tsx",
"repo_id": "DarkInventor/easy-ui",
"token_count": 395
} | 3 |
import { MainNav } from "@/app/(app)/_components/main-nav";
import { ThemeToggle } from "@/components/theme-toggle";
import { MoonIcon, SunIcon } from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button";
import { siteUrls } from "@/config/urls";
import Link from "next/link";
import { Icons } from "@/components/icons";
import { MobileNav } from "@/app/(app)/_components/mobile-nav";
export function SiteHeader() {
return (
<header className="sticky top-0 z-50 w-full border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="container flex h-14 max-w-screen-2xl items-center justify-between">
<div className="flex items-center gap-5">
<MobileNav />
<Link
href={siteUrls.marketing.base}
className="left-4 z-10"
>
<Icons.logo
classNameText="hidden sm:block"
iconProps={{
className:
"w-6 h-6 sm:w-5 sm:h-5 fill-foreground",
}}
/>
</Link>
<MainNav />
</div>
<nav className="flex items-center gap-2">
<Link
href={siteUrls.socials.twitter}
target="_blank"
className={buttonVariants({
variant: "outline",
size: "iconSm",
})}
>
<Icons.twitter className="h-4 w-4 fill-foreground" />
</Link>
<Link
href={siteUrls.socials.github}
target="_blank"
className={buttonVariants({
variant: "outline",
size: "iconSm",
})}
>
<Icons.gitHub className="h-4 w-4 fill-foreground" />
</Link>
<ThemeToggle
button={
<Button variant="outline" size="iconSm">
<SunIcon className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<MoonIcon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
}
/>
</nav>
</div>
</header>
);
}
| alifarooq9/rapidlaunch/apps/www/src/app/(app)/_components/side-header.tsx | {
"file_path": "alifarooq9/rapidlaunch/apps/www/src/app/(app)/_components/side-header.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 1759
} | 4 |
import type { MDXComponents } from "mdx/types";
import defaultComponents from "fumadocs-ui/mdx";
import { Step, Steps } from "fumadocs-ui/components/steps";
import { Tab, Tabs } from "fumadocs-ui/components/tabs";
import { TypeTable } from "fumadocs-ui/components/type-table";
import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
export function useMDXComponents(components?: MDXComponents): MDXComponents {
return {
Step,
Steps,
Tab,
Tabs,
TypeTable,
Accordion,
Accordions,
...defaultComponents,
...components,
};
}
| alifarooq9/rapidlaunch/starterkits/saas/mdx-components.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/mdx-components.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 264
} | 5 |
import { AppPageShell } from "@/app/(app)/_components/page-shell";
import { userFeedbackPageConfig } from "@/app/(app)/(user)/feedback/_constants/page-config";
import { CreateFeedbackForm } from "@/app/(app)/(user)/feedback/_components/create-feedback-form";
import { getUserFeedbacksQuery } from "@/server/actions/feedback/queries";
import {
Card,
CardContent,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import { format } from "date-fns";
import { Badge } from "@/components/ui/badge";
import { FeedbackDropdown } from "@/app/(app)/(user)/feedback/_components/feedback-dropdown";
import Balancer from "react-wrap-balancer";
export default async function UserFeedbackPage() {
const feedbacks = await getUserFeedbacksQuery();
return (
<AppPageShell
title={userFeedbackPageConfig.title}
description={userFeedbackPageConfig.description}
>
<div className="flex w-full items-start justify-between">
<h2 className="text-base font-medium sm:text-lg">
{feedbacks.length} feedbacks you have created.
</h2>
<CreateFeedbackForm />
</div>
<div className="grid gap-4">
{feedbacks.length > 0 ? (
feedbacks.map((feedback) => (
<Card key={feedback.id} className="relative">
<FeedbackDropdown {...feedback} />
<CardContent className="grid gap-3 p-6">
<CardTitle>{feedback.title}</CardTitle>
<CardDescription>
{feedback.message}
</CardDescription>
<p className="flex items-center gap-2 text-xs text-muted-foreground">
{format(
new Date(feedback.createdAt),
"PPP",
)}
</p>
<Badge variant="background" className="w-fit">
{feedback.label}
</Badge>
<Badge
variant={
feedback.status === "Open"
? "success"
: feedback.status === "In Progress"
? "info"
: "secondary"
}
className="w-fit"
>
{feedback.status}
</Badge>
</CardContent>
</Card>
))
) : (
<div className="flex w-full flex-col items-center justify-center gap-4 py-10">
<p className="font-medium text-muted-foreground">
No feedbacks found.
</p>
<Balancer
as="p"
className="text-center text-muted-foreground"
>
Create a feedback using the form above, your
feedback is important to us.
</Balancer>
</div>
)}
</div>
</AppPageShell>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/feedback/page.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/feedback/page.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 2264
} | 6 |
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { sendOrgInviteEmail } from "@/server/actions/send-org-invite-email";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Icons } from "@/components/ui/icons";
const formSchema = z.object({
email: z.string().email("Please enter a valid email address"),
});
type formSchemaType = z.infer<typeof formSchema>;
type SendInviteLinkProps = {
inviteLink: string;
orgName: string;
};
export function SendInviteLink({ inviteLink, orgName }: SendInviteLinkProps) {
const [isLoading, setIsLoading] = useState(false);
const [isSent, setIsSent] = useState(false);
const form = useForm<formSchemaType>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
},
});
const onSumbmit = async (data: formSchemaType) => {
setIsLoading(true);
const sendInvitePromise = () => sendOrgInviteEmail({
email: data.email,
orgName: orgName,
invLink: inviteLink
});
toast.promise(sendInvitePromise(), {
loading: 'Sending invite...',
success: () => {
setIsSent(true);
return "Invite sent";
},
error: 'Error sending invite',
finally() {
setIsLoading(false);
form.reset({ email: "" });
},
});
};
useEffect(() => {
let timeout: NodeJS.Timeout;
if (isSent) {
timeout = setTimeout(() => {
setIsSent(false);
}, 3000);
}
return () => {
clearTimeout(timeout);
};
}, [isSent]);
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSumbmit)}
className="flex gap-4 md:flex-row md:items-center md:justify-between"
>
<div className="flex w-full space-x-2">
<div className="w-full">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
className="bg-background w-full"
placeholder="hey@example.com"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<Button
disabled={isLoading}
aria-disabled={isLoading}
variant="secondary"
className="shrink-0"
type="submit"
>
{isLoading && <Icons.loader className="h-4 w-4 mr-2" />}
{isSent ? "Invite Sent" : "Send Invite"}
</Button>
</div>
</form>
</Form>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/members/invite/_components/send-invite-link.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/org/members/invite/_components/send-invite-link.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 2014
} | 7 |
"use client";
import { Button } from "@/components/ui/button";
import {
Card,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Icons } from "@/components/ui/icons";
import { siteUrls } from "@/config/urls";
import { useMutation } from "@tanstack/react-query";
import type { User } from "next-auth";
import { signIn } from "next-auth/react";
import { toast } from "sonner";
type UserVerifyFormProps = {
user: User;
};
export function UserVerifyForm({ user }: UserVerifyFormProps) {
const { isPending, mutate } = useMutation({
mutationFn: () =>
signIn("email", {
email: user.email,
redirect: false,
callbackUrl: siteUrls.profile.settings,
}),
onSuccess: () => {
toast.success("Verification email sent! Check your inbox.");
},
onError: (error) => {
toast.error(error.message || "Failed to send verification email");
},
});
return (
<Card>
<CardHeader>
<CardTitle>Verify your email</CardTitle>
<CardDescription>
Verify your email to enable all features
</CardDescription>
</CardHeader>
<CardFooter>
<Button
disabled={isPending}
onClick={() => mutate()}
className="gap-2"
>
{isPending ? <Icons.loader className="h-4 w-4" /> : null}
<span>Verify Email</span>
</Button>
</CardFooter>
</Card>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/profile/settings/_components/user-verify-form.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/(user)/profile/settings/_components/user-verify-form.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 840
} | 8 |
import { getUser } from "@/server/auth";
import { NewUserProfileForm } from "@/app/(app)/_components/new-user-profile-form";
import { NewUserOrgForm } from "@/app/(app)/_components/new-user-org-form";
import { cookies } from "next/headers";
import { new_user_setup_step_cookie } from "@/config/cookie-keys";
export async function NewUserSetup() {
const user = await getUser();
if (!user?.isNewUser) {
return null;
}
const currentStep =
cookies().get(`${new_user_setup_step_cookie}${user.id}`)?.value ?? 1;
const forms = {
1: <NewUserProfileForm user={user} currentStep={Number(currentStep)} />,
2: (
<NewUserOrgForm
currentStep={Number(currentStep)}
userId={user?.id}
/>
),
};
return (
<div className="fixed inset-0 flex h-screen w-screen flex-col items-center justify-center bg-black/80">
<div className="w-full max-w-xl">
{forms[currentStep as keyof typeof forms]}
</div>
</div>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/_components/new-user-setup.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/_components/new-user-setup.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 470
} | 9 |
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
"use client";
import { type ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import { ColumnDropdown } from "@/app/(app)/admin/feedbacks/_components/column-dropdown";
import { FeedbackDetails } from "@/app/(app)/admin/feedbacks/_components/feedback-details";
import { format } from "date-fns";
import type { getAllPaginatedFeedbacksQuery } from "@/server/actions/feedback/queries";
// This type is used to define the shape of our data.
// You can use a Zod schema here if you want.
export type FeedbackData = Awaited<
ReturnType<typeof getAllPaginatedFeedbacksQuery>
>["data"][number];
export function getColumns(): ColumnDef<FeedbackData>[] {
return columns;
}
export const columns: ColumnDef<FeedbackData>[] = [
{
accessorKey: "idx",
header: () => <span className="px-1">IDX</span>,
cell: ({ row }) => (
<span className="px-2 text-center">{row.index + 1}</span>
),
},
{
accessorKey: "title",
header: "Title",
cell: ({ row }) => <FeedbackDetails {...row.original} />,
},
{
accessorKey: "email",
header: "User Email",
cell: ({ row }) => {
return row.original.user.email;
},
},
{
accessorKey: "label",
header: "Label",
cell: ({ row }) => (
<Badge variant="secondary" className="capitalize">
{row.original.label}
</Badge>
),
filterFn: (row, id, value) => {
return !!value.includes(row.getValue(id));
},
},
{
accessorKey: "status",
header: "Status",
cell: ({ row }) => (
<Badge
variant={
row.original.status === "Open"
? "success"
: row.original.status === "In Progress"
? "info"
: "secondary"
}
className="capitalize"
>
{row.original.status}
</Badge>
),
filterFn: (row, id, value) => {
return !!value.includes(row.getValue(id));
},
},
{
accessorKey: "createdAt",
header: "Created At",
cell: ({ row }) => (
<span className="text-muted-foreground">
{format(new Date(row.original.createdAt), "PP")}
</span>
),
},
{
id: "actions",
cell: ({ row }) => <ColumnDropdown {...row.original} />,
},
];
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/feedbacks/_components/columns.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/feedbacks/_components/columns.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 1305
} | 10 |
"use client";
import { DataTable } from "@/app/(app)/_components/data-table";
import { type ColumnDef } from "@tanstack/react-table";
import React, { useMemo } from "react";
import { getColumns, type UsersData } from "./columns";
import { usersRoleEnum } from "@/server/db/schema";
import { useDataTable } from "@/hooks/use-data-table";
import type {
DataTableFilterableColumn,
DataTableSearchableColumn,
} from "@/types/data-table";
import { type getPaginatedUsersQuery } from "@/server/actions/user/queries";
/** @learn more about data-table at shadcn ui website @see https://ui.shadcn.com/docs/components/data-table */
const filterableColumns: DataTableFilterableColumn<UsersData>[] = [
{
id: "role",
title: "Role",
options: usersRoleEnum.enumValues.map((v) => ({
label: v,
value: v,
})),
},
];
type UsersTableProps = {
usersPromise: ReturnType<typeof getPaginatedUsersQuery>;
};
const searchableColumns: DataTableSearchableColumn<UsersData>[] = [
{ id: "email", placeholder: "Search email..." },
];
export function UsersTable({ usersPromise }: UsersTableProps) {
const { data, pageCount, total } = React.use(usersPromise);
const columns = useMemo<ColumnDef<UsersData, unknown>[]>(
() => getColumns(),
[],
);
const usersData: UsersData[] = data.map((user) => {
return {
id: user.id,
name: user.name,
email: user.email,
role: user.role,
status: user.emailVerified ? "verified" : "unverified",
createdAt: user.createdAt,
};
});
const { table } = useDataTable({
data: usersData,
columns,
pageCount,
searchableColumns,
filterableColumns,
});
return (
<DataTable
table={table}
columns={columns}
filterableColumns={filterableColumns}
searchableColumns={searchableColumns}
totalRows={total}
/>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/users/_components/users-table.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(app)/admin/users/_components/users-table.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 861
} | 11 |
import { buttonVariants } from "@/components/ui/button";
import { siteUrls } from "@/config/urls";
import { getUser } from "@/server/auth";
import Link from "next/link";
import { Fragment } from "react";
export async function HeaderAuth() {
const user = await getUser();
return (
<section className="flex items-center space-x-2">
{user ? (
<Link
href={siteUrls.dashboard.home}
className={buttonVariants({
className: "flex items-center space-x-1",
})}
>
<span>Dashboard</span>
</Link>
) : (
<Fragment>
<Link
href={siteUrls.auth.signup}
className={buttonVariants({
className: "flex items-center space-x-1",
})}
>
<span>Sign Up</span>
<span className="font-light italic">
{" "}
it's free
</span>
</Link>
</Fragment>
)}
</section>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(web)/_components/header-auth.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(web)/_components/header-auth.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 777
} | 12 |
import { siteConfig } from "@/config/site";
export const supportPageConfig = {
title: "Support",
description: `Get support from ${siteConfig.name} to get started building your next project.`,
} as const;
| alifarooq9/rapidlaunch/starterkits/saas/src/app/(web)/support/_constants/page-config.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/(web)/support/_constants/page-config.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 61
} | 13 |
export const invitePageConfig = {
title: ({ orgName }: { orgName: string }) => `Invite to ${orgName}`,
description: ({ orgName }: { orgName: string }) =>
`Invite your team to ${orgName} and get started building your next project.`,
} as const;
| alifarooq9/rapidlaunch/starterkits/saas/src/app/invite/org/[orgId]/_constants/page-config.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/app/invite/org/[orgId]/_constants/page-config.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 85
} | 14 |
"use client";
import { Slot } from "@radix-ui/react-slot";
import { signOut } from "next-auth/react";
import React from "react";
type SignoutTriggerProps = {
callbackUrl?: string;
redirect?: boolean;
asChild?: boolean;
children?: React.ReactNode;
} & React.HTMLAttributes<HTMLButtonElement>;
export function SignoutTrigger({
callbackUrl,
redirect = true,
asChild,
children,
...props
}: SignoutTriggerProps) {
const Comp = asChild ? Slot : "button";
return (
<Comp
onClick={async () => await signOut({ callbackUrl, redirect })}
{...props}
>
{children}
</Comp>
);
}
| alifarooq9/rapidlaunch/starterkits/saas/src/components/signout-trigger.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/components/signout-trigger.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 275
} | 15 |
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-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Input.displayName = "Input";
export { Input };
| alifarooq9/rapidlaunch/starterkits/saas/src/components/ui/input.tsx | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/components/ui/input.tsx",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 393
} | 16 |
/**
* @purpose Contains the navigation items for the header.
* The headerNav array contains the navigation items for the header.
*
* To Add a new navigation item:
* 1. Add a new object to the headerNav array with the following properties:
* - id: A unique string identifier for the navigation item.
* - href: The URL for the navigation item.
* - label: The label for the navigation item.
* - badge: (Optional) A badge to display next to the navigation item.
* 2. Import the siteUrls object from "@/config/urls".
* 3. Add the URL for the navigation item to the siteUrls object.
*/
import { siteUrls } from "@/config/urls";
interface NavigationItem {
id: string;
href: string;
label: string;
badge?: string;
external?: boolean;
}
export const navigation: NavigationItem[] = [
{
id: "pricing",
href: siteUrls.pricing,
label: "Pricing",
badge: "Beta",
},
{
id: "support",
href: siteUrls.support,
label: "Support",
},
{
id: "blogs",
href: siteUrls.blogs,
label: "Blogs",
},
{
id: "docs",
href: siteUrls.docs,
label: "Docs",
},
{
id: "changelogs",
href: siteUrls.changelogs,
label: "Changelogs",
},
];
| alifarooq9/rapidlaunch/starterkits/saas/src/config/header.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/config/header.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 517
} | 17 |
"use server";
import { db } from "@/server/db";
import {
feedback,
feedbackInsertSchema,
feedbackSelectSchema,
} from "@/server/db/schema";
import { adminProcedure, protectedProcedure } from "@/server/procedures";
import { and, eq } from "drizzle-orm";
import type { z } from "zod";
/**
* Create a new feedback
* @params title - The title of the feedback
* @params message - The message of the feedback
* @params label - The label of the feedback
*/
const feedbackFormSchema = feedbackInsertSchema.pick({
title: true,
message: true,
label: true,
id: true,
});
type CreateFeedbackProps = z.infer<typeof feedbackFormSchema>;
export async function createFeedbackMutation(props: CreateFeedbackProps) {
const { user } = await protectedProcedure();
const feedbackParse = await feedbackFormSchema.safeParseAsync(props);
if (!feedbackParse.success) {
throw new Error("Invalid feedback", {
cause: feedbackParse.error.errors,
});
}
return await db
.insert(feedback)
.values({
userId: user.id,
...feedbackParse.data,
})
.onConflictDoUpdate({
target: feedback.id,
set: feedbackParse.data,
})
.execute();
}
/**
* Remove a feedback
* @params id - The id of the feedback
*/
export async function removeUserFeedbackMutation({ id }: { id: string }) {
const { user } = await protectedProcedure();
if (!id) throw new Error("Invalid feedback id");
const feedbackData = await db.query.feedback.findFirst({
where: and(eq(feedback.id, id), eq(feedback.userId, user.id)),
});
if (!feedbackData) {
throw new Error("Feedback not found");
}
return await db.delete(feedback).where(eq(feedback.id, id)).execute();
}
/**
* Update a feedback
* @params id - The id of the feedback
* @params status - The status of the feedback
* @params label - The label of the feedback
*
*/
const feedbackUpdateSchema = feedbackSelectSchema.pick({
id: true,
status: true,
label: true,
});
type UpdateFeedbackProps = z.infer<typeof feedbackUpdateSchema>;
export async function updateFeedbackMutation(props: UpdateFeedbackProps) {
await adminProcedure();
const feedbackParse = await feedbackUpdateSchema.safeParseAsync(props);
if (!feedbackParse.success) {
throw new Error("Invalid feedback", {
cause: feedbackParse.error.errors,
});
}
return await db
.update(feedback)
.set(feedbackParse.data)
.where(eq(feedback.id, feedbackParse.data.id))
.execute();
}
/**
* delete feedback by id
* @params id - The id of the feedback
*/
export async function deleteFeedbackMutation({ id }: { id: string }) {
await adminProcedure();
if (!id) throw new Error("Invalid feedback id");
return await db.delete(feedback).where(eq(feedback.id, id)).execute();
}
| alifarooq9/rapidlaunch/starterkits/saas/src/server/actions/feedback/mutations.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/server/actions/feedback/mutations.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 1092
} | 18 |
"use server";
/**
* @purpose This file contains all the server procedures
*/
import { getUser } from "@/server/auth";
import { type User } from "next-auth";
import { usersRoleEnum } from "@/server/db/schema";
import { z } from "zod";
const userRoles = z.enum(usersRoleEnum.enumValues);
/**
* @purpose This is a protected procedure
* @description This procedure is protected and can only be accessed by authenticated users
* */
export const protectedProcedure = async () => {
const user = await getUser();
if (!user) {
throw new Error("You is not authenticated");
}
return {
user: user as User,
};
};
/**
* @purpose This is an admin procedure
* @description This procedure is protected and can only be accessed by admins
* */
export const adminProcedure = async () => {
const user = await getUser();
if (
user &&
user.role !== userRoles.Values.Admin &&
user.role !== userRoles.Values["Super Admin"]
) {
throw new Error("You are not authorized to perform this action");
}
return {
user: user as User,
};
};
/**
* @purpose This is a super admin procedure
* @description This procedure is protected and can only be accessed by super admins
* */
export const superAdminProcedure = async () => {
const user = await getUser();
if (user && user.role !== userRoles.Values["Super Admin"]) {
throw new Error("You are not authorized to perform this action");
}
return {
user: user as User,
};
};
| alifarooq9/rapidlaunch/starterkits/saas/src/server/procedures.ts | {
"file_path": "alifarooq9/rapidlaunch/starterkits/saas/src/server/procedures.ts",
"repo_id": "alifarooq9/rapidlaunch",
"token_count": 512
} | 19 |
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
import { NextResponse } from 'next/server';
const s3Client = new S3Client({
region: process.env.NEXT_PUBLIC_AWS_S3_REGION,
credentials: {
accessKeyId: process.env.NEXT_PUBLIC_AWS_S3_ACCESS_KEY_ID,
secretAccessKey: process.env.NEXT_PUBLIC_AWS_S3_SECRET_ACCESS_KEY,
},
});
const downloadFileToS3 = async (fileName, userId) => {
const command = new GetObjectCommand({
Bucket: process.env.NEXT_PUBLIC_AWS_S3_BUCKET_NAME,
Key: `${userId}/${fileName}`,
});
try {
const response = await s3Client.send(command);
const str = await response.Body.transformToByteArray();
return str;
} catch (err) {
console.error(err);
}
};
// -------------- POST function to get user ID --------------
export async function POST(request, res) {
try {
const formData = await request.formData();
const userId = formData.get('userId');
const filename = 'speech.mp3';
const mp3Data = await downloadFileToS3(filename, userId);
return NextResponse.json(mp3Data);
} catch (error) {
return NextResponse.json({ error });
}
}
| horizon-ui/shadcn-nextjs-boilerplate/app/api/s3-download/route.js | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/app/api/s3-download/route.js",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 419
} | 20 |
'use client';
import LineChart from '@/components/charts/LineChart';
import { Card } from '@/components/ui/card';
import { lineChartDataMain, lineChartOptionsMain } from '@/variables/charts';
import { HiChartBar } from 'react-icons/hi2';
function OverallRevenue() {
const newOptions = {
...lineChartOptionsMain
};
return (
<Card className={'border-zinc-200 p-6 dark:border-zinc-800 w-full'}>
<div className="flex items-center gap-3">
<div className="flex h-14 w-14 items-center justify-center rounded-full border border-zinc-200 text-4xl dark:border-zinc-800 dark:text-white">
<HiChartBar className="h-5 w-5" />
</div>
<div>
<h5 className="text-sm font-medium leading-5 text-zinc-950 dark:text-white">
Credits usage in the last year
</h5>
<p className="mt-1 text-2xl font-bold leading-6 text-zinc-950 dark:text-white">
149,758
</p>
</div>
</div>
{/* Charts */}
<div className="flex h-[350px] w-full flex-row sm:flex-wrap lg:flex-nowrap 2xl:overflow-hidden">
<div className="h-full w-full">
<LineChart chartData={lineChartDataMain} chartOptions={newOptions} />
</div>
</div>
</Card>
);
}
export default OverallRevenue;
| horizon-ui/shadcn-nextjs-boilerplate/components/dashboard/main/cards/MainChart.tsx | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/components/dashboard/main/cards/MainChart.tsx",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 565
} | 21 |
'use client';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import {
renderThumb,
renderTrack,
renderView
} from '@/components/scrollbar/Scrollbar';
import Links from '@/components/sidebar/components/Links';
import SidebarCard from '@/components/sidebar/components/SidebarCard';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Card } from '@/components/ui/card';
import { IRoute } from '@/types/types';
import { useRouter } from 'next/navigation';
import React, { PropsWithChildren, useContext } from 'react';
import { Scrollbars } from 'react-custom-scrollbars-2';
import { HiX } from 'react-icons/hi';
import { HiBolt } from 'react-icons/hi2';
import { HiOutlineArrowRightOnRectangle } from 'react-icons/hi2';
import { getRedirectMethod } from '@/utils/auth-helpers/settings';
import { UserContext, UserDetailsContext } from '@/contexts/layout';
import { createClient } from '@/utils/supabase/client';
const supabase = createClient();
export interface SidebarProps extends PropsWithChildren {
routes: IRoute[];
[x: string]: any;
}
function Sidebar(props: SidebarProps) {
const router = getRedirectMethod() === 'client' ? useRouter() : null;
const { routes } = props;
const user = useContext(UserContext);
const userDetails = useContext(UserDetailsContext);
const handleSignOut = async (e) => {
e.preventDefault();
supabase.auth.signOut();
router.push('/dashboard/signin');
};
// SIDEBAR
return (
<div
className={`lg:!z-99 fixed !z-[99] min-h-full w-[300px] transition-all md:!z-[99] xl:!z-0 ${
props.variant === 'auth' ? 'xl:hidden' : 'xl:block'
} ${props.open ? '' : '-translate-x-[120%] xl:translate-x-[unset]'}`}
>
<Card
className={`m-3 ml-3 h-[96.5vh] w-full overflow-hidden !rounded-lg border-zinc-200 pe-4 dark:border-zinc-800 sm:my-4 sm:mr-4 md:m-5 md:mr-[-50px]`}
>
<Scrollbars
autoHide
renderTrackVertical={renderTrack}
renderThumbVertical={renderThumb}
renderView={renderView}
>
<div className="flex h-full flex-col justify-between">
<div>
<span
className="absolute top-4 block cursor-pointer text-zinc-200 dark:text-white/40 xl:hidden"
onClick={() => props.setOpen(false)}
>
<HiX />
</span>
<div className={`mt-8 flex items-center justify-center`}>
<div className="me-2 flex h-[40px] w-[40px] items-center justify-center rounded-md bg-zinc-950 text-white dark:bg-white dark:text-zinc-950">
<HiBolt className="h-5 w-5" />
</div>
<h5 className="me-2 text-2xl font-bold leading-5 text-zinc-950 dark:text-white">
Horizon AI
</h5>
<Badge
variant="outline"
className="my-auto w-max px-2 py-0.5 text-xs text-zinc-950 dark:border-none dark:bg-zinc-800 dark:text-white"
>
FREE
</Badge>
</div>
<div className="mb-8 mt-8 h-px bg-zinc-200 dark:bg-white/10" />
{/* Nav item */}
<ul>
<Links routes={routes} />
</ul>
</div>
{/* Free Horizon Card */}
<div className="mb-9 mt-7">
<div className="flex justify-center">
<SidebarCard />
</div>
{/* Sidebar profile info */}
<div className="mt-5 flex w-full items-center rounded-lg border border-zinc-200 p-4 dark:border-zinc-800">
<a href="/dashboard/dashboard/settings">
<Avatar className="min-h-10 min-w-10">
<AvatarImage src={user?.user_metadata.avatar_url} />
<AvatarFallback className="font-bold dark:text-zinc-950">
{/* {userDetails.full_name
? `${userDetails.full_name[0]}`
: `${user?.user_metadata.email[0].toUpperCase()}`} */}
</AvatarFallback>
</Avatar>
</a>
<a href="/dashboard/settings">
<p className="ml-2 mr-3 flex items-center text-sm font-semibold leading-none text-zinc-950 dark:text-white">
{userDetails?.full_name ||
user?.user_metadata?.full_name ||
'User'}
</p>
</a>
<Button
onClick={(e) => handleSignOut(e)}
variant="outline"
className="ml-auto flex h-[40px] w-[40px] cursor-pointer items-center justify-center rounded-full p-0 text-center text-sm font-medium hover:dark:text-white"
type="submit"
>
<HiOutlineArrowRightOnRectangle
className="h-4 w-4 stroke-2 text-zinc-950 dark:text-white"
width="16px"
height="16px"
color="inherit"
/>
</Button>
</div>
</div>
</div>
</Scrollbars>
</Card>
</div>
);
}
// PROPS
export default Sidebar;
| horizon-ui/shadcn-nextjs-boilerplate/components/sidebar/Sidebar.tsx | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/components/sidebar/Sidebar.tsx",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 2713
} | 22 |
import endent from 'endent';
import {
createParser,
ParsedEvent,
ReconnectInterval,
} from 'eventsource-parser';
const createPrompt = (inputMessage: string) => {
const data = (inputMessage: string) => {
return endent`
You are ChatGPT, but if you are asked what your name is, you present yourself as Horizon UI Boilerplate and you can be bought from your website https://horizon-ui.com/boilerplate, and the link should be bold. Also, you are very friendly and formal. The generated content must be in markdown format and it must include all markdown characteristics, but it shouldn't be rendered. The title must be bold, and there should be a between every paragraph or title. Do not include information about console logs or print messages.
${inputMessage}
`;
};
if (inputMessage) {
return data(inputMessage);
}
};
export async function OpenAIStream (
inputMessage: string,
model: string,
key: string | undefined,
) {
const prompt = createPrompt(inputMessage);
const system = { role: 'system', content: prompt };
const res = await fetch(`https://api.openai.com/v1/chat/completions`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${key || process.env.NEXT_PUBLIC_OPENAI_API_KEY}`,
},
method: 'POST',
body: JSON.stringify({
model,
messages: [system],
temperature: 0,
stream: true,
}),
});
const encoder = new TextEncoder();
const decoder = new TextDecoder();
if (res.status !== 200) {
const statusText = res.statusText;
const result = await res.body?.getReader().read();
throw new Error(
`OpenAI API returned an error: ${
decoder.decode(result?.value) || statusText
}`,
);
}
const stream = new ReadableStream({
async start(controller) {
const onParse = (event: ParsedEvent | ReconnectInterval) => {
if (event.type === 'event') {
const data = event.data;
if (data === '[DONE]') {
controller.close();
return;
}
try {
const json = JSON.parse(data);
const text = json.choices[0].delta.content;
const queue = encoder.encode(text);
controller.enqueue(queue);
} catch (e) {
controller.error(e);
}
}
};
const parser = createParser(onParse);
for await (const chunk of res.body as any) {
parser.feed(decoder.decode(chunk));
}
},
});
return stream;
};
| horizon-ui/shadcn-nextjs-boilerplate/utils/chatStream.ts | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/utils/chatStream.ts",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 970
} | 23 |
type RowObj = {
item: string;
quantity: number;
rate: number;
amount: number;
};
const tableDataInvoice: RowObj[] = [
{
item: 'Premium Support',
quantity: 1,
rate: 9.0,
amount: 9.0
},
{
item: 'Horizon UI - Dashboard PRO',
quantity: 3,
rate: 99.0,
amount: 297.0
},
{
item: 'Parts for Service',
quantity: 1,
rate: 89.0,
amount: 89.0
}
];
export default tableDataInvoice;
| horizon-ui/shadcn-nextjs-boilerplate/variables/tableDataInvoice.ts | {
"file_path": "horizon-ui/shadcn-nextjs-boilerplate/variables/tableDataInvoice.ts",
"repo_id": "horizon-ui/shadcn-nextjs-boilerplate",
"token_count": 183
} | 24 |
import { defineConfig, devices } from '@playwright/test';
// Use process.env.PORT by default and fallback to port 3000
const PORT = process.env.PORT || 3000;
// Set webServer.url and use.baseURL with the location of the WebServer respecting the correct set port
const baseURL = `http://localhost:${PORT}`;
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests',
// Look for files with the .spec.js or .e2e.js extension
testMatch: '*.@(spec|e2e).?(c|m)[jt]s?(x)',
// Timeout per test
timeout: 30 * 1000,
// Fail the build on CI if you accidentally left test.only in the source code.
forbidOnly: !!process.env.CI,
// Reporter to use. See https://playwright.dev/docs/test-reporters
reporter: process.env.CI ? 'github' : 'list',
expect: {
// Set timeout for async expect matchers
timeout: 10 * 1000,
},
// Run your local dev server before starting the tests:
// https://playwright.dev/docs/test-advanced#launching-a-development-web-server-during-the-tests
webServer: {
command: process.env.CI ? 'npm run start' : 'npm run dev:next',
url: baseURL,
timeout: 2 * 60 * 1000,
reuseExistingServer: !process.env.CI,
},
// Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions.
use: {
// Use baseURL so to make navigations relative.
// More information: https://playwright.dev/docs/api/class-testoptions#test-options-base-url
baseURL,
// Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer
trace: process.env.CI ? 'retain-on-failure' : undefined,
// Record videos when retrying the failed test.
video: process.env.CI ? 'retain-on-failure' : undefined,
},
projects: [
// `setup` and `teardown` are used to run code before and after all E2E tests.
// These functions can be used to configure Clerk for testing purposes. For example, bypassing bot detection.
// In the `setup` file, you can create an account in `Test mode`.
// For each test, an organization can be created within this account to ensure total isolation.
// After all tests are completed, the `teardown` file can delete the account and all associated organizations.
// You can find the `setup` and `teardown` files at: https://nextjs-boilerplate.com/pro-saas-starter-kit
{ name: 'setup', testMatch: /.*\.setup\.ts/, teardown: 'teardown' },
{ name: 'teardown', testMatch: /.*\.teardown\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
dependencies: ['setup'],
},
...(process.env.CI
? [
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
dependencies: ['setup'],
},
]
: []),
],
});
| ixartz/SaaS-Boilerplate/playwright.config.ts | {
"file_path": "ixartz/SaaS-Boilerplate/playwright.config.ts",
"repo_id": "ixartz/SaaS-Boilerplate",
"token_count": 983
} | 25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.