UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.
feat: add flickering grid component (#269)
Arghya Das5e8148d1483a
diff --git a/config/docs.ts b/config/docs.tsindex c51b2600..693fecc7 100644--- a/config/docs.ts+++ b/config/docs.ts@@ -367,6 +367,12 @@ export const docsConfig: DocsConfig = {{title: "Backgrounds",items: [+ {+ title: "Flickering Grid",+ href: `/docs/components/flickering-grid`,+ items: [],+ label: "New",+ },{title: "Animated Grid Pattern",href: `/docs/components/animated-grid-pattern`,diff --git a/content/docs/components/flickering-grid.mdx b/content/docs/components/flickering-grid.mdxnew file mode 100644index 00000000..6be16303--- /dev/null+++ b/content/docs/components/flickering-grid.mdx@@ -0,0 +1,54 @@+---+title: Flickering Grid+date: 2023-07-20+description: A flickering grid background made with SVGs, fully customizable using Tailwind CSS.+author: dillionverma+published: true+---++<ComponentPreview name="flickering-grid-demo" />++## Installation++<Tabs defaultValue="cli">++<TabsList>+ <TabsTrigger value="cli">CLI</TabsTrigger>+ <TabsTrigger value="manual">Manual</TabsTrigger>+</TabsList>+<TabsContent value="cli">++```bash+npx magicui-cli add flickering-grid+```++</TabsContent>++<TabsContent value="manual">++<Steps>++<Step>Copy and paste the following code into your project.</Step>++<ComponentSource name="flickering-grid" />++<Step>Update the import paths to match your project setup.</Step>++</Steps>++</TabsContent>++</Tabs>++## Props++| Prop | Type | Description | Default |+| ------------- | ------ | ------------------------------------- | -------------- |+| squareSize | number | Size of each square in the grid | 4 |+| gridGap | number | Gap between squares in the grid | 6 |+| flickerChance | number | Probability of a square flickering | 0.3 |+| color | string | Color of the squares | "rgb(0, 0, 0)" |+| width | number | Width of the canvas | - |+| height | number | Height of the canvas | - |+| className | string | Additional CSS classes for the canvas | - |+| maxOpacity | number | Maximum opacity of the squares | 0.2 |diff --git a/registry/components/example/flickering-grid-demo.tsx b/registry/components/example/flickering-grid-demo.tsxnew file mode 100644index 00000000..064e298a--- /dev/null+++ b/registry/components/example/flickering-grid-demo.tsx@@ -0,0 +1,18 @@+import FlickeringGrid from "@/components/magicui/flickering-grid";++export default function FlickeringGridDemo() {+ return (+ <div className="relative h-[500px] rounded-lg w-full bg-background overflow-hidden border">+ <FlickeringGrid+ className="z-0 absolute inset-0 size-full"+ squareSize={4}+ gridGap={6}+ color="#6B7280"+ maxOpacity={0.5}+ flickerChance={0.1}+ height={800}+ width={800}+ />+ </div>+ );+}diff --git a/registry/components/magicui/flickering-grid.tsx b/registry/components/magicui/flickering-grid.tsxnew file mode 100644index 00000000..4ef68450--- /dev/null+++ b/registry/components/magicui/flickering-grid.tsx@@ -0,0 +1,184 @@+"use client";++import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";++interface FlickeringGridProps {+ squareSize?: number;+ gridGap?: number;+ flickerChance?: number;+ color?: string;+ width?: number;+ height?: number;+ className?: string;+ maxOpacity?: number;+}++const FlickeringGrid: React.FC<FlickeringGridProps> = ({+ squareSize = 4,+ gridGap = 6,+ flickerChance = 0.3,+ color = "rgb(0, 0, 0)",+ width,+ height,+ className,+ maxOpacity = 0.2,+}) => {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const [isInView, setIsInView] = useState(false);++ const memoizedColor = useMemo(() => {+ const toRGBA = (color: string) => {+ if (typeof window === "undefined") {+ return `rgba(0, 0, 0,`;+ }+ const canvas = document.createElement("canvas");+ canvas.width = canvas.height = 1;+ const ctx = canvas.getContext("2d");+ if (!ctx) return "rgba(255, 0, 0,";+ ctx.fillStyle = color;+ ctx.fillRect(0, 0, 1, 1);+ const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data;+ return `rgba(${r}, ${g}, ${b},`;+ };+ return toRGBA(color);+ }, [color]);++ const setupCanvas = useCallback(+ (canvas: HTMLCanvasElement) => {+ const canvasWidth = width || canvas.clientWidth;+ const canvasHeight = height || canvas.clientHeight;+ const dpr = window.devicePixelRatio || 1;+ canvas.width = canvasWidth * dpr;+ canvas.height = canvasHeight * dpr;+ canvas.style.width = `${canvasWidth}px`;+ canvas.style.height = `${canvasHeight}px`;+ const cols = Math.floor(canvasWidth / (squareSize + gridGap));+ const rows = Math.floor(canvasHeight / (squareSize + gridGap));++ const squares = new Float32Array(cols * rows);+ for (let i = 0; i < squares.length; i++) {+ squares[i] = Math.random() * maxOpacity;+ }++ return {+ width: canvasWidth,+ height: canvasHeight,+ cols,+ rows,+ squares,+ dpr,+ };+ },+ [squareSize, gridGap, width, height, maxOpacity]+ );++ const updateSquares = useCallback(+ (squares: Float32Array, deltaTime: number) => {+ for (let i = 0; i < squares.length; i++) {+ if (Math.random() < flickerChance * deltaTime) {+ squares[i] = Math.random() * maxOpacity;+ }+ }+ },+ [flickerChance, maxOpacity]+ );++ const drawGrid = useCallback(+ (+ ctx: CanvasRenderingContext2D,+ width: number,+ height: number,+ cols: number,+ rows: number,+ squares: Float32Array,+ dpr: number+ ) => {+ ctx.clearRect(0, 0, width, height);+ ctx.fillStyle = "transparent";+ ctx.fillRect(0, 0, width, height);++ for (let i = 0; i < cols; i++) {+ for (let j = 0; j < rows; j++) {+ const opacity = squares[i * rows + j];+ ctx.fillStyle = `${memoizedColor}${opacity})`;+ ctx.fillRect(+ i * (squareSize + gridGap) * dpr,+ j * (squareSize + gridGap) * dpr,+ squareSize * dpr,+ squareSize * dpr+ );+ }+ }+ },+ [memoizedColor, squareSize, gridGap]+ );++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;++ const ctx = canvas.getContext("2d");+ if (!ctx) return;++ let animationFrameId: number;+ let { width, height, cols, rows, squares, dpr } = setupCanvas(canvas);++ let lastTime = 0;+ const animate = (time: number) => {+ if (!isInView) return;++ const deltaTime = (time - lastTime) / 1000;+ lastTime = time;++ updateSquares(squares, deltaTime);+ drawGrid(ctx, width * dpr, height * dpr, cols, rows, squares, dpr);+ animationFrameId = requestAnimationFrame(animate);+ };++ const handleResize = () => {+ ({ width, height, cols, rows, squares, dpr } = setupCanvas(canvas));+ };++ const observer = new IntersectionObserver(+ ([entry]) => {+ setIsInView(entry.isIntersecting);+ },+ { threshold: 0 }+ );++ observer.observe(canvas);++ window.addEventListener("resize", handleResize);++ if (isInView) {+ animationFrameId = requestAnimationFrame(animate);+ }++ return () => {+ window.removeEventListener("resize", handleResize);+ cancelAnimationFrame(animationFrameId);+ observer.disconnect();+ };+ }, [setupCanvas, updateSquares, drawGrid, width, height, isInView]);++ return (+ <canvas+ ref={canvasRef}+ className={`size-full pointer-events-none ${className}`}+ style={{+ width: width || "100%",+ height: height || "100%",+ }}+ width={width}+ height={height}+ />+ );+};++export default FlickeringGrid;diff --git a/registry/index.tsx b/registry/index.tsxindex 41bfd666..1ed6ad01 100644--- a/registry/index.tsx+++ b/registry/index.tsx@@ -28,6 +28,11 @@ const ui: Registry = {type: "components:magicui",files: ["registry/components/magicui/dot-pattern.tsx"],},+ "flickering-grid": {+ name: "flickering-grid",+ type: "components:ui",+ files: ["registry/components/magicui/flickering-grid.tsx"],+ },marquee: {name: "marquee",type: "components:magicui",@@ -324,6 +329,14 @@ const example: Registry = {() => import("@/registry/components/example/dot-pattern-linear-gradient"),),},+ "flickering-grid-demo": {+ name: "flickering-grid",+ type: "components:example",+ files: ["registry/components/example/flickering-grid-demo.tsx"],+ component: React.lazy(+ () => import("@/registry/components/example/flickering-grid-demo"),+ ),+ },"marquee-demo": {name: "marquee-demo",type: "components:example",