{
    "id": "bhaskar/activity-heatmap",
    "kind": "component",
    "title": "Activity Dither Heatmap",
    "summary": "GitHub-style activity heatmap with interactive dither dots.",
    "author": "Admin",
    "stars": 0,
    "url": "https://ownlyplans.com/bhaskar/activity-heatmap/",
    "stack": [
        "Motion",
        "React",
        "Tailwind CSS"
    ],
    "tools": [
        "claude-code",
        "cursor",
        "lovable"
    ],
    "difficulty": "beginner",
    "license": "mit",
    "version": "1.0",
    "overview": "GitHub-style activity heatmap with interactive dither dots.\n\nA React chart built with Motion and Tailwind CSS. Open the Preview tab to try it, then copy the code from the Code tab or install it with the shadcn command. Hand this page's link to Claude or any AI tool and it can read the code straight from the page.\n\nCredit: from the amicro library by Syed Subhan Uddin (https://github.com/Subhan-code/Amicro--Micro-transitions-), shared here under the MIT licence.\n\nMIT License\n\nCopyright (c) 2026 Syed Subhan Uddin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
    "steps": [],
    "files": [],
    "install": "npx shadcn@latest add https://ownlyplans.com/r/bhaskar/activity-heatmap.json",
    "how_to_use": "Use the component code (html, css, js, or react) directly, or run the install command.",
    "source": {
        "name": "amicro by Syed Subhan Uddin",
        "url": "https://github.com/Subhan-code/Amicro--Micro-transitions-/blob/main/src/components/dither-charts/ActivityHeatmap.tsx",
        "license": "MIT"
    },
    "component": {
        "category": "Charts",
        "framework": "React + Motion + Tailwind CSS",
        "files": [
            {
                "name": "activity-heatmap.tsx",
                "code": "/*\n * MIT License\n *\n * Copyright (c) 2026 Syed Subhan Uddin\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n// Activity Dither Heatmap from amicro by Syed Subhan Uddin\n// https://github.com/Subhan-code/Amicro--Micro-transitions-/blob/main/src/components/dither-charts/ActivityHeatmap.tsx\n// MIT License, Copyright (c) 2026 Syed Subhan Uddin. Full licence: https://github.com/Subhan-code/Amicro--Micro-transitions-/blob/main/LICENSE\n// Styled with Tailwind CSS. Needs: motion, lucide-react\n\nimport React, { useEffect, useRef, useState, useMemo } from 'react';\nimport { motion, useSpring, useTransform, useReducedMotion } from 'motion/react';\nimport { Activity } from 'lucide-react';\nimport { useCanvasSetup } from './use-canvas-setup';\n\nconst PERIODS = [\n  { name: 'Last 3 Months', weeks: 12 },\n  { name: 'Last 6 Months', weeks: 24 },\n];\n\nconst smoothstep = (min: number, max: number, value: number) => {\n  const x = Math.max(0, Math.min(1, (value - min) / (max - min)));\n  return x * x * (3 - 2 * x);\n};\n\nconst hash = (x: number, y: number) => {\n  let h = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453;\n  return h - Math.floor(h);\n};\n\nfunction AnimatedNumber({ value }: { value: number }) {\n  const prefersReducedMotion = useReducedMotion();\n  const spring = useSpring(value, { stiffness: 190, damping: 20, mass: 0.7 });\n  const display = useTransform(spring, (current) =>\n    Math.round(current).toLocaleString('en-US')\n  );\n  useEffect(() => {\n    if (prefersReducedMotion) spring.jump(value);\n    else spring.set(value);\n  }, [value, spring, prefersReducedMotion]);\n  return <motion.span className=\"tabular-nums\">{display}</motion.span>;\n}\n\nexport function ActivityHeatmap({ theme = 'dark', compact = false }: { theme?: 'dark' | 'light'; compact?: boolean }) {\n  const [periodIndex, setPeriodIndex] = useState(0);\n  const { canvasRef, rect, isVisible, reducedMotion } = useCanvasSetup();\n  const period = PERIODS[periodIndex];\n\n  const { data, total } = useMemo(() => {\n    const weeks = period.weeks;\n    const newData = [];\n    let tot = 0;\n    for (let w = 0; w < weeks; w++) {\n      const col = [];\n      for (let d = 0; d < 7; d++) {\n        const val = Math.floor(Math.sin(w * 0.5 + d * 0.2) * 2 + Math.cos(w * 1.2) * 1.5 + 2);\n        const clamped = Math.max(0, Math.min(4, val));\n        col.push(clamped);\n        tot += clamped * 10;\n      }\n      newData.push(col);\n    }\n    return { data: newData, total: tot };\n  }, [periodIndex]);\n\n  const targetDataRef = useRef(data);\n  const fromDataRef = useRef(data);\n  const morphStartTimeRef = useRef(0);\n  const timeRef = useRef(0);\n\n  useEffect(() => {\n    fromDataRef.current = targetDataRef.current;\n    targetDataRef.current = data;\n    morphStartTimeRef.current = performance.now();\n  }, [data]);\n\n  useEffect(() => {\n    let req: number;\n    const draw = () => {\n      if (!isVisible.current) { req = requestAnimationFrame(draw); return; }\n\n      const canvas = canvasRef.current;\n      if (!canvas) return;\n      const ctx = canvas.getContext('2d');\n      if (!ctx) return;\n\n      const { width: w, height: h } = rect.current;\n      if (w === 0 || h === 0) { req = requestAnimationFrame(draw); return; }\n\n      timeRef.current += reducedMotion ? 0 : 0.02;\n\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n      ctx.save();\n      ctx.scale(dpr, dpr);\n      ctx.clearRect(0, 0, w, h);\n\n      const prog = reducedMotion ? 1 : Math.min(1, (performance.now() - morphStartTimeRef.current) / 500);\n      const e = 1 - Math.pow(2, -10 * prog);\n\n      const weeks = Math.max(fromDataRef.current.length, targetDataRef.current.length);\n      const cellSize = 10;\n      const gap = 2.5;\n      const totalW = weeks * (cellSize + gap) - gap;\n      const totalH = 7 * (cellSize + gap) - gap;\n\n      const startX = (w - totalW) / 2;\n      const startY = (h - totalH) / 2;\n\n      const colors = ['rgba(255,255,255,0.15)', 'rgba(255,255,255,0.35)', 'rgba(255,255,255,0.55)', 'rgba(255,255,255,0.75)', '#FFFFFF'];\n      const cell = Math.max(2, Math.round(w / 250));\n      const t2 = timeRef.current;\n\n      for (let wk = 0; wk < weeks; wk++) {\n        for (let d = 0; d < 7; d++) {\n          const targetVal = targetDataRef.current[wk]?.[d] || 0;\n          const fromVal = fromDataRef.current[wk]?.[d] || 0;\n          const val = fromVal + (targetVal - fromVal) * e;\n\n          const x = startX + wk * (cellSize + gap);\n          const y = startY + d * (cellSize + gap);\n\n          const colorIdx = Math.max(0, Math.min(4, Math.round(val)));\n\n          ctx.save();\n          ctx.beginPath();\n          ctx.rect(x, y, cellSize, cellSize);\n          ctx.clip();\n\n          ctx.globalAlpha = 0.85;\n          ctx.fillStyle = colors[colorIdx];\n\n          for (let tx = Math.floor(x); tx <= Math.ceil(x + cellSize); tx += cell) {\n            for (let ty = Math.floor(y); ty <= Math.ceil(y + cellSize); ty += cell) {\n              const jx = tx + cell / 2;\n              const jy = ty + cell / 2;\n              const jit = hash(jx, jy);\n\n              const waveRaw = reducedMotion ? 0 :\n                Math.sin(jx * 0.05 + t2) + Math.sin(jy * 0.05 + t2 * 0.7);\n              const mod = smoothstep(-1.5, 1.5, waveRaw);\n\n              const sz = cell * (0.4 + 0.4 * mod) * (0.8 + 0.4 * jit);\n              ctx.fillRect(tx + (cell - sz)/2, ty + (cell - sz)/2, sz, sz);\n            }\n          }\n          ctx.restore();\n        }\n      }\n      ctx.restore();\n      req = requestAnimationFrame(draw);\n    };\n    req = requestAnimationFrame(draw);\n    return () => cancelAnimationFrame(req);\n  }, [reducedMotion]);\n\n  return (\n    <div className=\"w-full h-full flex flex-col items-center justify-center p-2\">\n      <div className=\"w-full flex flex-col items-center gap-2\">\n        {!compact && (\n          <div className=\"flex items-center justify-between w-full px-2\">\n            <span className={`text-xs font-semibold ${theme === 'dark' ? 'text-white' : 'text-black'}`}>\n              <AnimatedNumber value={total} /> contributions\n            </span>\n          </div>\n        )}\n        <div className=\"w-full flex justify-center\">\n          <canvas ref={canvasRef} className=\"w-full h-[120px]\" />\n        </div>\n      </div>\n    </div>\n  );\n}"
            },
            {
                "name": "use-canvas-setup.ts",
                "code": "/*\n * MIT License\n *\n * Copyright (c) 2026 Syed Subhan Uddin\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { useEffect, useRef, useState, RefObject } from 'react';\n\ninterface CanvasRect {\n  width: number;\n  height: number;\n}\n\ninterface UseCanvasSetupResult {\n  canvasRef: RefObject<HTMLCanvasElement>;\n  /** Cached canvas logical size — updated by ResizeObserver, never from getBoundingClientRect inside RAF */\n  rect: RefObject<CanvasRect>;\n  /** true when the canvas is in the viewport (IntersectionObserver) */\n  isVisible: RefObject<boolean>;\n  /** true when prefers-reduced-motion is active — read once on mount */\n  reducedMotion: boolean;\n}\n\n/**\n * Shared canvas performance hook.\n *\n * Responsibilities:\n * - Caches logical canvas size via ResizeObserver (avoids layout reflow per frame)\n * - Pauses animation when canvas is scrolled off-screen (IntersectionObserver)\n * - Pauses animation when the browser tab is hidden (visibilitychange)\n * - Reads prefers-reduced-motion ONCE on mount (not per frame)\n */\nexport function useCanvasSetup(): UseCanvasSetupResult {\n  const canvasRef = useRef<HTMLCanvasElement>(null!);\n  const rect = useRef<CanvasRect>({ width: 0, height: 0 });\n  const isVisible = useRef(true);\n\n  const [reducedMotion] = useState(\n    () => typeof window !== 'undefined' && (\n      window.matchMedia('(prefers-reduced-motion: reduce)').matches ||\n      window.innerWidth < 768 ||\n      window.matchMedia('(max-width: 768px)').matches\n    )\n  );\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n\n    // --- ResizeObserver: cache logical size ---\n    const ro = new ResizeObserver((entries) => {\n      for (const entry of entries) {\n        const { width, height } = entry.contentRect;\n        rect.current = { width, height };\n\n        // Also keep canvas pixel size in sync on resize\n        const dpr = Math.min(window.devicePixelRatio || 1, 2);\n        canvas.width = Math.round(width * dpr);\n        canvas.height = Math.round(height * dpr);\n      }\n    });\n    ro.observe(canvas);\n\n    // --- IntersectionObserver: pause when off-screen ---\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        isVisible.current = entry.isIntersecting;\n      },\n      { rootMargin: '100px' }\n    );\n    io.observe(canvas);\n\n    // --- Tab visibility: pause when hidden ---\n    const handleVisibility = () => {\n      isVisible.current = document.visibilityState === 'visible';\n    };\n    document.addEventListener('visibilitychange', handleVisibility);\n\n    return () => {\n      ro.disconnect();\n      io.disconnect();\n      document.removeEventListener('visibilitychange', handleVisibility);\n    };\n  }, []);\n\n  return { canvasRef, rect, isVisible, reducedMotion };\n}"
            }
        ],
        "dependencies": [
            "motion",
            "lucide-react"
        ],
        "install": "npx shadcn@latest add https://ownlyplans.com/r/bhaskar/activity-heatmap.json",
        "licence_notice": "MIT License\n\nCopyright (c) 2026 Syed Subhan Uddin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
    }
}