All files / components/anim/BotNetwork BotNetwork.tsx

23.16% Statements 41/177
17.85% Branches 10/56
18.18% Functions 4/22
25.62% Lines 41/160

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325                                              1x                       1x 1x 1x 1x 1x 1x     1x                                                                                                                       1x 1x 1x 1x 1x 1x     1x                   1x                       1x 1x     1x                               1x 1x     1x 1x 1x 1x   1x 1x               1x     1x 1x     1x 1x 1x                                                                                                                                                                                                                             1x   1x 1x 1x 1x 1x 1x         1x                                          
import React, { useEffect, useRef } from "react";
 
type Bot = {
  id: number;
  x: number;
  y: number;
  z: number;
  vx: number;
  vy: number;
  vz: number;
  size: number; // base size
  color: string;
  img?: HTMLImageElement | null; // optional avatar image
};
 
type BotNetworkProps = {
  bots?: number; // number of bots
  density?: number; // connection distance factor
  bgColor?: string; // not applied to canvas (transparent) but available
  showAvatars?: boolean;
  avatarUrls?: string[]; // optional avatar urls (cycled)
};
 
const DEFAULTS = {
  bots: 20,
  density: 0.18, // lower = more connections
  showAvatars: true,
};
 
export function BotNetwork({
  bots = DEFAULTS.bots,
  density = DEFAULTS.density,
  showAvatars = DEFAULTS.showAvatars,
  avatarUrls = [],
}: BotNetworkProps) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const botsRef = useRef<Bot[]>([]);
  const rafRef = useRef<number | null>(null);
  const mouseRef = useRef({ x: 0, y: 0, active: false });
  const messagesRef = useRef<
    { from: number; to: number; t: number; speed: number }[]
  >([]);
  const imgsLoadedRef = useRef<HTMLImageElement[]>([]);
 
  // Helpers: 3D rotate & project
  function rotateY(p: { x: number; y: number; z: number }, a: number) {
    const cos = Math.cos(a),
      sin = Math.sin(a);
    return { x: p.x * cos - p.z * sin, y: p.y, z: p.x * sin + p.z * cos };
  }
  function rotateX(p: { x: number; y: number; z: number }, a: number) {
    const cos = Math.cos(a),
      sin = Math.sin(a);
    return { x: p.x, y: p.y * cos - p.z * sin, z: p.y * sin + p.z * cos };
  }
  function project(
    p: { x: number; y: number; z: number },
    w: number,
    h: number,
    fov: number,
    vd: number,
  ) {
    const factor = fov / (vd + p.z);
    return { x: p.x * factor + w / 2, y: p.y * factor + h / 2, s: factor };
  }
 
  // initialize bots positions based on container size
  function initBots(width: number, height: number) {
    const cube = Math.min(width, height) * 0.8; // 3D cube side
    const half = cube / 2;
    botsRef.current = Array.from({ length: bots }, (_, i) => ({
      id: i,
      x: Math.random() * cube - half,
      y: Math.random() * cube - half,
      z: Math.random() * cube - half,
      vx: (Math.random() * 2 - 1) * 0.2,
      vy: (Math.random() * 2 - 1) * 0.2,
      vz: (Math.random() * 2 - 1) * 0.2,
      size: 18 + Math.random() * 14,
      color: `hsl(${Math.round(Math.random() * 40 + 200)}, 70%, 60%)`,
      img: null,
    }));
 
    // preload avatar images (if provided)
    imgsLoadedRef.current = [];
    if (avatarUrls.length > 0 && showAvatars) {
      const urls = avatarUrls.length ? avatarUrls : [];
      botsRef.current.forEach((b, idx) => {
        const url = urls[idx % urls.length];
        const img = new Image();
        img.src = url;
        img.onload = () => {
          b.img = img;
        };
        img.onerror = () => {
          b.img = null;
        };
        imgsLoadedRef.current.push(img);
      });
    }
  }
 
  useEffect(() => {
    const canvas = canvasRef.current!;
    const container = containerRef.current!;
    Iif (!canvas || !container) return;
    const ctx = canvas.getContext("2d")!;
    Iif (!ctx) return;
 
    // resize logic using ResizeObserver
    const ro = new ResizeObserver(() => {
      const rect = container.getBoundingClientRect();
      const dpr = window.devicePixelRatio || 1;
      canvas.width = Math.max(1, Math.floor(rect.width * dpr));
      canvas.height = Math.max(1, Math.floor(rect.height * dpr));
      canvas.style.width = `${rect.width}px`;
      canvas.style.height = `${rect.height}px`;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // keep drawing crisp
      initBots(rect.width, rect.height);
    });
    ro.observe(container);
 
    // mouse move for parallax
    function onMove(e: MouseEvent) {
      const rect = canvas.getBoundingClientRect();
      mouseRef.current.x = (e.clientX - rect.left) / rect.width - 0.5;
      mouseRef.current.y = (e.clientY - rect.top) / rect.height - 0.5;
      mouseRef.current.active = true;
    }
    function onLeave() {
      mouseRef.current.active = false;
    }
    canvas.addEventListener("mousemove", onMove);
    canvas.addEventListener("mouseleave", onLeave);
 
    // occasionally queue messages between bots
    const messageInterval = setInterval(() => {
      if (botsRef.current.length < 2) return;
      const from = Math.floor(Math.random() * botsRef.current.length);
      let to = Math.floor(Math.random() * botsRef.current.length);
      if (to === from) to = (to + 1) % botsRef.current.length;
      messagesRef.current.push({
        from,
        to,
        t: 0,
        speed: 0.01 + Math.random() * 0.02,
      });
      // keep message list short
      if (messagesRef.current.length > 30) messagesRef.current.shift();
    }, 800);
 
    // animation state
    let angleY = 0;
    let angleX = 0;
 
    function draw() {
      const rect = container.getBoundingClientRect();
      const w = rect.width;
      const h = rect.height;
      ctx.clearRect(0, 0, w, h);
 
      Eif (botsRef.current.length === 0)
        return (rafRef.current = requestAnimationFrame(draw));
 
      // subtle auto-rotation + mouse parallax
      angleY += 0.002;
      angleX += 0.001;
 
      const targetY =
        (mouseRef.current.active ? mouseRef.current.x * 0.8 : 0) + angleY;
      const targetX =
        (mouseRef.current.active ? -mouseRef.current.y * 0.6 : 0) + angleX;
      // smooth them
      angleY += (targetY - angleY) * 0.06;
      angleX += (targetX - angleX) * 0.06;
 
      // Move bots slowly in 3D space (wrap inside cube)
      const cubeSize = Math.min(w, h) * 0.8;
      const half = cubeSize / 2;
      for (const b of botsRef.current) {
        b.x += b.vx;
        b.y += b.vy;
        b.z += b.vz;
        // soft bounds (reflect)
        if (b.x < -half || b.x > half) b.vx *= -1;
        if (b.y < -half || b.y > half) b.vy *= -1;
        if (b.z < -half || b.z > half) b.vz *= -1;
      }
 
      // Project bots
      const fov = cubeSize * 1.2;
      const vd = cubeSize * 1.6;
      const projected = botsRef.current.map((b) => {
        const r1 = rotateY(b, angleY);
        const r2 = rotateX(r1, angleX);
        return { bot: b, p: project(r2, w, h, fov, vd) };
      });
 
      // Draw connections (limited by distance)
      const connDist = cubeSize * density;
      for (let i = 0; i < projected.length; i++) {
        for (let j = i + 1; j < projected.length; j++) {
          const a = projected[i].bot;
          const b = projected[j].bot;
          const dx = a.x - b.x;
          const dy = a.y - b.y;
          const dz = a.z - b.z;
          const d = Math.sqrt(dx * dx + dy * dy + dz * dz);
          if (d < connDist) {
            const p1 = projected[i].p;
            const p2 = projected[j].p;
            const alpha = 1 - d / connDist;
            ctx.strokeStyle = `rgba(140,180,255,${0.12 * alpha})`;
            ctx.lineWidth = 1 * alpha;
            ctx.beginPath();
            ctx.moveTo(p1.x, p1.y);
            ctx.lineTo(p2.x, p2.y);
            ctx.stroke();
          }
        }
      }
 
      // Draw message pulses traveling along connections
      for (const m of messagesRef.current) {
        m.t += m.speed;
        if (m.t >= 1) m.t = 1;
        const from = projected.find((x) => x.bot.id === m.from);
        const to = projected.find((x) => x.bot.id === m.to);
        if (!from || !to) continue;
        const sx = from.p.x;
        const sy = from.p.y;
        const tx = to.p.x;
        const ty = to.p.y;
        const px = sx + (tx - sx) * m.t;
        const py = sy + (ty - sy) * m.t;
        const pulseSize = 6 * (1 + Math.sin(m.t * Math.PI) * 1.2);
        ctx.beginPath();
        ctx.fillStyle = "rgba(255,220,120,0.95)";
        ctx.arc(px, py, pulseSize, 0, Math.PI * 2);
        ctx.fill();
      }
      // remove finished messages
      messagesRef.current = messagesRef.current.filter((m) => m.t < 1);
 
      // Draw bots (closer bots on top)
      projected
        .sort((a, b) => b.p.s - a.p.s)
        .forEach(({ bot, p }) => {
          const scale = p.s;
          const size = Math.max(6, bot.size * scale);
          // glow
          ctx.beginPath();
          ctx.fillStyle = `rgba(70,100,160,${0.06 + 0.06 * scale})`;
          ctx.arc(p.x, p.y, size * 1.6, 0, Math.PI * 2);
          ctx.fill();
 
          // body circle
          ctx.beginPath();
          ctx.fillStyle = bot.color;
          ctx.arc(p.x, p.y, size, 0, Math.PI * 2);
          ctx.fill();
 
          // avatar or initials
          if (showAvatars && bot.img) {
            const imgSize = size * 1.6;
            ctx.save();
            ctx.beginPath();
            ctx.arc(p.x, p.y, imgSize / 2, 0, Math.PI * 2);
            ctx.clip();
            // draw image centered
            ctx.drawImage(
              bot.img,
              p.x - imgSize / 2,
              p.y - imgSize / 2,
              imgSize,
              imgSize,
            );
            ctx.restore();
          } else {
            // small center dot
            ctx.beginPath();
            ctx.fillStyle = "rgba(255,255,255,0.9)";
            ctx.arc(p.x, p.y, Math.max(2, size * 0.28), 0, Math.PI * 2);
            ctx.fill();
          }
        });
 
      rafRef.current = requestAnimationFrame(draw);
    }
 
    draw();
 
    return () => {
      ro.disconnect();
      canvas.removeEventListener("mousemove", onMove);
      canvas.removeEventListener("mouseleave", onLeave);
      clearInterval(messageInterval);
      Iif (rafRef.current) cancelAnimationFrame(rafRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bots, density, showAvatars, avatarUrls.join(",")]); // re-init if props change
 
  return (
    <div ref={containerRef} className="w-full h-full relative overflow-hidden">
      <canvas
        ref={canvasRef}
        className="block w-full h-full rounded-lg pointer-events-auto"
        style={{ display: "block", background: "transparent" }}
      />
      {/* Example overlay content (marketing copy) — optional, remove if you only want the canvas */}
      <div className="absolute inset-0 pointer-events-none flex justify-center top-0">
        <div className="text-center text-blue text-shadow-2xl pointer-events-none">
          <h2 className="text-3xl md:text-5xl font-bold drop-shadow-lg">
            Orchestrate Your LLM Fleet
          </h2>
          <p className="mt-2 text-sm md:text-lg opacity-80">
            Manage, monitor & connect intelligent agents.
          </p>
        </div>
      </div>
    </div>
  );
}