{ "name": "color-swatch", "type": "registry:ui", "files": [ { "path": "ui/color-swatch.tsx", "type": "registry:ui", "content": "\"use client\";\n\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { useRender } from \"@base-ui/react/use-render\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport * as React from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nconst colorSwatchVariants = cva(\n \"box-border rounded-sm border bg-clip-padding shadow-sm data-disabled:pointer-events-none data-disabled:opacity-50\",\n {\n variants: {\n size: {\n default: \"size-8\",\n sm: \"size-6\",\n lg: \"size-12\",\n },\n },\n defaultVariants: {\n size: \"default\",\n },\n },\n);\n\nfunction getIsCssColor(v: string): boolean {\n try {\n return typeof CSS !== \"undefined\" && typeof CSS.supports === \"function\"\n ? CSS.supports(\"color\", v)\n : true;\n } catch {\n return false;\n }\n}\n\nfunction getHasAlpha(v: string): boolean {\n const s = v.trim().toLowerCase();\n\n if (s === \"transparent\") return true;\n\n if (/^#(?:[0-9a-f]{4}|[0-9a-f]{8})$/i.test(s)) return true;\n\n if (/\\b(?:rgba|hsla)\\s*\\(/i.test(s)) return true;\n\n if (\n /\\b(?:rgb|hsl|lab|lch|oklab|oklch|color)\\s*\\([^)]*\\/\\s*[\\d.]+%?\\s*\\)/i.test(\n s,\n )\n ) {\n return true;\n }\n\n return false;\n}\n\ninterface ColorSwatchProps\n extends Omit, \"children\">,\n VariantProps,\n useRender.ComponentProps<\"div\"> {\n color?: string;\n disabled?: boolean;\n withoutTransparency?: boolean;\n}\n\nfunction ColorSwatch({\n color,\n size = \"default\",\n disabled = false,\n withoutTransparency = false,\n className,\n style,\n render,\n ...props\n}: ColorSwatchProps) {\n const colorValue = color?.trim();\n\n const backgroundStyle = React.useMemo(() => {\n if (!colorValue) {\n return {\n background:\n \"linear-gradient(to bottom right, transparent calc(50% - 1px), hsl(var(--destructive)) calc(50% - 1px) calc(50% + 1px), transparent calc(50% + 1px)) no-repeat\",\n };\n }\n\n if (!getIsCssColor(colorValue)) {\n return { backgroundColor: \"transparent\" };\n }\n\n if (!withoutTransparency && getHasAlpha(colorValue)) {\n return {\n background: `linear-gradient(${colorValue}, ${colorValue}), repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0% 50% / 10px 10px`,\n };\n }\n\n return { backgroundColor: colorValue };\n }, [colorValue, withoutTransparency]);\n\n const ariaLabel = !colorValue\n ? \"No color selected\"\n : `Color swatch: ${colorValue}`;\n\n return useRender({\n defaultTagName: \"div\",\n props: mergeProps<\"div\">(\n {\n role: \"img\",\n \"aria-label\": ariaLabel,\n \"aria-disabled\": disabled || undefined,\n className: cn(colorSwatchVariants({ size }), className),\n style: {\n ...backgroundStyle,\n forcedColorAdjust: \"none\",\n ...style,\n },\n },\n props,\n ),\n render,\n state: {\n slot: \"color-swatch\",\n ...(disabled && { disabled: \"\" }),\n },\n });\n}\n\nexport { ColorSwatch };\n", "target": "" } ], "dependencies": [ "@base-ui/react" ] }