{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "crt-screen",
  "title": "CRT screen",
  "description": "A realistic CRT filter to really take your UI back in time. Fully customizable.",
  "dependencies": [
    "cn"
  ],
  "registryDependencies": [
    "@ui95/shader-mount",
    "@ui95/use-prefers-reduced-motion"
  ],
  "files": [
    {
      "path": "lib/shaders/crt.ts",
      "content": "import { BARREL_REACH } from \"../crt/warp-filter\"\nimport type { ShaderMotionParams, ShaderPreset } from \"./types\"\n\nexport const crtFragmentShader = `#version 300 es\nprecision highp float;\n\nuniform float u_time;\nuniform vec2 u_resolution;\nuniform float u_pxSize;\nuniform float u_pixelRatio;\nuniform float u_fps;\nuniform float u_scanlines;\nuniform float u_scanlineDensity;\nuniform float u_noise;\nuniform float u_vignette;\nuniform float u_mask;\nuniform float u_flicker;\nuniform float u_curvature;\nuniform float u_roll;\n\nout vec4 fragColor;\n\nconst float TAU = 6.2831853;\nconst float BARREL_REACH = ${BARREL_REACH.toFixed(3)};\n\nfloat readHash(vec3 point) {\n  vec3 scaled = fract(point * vec3(0.1031, 0.103, 0.0973));\n  scaled += dot(scaled, scaled.yxz + 33.33);\n  return fract((scaled.x + scaled.y) * scaled.z);\n}\n\nvec2 readBarrelShift(vec2 unit) {\n  float reach = u_curvature * BARREL_REACH;\n  float radiusSquared = dot(unit, unit) * 0.5;\n  return unit * reach * (radiusSquared - 1.0) / (1.0 + reach);\n}\n\nfloat readBoxDistance(vec2 point, vec2 halfSize, float radius) {\n  vec2 inner = abs(point) - halfSize + radius;\n  return length(max(inner, 0.0)) + min(max(inner.x, inner.y), 0.0) - radius;\n}\n\nvec4 readLayer(vec3 color, float alpha) {\n  return vec4(color * alpha, alpha);\n}\n\nvec4 stack(vec4 top, vec4 bottom) {\n  return top + bottom * (1.0 - top.a);\n}\n\nvec4 readMask(vec2 fragment) {\n  float stripe = mod(floor(fragment.x / max(u_pixelRatio, 1.0)), 3.0);\n  vec3 phosphor = stripe < 0.5 ? vec3(1.0, 0.0, 0.0) : stripe < 1.5 ? vec3(0.0, 1.0, 0.0) : vec3(0.0, 0.0, 1.0);\n  return readLayer(phosphor, u_mask * 0.2);\n}\n\nvec4 readScanlines(vec2 sourcePx) {\n  float period = max(u_scanlineDensity * u_pixelRatio, 2.0);\n  float gap = 0.5 - 0.5 * cos(sourcePx.y / period * TAU);\n  return readLayer(vec3(0.0), u_scanlines * gap * gap);\n}\n\nvec4 readNoise(vec2 fragment, float frame) {\n  float grain = readHash(vec3(fragment, frame)) - 0.5;\n  return readLayer(vec3(step(0.0, grain)), abs(grain) * 2.0 * u_noise * 0.4);\n}\n\nvec4 readRoll(float height) {\n  float head = mod(u_time * 0.18, 1.35) - 0.2;\n  float along = (height - head) / 0.16;\n  float glow = exp(-along * along);\n  float trail = exp(-(along + 1.8) * (along + 1.8) * 0.4);\n  return stack(readLayer(vec3(1.0), glow * 0.08), readLayer(vec3(0.0), trail * 0.2));\n}\n\nvec4 readVignette(vec2 unit) {\n  float reach = smoothstep(0.3, 1.45, length(unit));\n  return readLayer(vec3(0.0), u_vignette * reach * reach);\n}\n\nvec4 readBezel(vec2 fragment) {\n  vec2 center = u_resolution * 0.5;\n  float shortSide = min(u_resolution.x, u_resolution.y);\n  float lip = (1.0 + 6.0 * u_curvature) * u_pxSize;\n  float bow = u_curvature * 0.05 * shortSide;\n  float radius = max(min(u_curvature * 0.3 * shortSide, shortSide * 0.5 - lip - bow), 0.0);\n  vec2 cell = (floor(fragment / u_pxSize) + 0.5) * u_pxSize;\n  vec2 cellUnit = (cell - center) / center;\n  vec2 pointUnit = (fragment - center) / center;\n  vec2 cellBox = center - lip - bow * cellUnit.yx * cellUnit.yx;\n  vec2 pointBox = center - lip - bow * pointUnit.yx * pointUnit.yx;\n  float outside = step(0.0, readBoxDistance(cell - center, cellBox, radius));\n  float depth = shortSide * (0.03 + 0.1 * u_curvature);\n  float inside = clamp(-readBoxDistance(fragment - center, pointBox, radius) / depth, 0.0, 1.0);\n  float shadow = (1.0 - inside) * (1.0 - inside) * 0.6;\n  return readLayer(vec3(0.0), max(outside, shadow));\n}\n\nvoid main() {\n  vec2 fragment = vec2(gl_FragCoord.x, u_resolution.y - gl_FragCoord.y);\n  vec2 unit = fragment / u_resolution * 2.0 - 1.0;\n  vec2 sourcePx = (unit + readBarrelShift(unit)) * 0.5 * u_resolution + u_resolution * 0.5;\n  float frame = floor(u_time * u_fps + 0.001);\n  vec4 color = vec4(0.0);\n\n  if (u_mask > 0.0) {\n    color = stack(readMask(fragment), color);\n  }\n  if (u_scanlines > 0.0) {\n    color = stack(readScanlines(sourcePx), color);\n  }\n  if (u_noise > 0.0) {\n    color = stack(readNoise(fragment, frame), color);\n  }\n  if (u_roll > 0.5) {\n    color = stack(readRoll(fragment.y / u_resolution.y), color);\n  }\n  if (u_flicker > 0.0) {\n    color = stack(readLayer(vec3(0.0), u_flicker * 0.14 * readHash(vec3(frame, 7.0, 3.0))), color);\n  }\n  if (u_vignette > 0.0) {\n    color = stack(readVignette(unit), color);\n  }\n  if (u_curvature > 0.0) {\n    color = stack(readBezel(fragment), color);\n  }\n\n  fragColor = color;\n}\n`\n\nexport type CrtUniforms = {\n  u_fps: number\n  u_scanlines: number\n  u_scanlineDensity: number\n  u_noise: number\n  u_vignette: number\n  u_mask: number\n  u_flicker: number\n  u_curvature: number\n  u_roll: number\n}\n\nexport type CrtParams = Required<ShaderMotionParams> & {\n  scanlines: number\n  scanlineDensity: number\n  noise: number\n  vignette: number\n  mask: number\n  flicker: number\n  bloom: number\n  curvature: number\n  aberration: number\n  roll: boolean\n}\n\nexport type CrtPresetName = \"subtle\" | \"arcade\" | \"broken\"\n\nexport const crtPresets: Record<CrtPresetName, ShaderPreset<CrtParams>> = {\n  subtle: {\n    name: \"Subtle\",\n    params: {\n      speed: 1,\n      frame: 0,\n      fps: 30,\n      scanlines: 0.18,\n      scanlineDensity: 3,\n      noise: 0.08,\n      vignette: 0.25,\n      mask: 0.1,\n      flicker: 0,\n      bloom: 0.15,\n      curvature: 0.15,\n      aberration: 0,\n      roll: false,\n    },\n  },\n  arcade: {\n    name: \"Arcade\",\n    params: {\n      speed: 1,\n      frame: 0,\n      fps: 30,\n      scanlines: 0.4,\n      scanlineDensity: 3,\n      noise: 0.12,\n      vignette: 0.45,\n      mask: 0.25,\n      flicker: 0,\n      bloom: 0.5,\n      curvature: 0.22,\n      aberration: 1.2,\n      roll: false,\n    },\n  },\n  broken: {\n    name: \"Broken\",\n    params: {\n      speed: 1,\n      frame: 0,\n      fps: 30,\n      scanlines: 0.35,\n      scanlineDensity: 3,\n      noise: 0.35,\n      vignette: 0.6,\n      mask: 0.15,\n      flicker: 0.6,\n      bloom: 0.4,\n      curvature: 0.32,\n      aberration: 3,\n      roll: true,\n    },\n  },\n}\n\nexport const defaultCrtPreset: CrtPresetName = \"subtle\"\n\nexport function resolveCrtParams(\n  preset: CrtPresetName,\n  overrides: Partial<CrtParams>,\n  isReducedMotion: boolean\n): CrtParams {\n  const base = crtPresets[preset].params\n  const defined = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined))\n  const resolved = { ...base, ...defined }\n  return isReducedMotion ? { ...resolved, speed: 0, flicker: 0 } : resolved\n}\n\nexport function toCrtUniforms(params: CrtParams): CrtUniforms {\n  return {\n    u_fps: params.fps,\n    u_scanlines: params.scanlines,\n    u_scanlineDensity: params.scanlineDensity,\n    u_noise: params.noise,\n    u_vignette: params.vignette,\n    u_mask: params.mask,\n    u_flicker: params.flicker,\n    u_curvature: params.curvature,\n    u_roll: params.roll ? 1 : 0,\n  }\n}\n",
      "type": "registry:lib",
      "target": "@lib/shaders/crt.ts"
    },
    {
      "path": "lib/crt/warp-filter.ts",
      "content": "const MAP_MAX_SIZE = 256\n\nconst MAP_DIVISOR = 4\n\nexport const BARREL_REACH = 0.4\n\nexport type BarrelMap = { href: string; scale: number }\n\nfunction readDisplacement(unit: number, radiusSquared: number, reach: number): number {\n  return (unit * reach * (radiusSquared - 1)) / (1 + reach)\n}\n\nexport function createBarrelMap(width: number, height: number, curvature: number): BarrelMap | null {\n  const mapWidth = Math.max(2, Math.min(MAP_MAX_SIZE, Math.ceil(width / MAP_DIVISOR)))\n  const mapHeight = Math.max(2, Math.min(MAP_MAX_SIZE, Math.ceil(height / MAP_DIVISOR)))\n  const canvas = document.createElement(\"canvas\")\n  canvas.width = mapWidth\n  canvas.height = mapHeight\n  const context = canvas.getContext(\"2d\")\n  if (!context) {\n    return null\n  }\n  const reach = curvature * BARREL_REACH\n  const shifts = new Float32Array(mapWidth * mapHeight * 2)\n  let peak = 0\n  for (let row = 0; row < mapHeight; row++) {\n    for (let column = 0; column < mapWidth; column++) {\n      const unitX = ((column + 0.5) / mapWidth) * 2 - 1\n      const unitY = ((row + 0.5) / mapHeight) * 2 - 1\n      const radiusSquared = (unitX * unitX + unitY * unitY) / 2\n      const shiftX = readDisplacement(unitX, radiusSquared, reach) * (width / 2)\n      const shiftY = readDisplacement(unitY, radiusSquared, reach) * (height / 2)\n      const index = (row * mapWidth + column) * 2\n      shifts[index] = shiftX\n      shifts[index + 1] = shiftY\n      peak = Math.max(peak, Math.abs(shiftX), Math.abs(shiftY))\n    }\n  }\n  const scale = Math.max(peak * 2, 1)\n  const image = context.createImageData(mapWidth, mapHeight)\n  for (let index = 0; index < mapWidth * mapHeight; index++) {\n    image.data[index * 4] = Math.round((0.5 + shifts[index * 2] / scale) * 255)\n    image.data[index * 4 + 1] = Math.round((0.5 + shifts[index * 2 + 1] / scale) * 255)\n    image.data[index * 4 + 2] = 128\n    image.data[index * 4 + 3] = 255\n  }\n  context.putImageData(image, 0, 0)\n  return { href: canvas.toDataURL(\"image/png\"), scale }\n}\n",
      "type": "registry:lib",
      "target": "@lib/crt/warp-filter.ts"
    },
    {
      "path": "components/retro/crt-screen.tsx",
      "content": "\"use client\"\n\nimport { cn } from \"cn\"\nimport * as React from \"react\"\n\nimport { ShaderMount } from \"@/components/ui/shader-mount\"\nimport { usePrefersReducedMotion } from \"@/hooks/use-prefers-reduced-motion\"\nimport { type BarrelMap, createBarrelMap } from \"@/lib/crt/warp-filter\"\nimport {\n  crtFragmentShader,\n  type CrtParams,\n  type CrtPresetName,\n  defaultCrtPreset,\n  resolveCrtParams,\n  toCrtUniforms,\n} from \"@/lib/shaders/crt\"\n\nconst NO_COLORS = {}\n\nconst BLOOM_BLUR = 6\n\nconst BLOOM_GAIN = 1.2\n\nconst FULLSCREEN_OVERLAY_CLASS = \"fixed inset-0 z-[2147483647]\"\n\nconst VIEWPORT_PROBE_CLASS = \"pointer-events-none invisible fixed inset-x-0 top-0 h-lvh\"\n\nconst CHANNELS = [\n  { name: \"red\", matrix: \"1 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 1 0\", direction: -1 },\n  { name: \"green\", matrix: \"0 0 0 0 0  0 1 0 0 0  0 0 0 0 0  0 0 0 1 0\", direction: 0 },\n  { name: \"blue\", matrix: \"0 0 0 0 0  0 0 0 0 0  0 0 1 0 0  0 0 0 1 0\", direction: 1 },\n] as const\n\ntype CrtScreenProps = React.ComponentProps<\"div\"> &\n  Partial<CrtParams> & {\n    preset?: CrtPresetName\n    fullscreen?: boolean\n  }\n\ntype Size = { width: number; height: number }\n\ntype Warp = { id: string; defs: React.ReactNode }\n\nfunction subscribeNothing(): () => void {\n  return () => {}\n}\n\nfunction readRootElement(): HTMLElement {\n  return document.documentElement\n}\n\nfunction readServerElement(): null {\n  return null\n}\n\nfunction readIsWebKit(): boolean {\n  return navigator.vendor.startsWith(\"Apple\")\n}\n\nfunction readServerIsWebKit(): boolean {\n  return false\n}\n\nfunction useElementSize(element: HTMLElement | null): Size | null {\n  const [size, setSize] = React.useState<Size | null>(null)\n  React.useEffect(() => {\n    if (!element) {\n      return\n    }\n    const observer = new ResizeObserver(([entry]) => {\n      if (entry) {\n        const { offsetWidth, offsetHeight } = element\n        setSize((previous) =>\n          previous?.width === offsetWidth && previous.height === offsetHeight\n            ? previous\n            : { width: offsetWidth, height: offsetHeight }\n        )\n      }\n    })\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [element])\n  return size\n}\n\nfunction useCrtWarp(\n  target: HTMLElement | null,\n  size: Size | null,\n  curvature: number,\n  aberration: number,\n  bloom: number\n): Warp | null {\n  const id = `crt-warp-${React.useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`\n  const isWarped = curvature > 0 || aberration > 0 || bloom > 0\n  const width = size?.width ?? 0\n  const height = size?.height ?? 0\n  const map = React.useMemo<BarrelMap | null>(\n    () => (curvature > 0 && width > 0 && height > 0 ? createBarrelMap(width, height, curvature) : null),\n    [curvature, width, height]\n  )\n  const isReady = isWarped && target !== null && width > 0 && height > 0 && (curvature <= 0 || map !== null)\n\n  React.useEffect(() => {\n    if (!target || !isReady) {\n      return\n    }\n    const previous = target.style.getPropertyValue(\"filter\")\n    target.style.setProperty(\"filter\", `url(#${id})`)\n    return () => {\n      target.style.setProperty(\"filter\", previous)\n    }\n  }, [target, isReady, id])\n\n  if (!isReady) {\n    return null\n  }\n  const warped = map ? \"warped\" : \"SourceGraphic\"\n  const split = aberration > 0 ? \"split\" : warped\n  const gain = bloom * BLOOM_GAIN\n  return {\n    id,\n    defs: (\n      <filter\n        id={id}\n        filterUnits=\"userSpaceOnUse\"\n        primitiveUnits=\"userSpaceOnUse\"\n        x={0}\n        y={0}\n        width={width}\n        height={height}\n        colorInterpolationFilters=\"sRGB\"\n      >\n        {map && (\n          <>\n            <feImage\n              href={map.href}\n              x={0}\n              y={0}\n              width={width}\n              height={height}\n              preserveAspectRatio=\"none\"\n              result=\"map\"\n            />\n            <feDisplacementMap\n              in=\"SourceGraphic\"\n              in2=\"map\"\n              scale={map.scale}\n              xChannelSelector=\"R\"\n              yChannelSelector=\"G\"\n              result=\"warped\"\n            />\n          </>\n        )}\n        {aberration > 0 &&\n          CHANNELS.map(({ name, matrix, direction }) => (\n            <React.Fragment key={name}>\n              <feColorMatrix in={warped} type=\"matrix\" values={matrix} result={`${name}-channel`} />\n              <feOffset in={`${name}-channel`} dx={direction * aberration} dy={0} result={`${name}-shifted`} />\n            </React.Fragment>\n          ))}\n        {aberration > 0 && (\n          <>\n            <feBlend in=\"red-shifted\" in2=\"green-shifted\" mode=\"screen\" result=\"red-green\" />\n            <feBlend in=\"red-green\" in2=\"blue-shifted\" mode=\"screen\" result=\"split\" />\n          </>\n        )}\n        {bloom > 0 && (\n          <>\n            <feGaussianBlur in={split} stdDeviation={BLOOM_BLUR * bloom} result=\"halo\" />\n            <feColorMatrix\n              in=\"halo\"\n              type=\"matrix\"\n              values={`${gain} 0 0 0 0  0 ${gain} 0 0 0  0 0 ${gain} 0 0  0 0 0 1 0`}\n              result=\"glow\"\n            />\n            <feBlend in=\"glow\" in2={split} mode=\"screen\" />\n          </>\n        )}\n      </filter>\n    ),\n  }\n}\n\nfunction WarpDefs({ warp }: { warp: Warp | null }) {\n  if (!warp) {\n    return null\n  }\n  return (\n    <svg aria-hidden=\"true\" focusable=\"false\" width={0} height={0} className=\"pointer-events-none absolute\">\n      {warp.defs}\n    </svg>\n  )\n}\n\nfunction CrtOverlay({ params, className, ...props }: { params: CrtParams } & React.ComponentProps<\"div\">) {\n  const uniforms = React.useMemo(() => toCrtUniforms(params), [params])\n  return (\n    <ShaderMount\n      aria-hidden=\"true\"\n      className={cn(\"pointer-events-none\", className)}\n      {...props}\n      speed={params.speed}\n      frame={params.frame}\n      fps={params.fps}\n      fragmentShader={crtFragmentShader}\n      uniforms={uniforms}\n      colors={NO_COLORS}\n    />\n  )\n}\n\nfunction useCrtParams(props: Partial<CrtParams>, preset: CrtPresetName): CrtParams {\n  const isReducedMotion = usePrefersReducedMotion()\n  const { speed, frame, fps, scanlines, scanlineDensity, noise, vignette, mask, flicker, bloom, curvature, aberration, roll } = props\n  return React.useMemo(\n    () =>\n      resolveCrtParams(\n        preset,\n        { speed, frame, fps, scanlines, scanlineDensity, noise, vignette, mask, flicker, bloom, curvature, aberration, roll },\n        isReducedMotion\n      ),\n    [preset, isReducedMotion, speed, frame, fps, scanlines, scanlineDensity, noise, vignette, mask, flicker, bloom, curvature, aberration, roll]\n  )\n}\n\nfunction FullscreenCrt({\n  params,\n  children,\n  ...props\n}: { params: CrtParams } & React.ComponentProps<\"div\">) {\n  const root = React.useSyncExternalStore(subscribeNothing, readRootElement, readServerElement)\n  const [probe, setProbe] = React.useState<HTMLDivElement | null>(null)\n  const viewport = useElementSize(probe)\n  const isWebKit = React.useSyncExternalStore(subscribeNothing, readIsWebKit, readServerIsWebKit)\n  const warpTarget = isWebKit ? null : root\n  const warp = useCrtWarp(warpTarget, viewport, params.curvature, params.aberration, params.bloom)\n  return (\n    <>\n      <div ref={setProbe} aria-hidden=\"true\" className={VIEWPORT_PROBE_CLASS} />\n      <WarpDefs warp={warp} />\n      {children}\n      <CrtOverlay data-slot=\"crt-screen\" data-fullscreen=\"\" params={params} {...props} className={cn(FULLSCREEN_OVERLAY_CLASS, props.className)} />\n    </>\n  )\n}\n\nfunction ScopedCrt({\n  params,\n  className,\n  children,\n  ...props\n}: { params: CrtParams } & React.ComponentProps<\"div\">) {\n  const [content, setContent] = React.useState<HTMLDivElement | null>(null)\n  const size = useElementSize(content)\n  const warp = useCrtWarp(content, size, params.curvature, params.aberration, params.bloom)\n  return (\n    <div data-slot=\"crt-screen\" className={cn(\"relative isolate\", className)} {...props}>\n      <WarpDefs warp={warp} />\n      <div ref={setContent} data-slot=\"crt-screen-content\" className=\"size-full\">\n        {children}\n      </div>\n      <CrtOverlay params={params} className=\"absolute inset-0 z-10\" />\n    </div>\n  )\n}\n\nfunction CrtScreen({\n  preset = defaultCrtPreset,\n  fullscreen = false,\n  speed,\n  frame,\n  fps,\n  scanlines,\n  scanlineDensity,\n  noise,\n  vignette,\n  mask,\n  flicker,\n  bloom,\n  curvature,\n  aberration,\n  roll,\n  ...props\n}: CrtScreenProps) {\n  const params = useCrtParams(\n    { speed, frame, fps, scanlines, scanlineDensity, noise, vignette, mask, flicker, bloom, curvature, aberration, roll },\n    preset\n  )\n  return fullscreen ? <FullscreenCrt params={params} {...props} /> : <ScopedCrt params={params} {...props} />\n}\n\nexport { CrtScreen }\nexport type { CrtScreenProps }\n",
      "type": "registry:component",
      "target": "@components/retro/crt-screen.tsx"
    }
  ],
  "docs": "Scoped is the default: the effect covers the box and its children, and the overlay never takes the pointer. Pass fullscreen to lay it over the whole viewport instead; curvature, aberration and bloom then filter the whole document, which costs more on large pages. Put padding and backgrounds on the children, not on CrtScreen, so the warp and the overlay share one box. Scanlines and grain are alpha black and white at device resolution and follow the barrel curve. Under curvature, clicks land at the undistorted position of the element. Portals opened from inside a scoped CrtScreen (dialogs, menus, toasts) mount on the body and escape the effect; use fullscreen to cover them. Reduced motion freezes the grain and turns flicker off.",
  "categories": [
    "shared"
  ],
  "type": "registry:block"
}