Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/six-clubs-grab.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@shipfox/react-ui": minor
---

Add Dot-grid component
9 changes: 5 additions & 4 deletions libs/react/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"framer-motion": "^12.23.24",
"gsap": "^3.13.0",
"lucide-react": "^0.553.0",
"react-day-picker": "^9.5.1",
"recharts": "^3.1.0",
Expand Down Expand Up @@ -75,16 +76,16 @@
"@testing-library/user-event": "^14.5.2",
"@types/react": "^19.1.11",
"@vitejs/plugin-react": "^5.0.4",
"@vitest/browser-playwright": "^4.0.8",
"@vitest/coverage-v8": "^4.0.8",
"date-fns": "^4.1.0",
"jsdom": "^27.0.0",
"playwright": "^1.56.1",
"storybook": "^10.0.0",
"storybook-addon-pseudo-states": "^10.0.0",
"tailwindcss": "^4.1.13",
"tw-animate-css": "^1.4.0",
"vite": "^7.1.7",
"vitest": "^4.0.8",
"playwright": "^1.56.1",
"@vitest/browser-playwright": "^4.0.8",
"@vitest/coverage-v8": "^4.0.8"
"vitest": "^4.0.8"
}
}
325 changes: 325 additions & 0 deletions libs/react/ui/src/components/dot-grid/dot-grid.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,325 @@
import {gsap} from 'gsap';
import {InertiaPlugin} from 'gsap/InertiaPlugin';
import type React from 'react';
import {useCallback, useEffect, useMemo, useRef} from 'react';
import {cn} from 'utils';

gsap.registerPlugin(InertiaPlugin);

const HEX_COLOR_REGEX = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;

const throttle = <T extends (...args: never[]) => void>(func: T, limit: number): T => {
let lastCall = 0;
return ((...args: Parameters<T>) => {
const now = performance.now();
if (now - lastCall >= limit) {
lastCall = now;
func(...args);
}
}) as T;
};
Comment on lines +11 to +20
Copy link

Copilot AI Nov 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using performance.now() in the throttle function but comparing against a timestamp that starts at 0. The first call will always execute, but subsequent calls within the throttle limit will be skipped even if they're the first real call. Consider initializing lastCall to -Infinity or performance.now() - limit to ensure consistent behavior.

Copilot uses AI. Check for mistakes.

interface Dot {
cx: number;
cy: number;
xOffset: number;
yOffset: number;
_inertiaApplied: boolean;
}

export interface DotGridProps {
dotSize?: number;
gap?: number;
baseColor?: string;
activeColor?: string;
proximity?: number;
speedTrigger?: number;
shockRadius?: number;
shockStrength?: number;
maxSpeed?: number;
resistance?: number;
returnDuration?: number;
className?: string;
style?: React.CSSProperties;
}

type RgbColor = {
r: number;
g: number;
b: number;
};

function hexToRgb(hex: string): RgbColor {
const m = hex.match(HEX_COLOR_REGEX);
if (!m) return {r: 0, g: 0, b: 0};
return {
r: parseInt(m[1], 16),
g: parseInt(m[2], 16),
b: parseInt(m[3], 16),
};
}
Comment on lines +52 to +60
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

hexToRgb silently treats non‑6‑digit hex (like #F00) as black

hexToRgb only matches 6‑digit hex via HEX_COLOR_REGEX, returning {r: 0, g: 0, b: 0} for anything else. Since the sign‑in story passes baseColor="#F00", the base RGB used for proximity blending becomes black instead of the intended red, which subtly changes the effect.

Recommend normalizing 3‑digit hex to 6‑digit before matching, so both forms work:

 function hexToRgb(hex: string): RgbColor {
-  const m = hex.match(HEX_COLOR_REGEX);
+  let value = hex.trim();
+
+  // Expand 3-digit #rgb to 6-digit #rrggbb for convenience.
+  if (value.length === 4 && value[0] === '#') {
+    value = `#${value[1]}${value[1]}${value[2]}${value[2]}${value[3]}${value[3]}`;
+  }
+
+  const m = value.match(HEX_COLOR_REGEX);
   if (!m) return {r: 0, g: 0, b: 0};
   return {
     r: parseInt(m[1], 16),
     g: parseInt(m[2], 16),
     b: parseInt(m[3], 16),
   };
 }

This keeps the existing regex and behavior while making the API friendlier to callers.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function hexToRgb(hex: string): RgbColor {
const m = hex.match(HEX_COLOR_REGEX);
if (!m) return {r: 0, g: 0, b: 0};
return {
r: parseInt(m[1], 16),
g: parseInt(m[2], 16),
b: parseInt(m[3], 16),
};
}
function hexToRgb(hex: string): RgbColor {
let value = hex.trim();
// Expand 3-digit #rgb to 6-digit #rrggbb for convenience.
if (value.length === 4 && value[0] === '#') {
value = `#${value[1]}${value[1]}${value[2]}${value[2]}${value[3]}${value[3]}`;
}
const m = value.match(HEX_COLOR_REGEX);
if (!m) return {r: 0, g: 0, b: 0};
return {
r: parseInt(m[1], 16),
g: parseInt(m[2], 16),
b: parseInt(m[3], 16),
};
}
🤖 Prompt for AI Agents
In libs/react/ui/src/components/dot-grid/dot-grid.tsx around lines 51 to 59,
hexToRgb currently only accepts 6‑digit hex and returns black for 3‑digit inputs
like "#F00"; normalize 3‑digit shorthand to 6‑digit before applying the existing
HEX_COLOR_REGEX (e.g. expand "#F00" to "#FF0000"), then run the same match/parse
logic and keep the current fallback of {r:0,g:0,b:0} for invalid values.


export function DotGrid({
dotSize = 16,
gap = 32,
baseColor = '#5227FF',
activeColor = '#5227FF',
proximity = 150,
speedTrigger = 100,
shockRadius = 250,
shockStrength = 5,
maxSpeed = 5000,
resistance = 750,
returnDuration = 1.5,
className = '',
style,
}: DotGridProps): React.JSX.Element {
const wrapperRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const dotsRef = useRef<Dot[]>([]);
const pointerRef = useRef({
x: 0,
y: 0,
vx: 0,
vy: 0,
speed: 0,
lastTime: 0,
lastX: 0,
lastY: 0,
});

const baseRgb = useMemo(() => hexToRgb(baseColor), [baseColor]);
const activeRgb = useMemo(() => hexToRgb(activeColor), [activeColor]);

const colorGradient = useMemo(() => {
const gradient: string[] = new Array(256);
for (let i = 0; i < 256; i++) {
const normalizedSqDist = i / 255;
const normalizedDist = Math.sqrt(normalizedSqDist);
const t = 1 - normalizedDist;
const r = Math.round(baseRgb.r + (activeRgb.r - baseRgb.r) * t);
const g = Math.round(baseRgb.g + (activeRgb.g - baseRgb.g) * t);
const b = Math.round(baseRgb.b + (activeRgb.b - baseRgb.b) * t);
gradient[i] = `rgb(${r},${g},${b})`;
}
return gradient;
}, [baseRgb, activeRgb]);

const circlePath = useMemo(() => {
if (typeof window === 'undefined' || !window.Path2D) return null;

const p = new Path2D();
p.arc(0, 0, dotSize / 2, 0, Math.PI * 2);
return p;
}, [dotSize]);

const buildGrid = useCallback(() => {
const wrap = wrapperRef.current;
const canvas = canvasRef.current;
if (!wrap || !canvas) return;

const {width, height} = wrap.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;

canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
const ctx = canvas.getContext('2d');
if (ctx) ctx.scale(dpr, dpr);

const cols = Math.floor((width + gap) / (dotSize + gap));
const rows = Math.floor((height + gap) / (dotSize + gap));
const cell = dotSize + gap;

const gridW = cell * cols - gap;
const gridH = cell * rows - gap;

const extraX = width - gridW;
const extraY = height - gridH;

const startX = extraX / 2 + dotSize / 2;
const startY = extraY / 2 + dotSize / 2;

const dots: Dot[] = [];
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const cx = startX + x * cell;
const cy = startY + y * cell;
dots.push({cx, cy, xOffset: 0, yOffset: 0, _inertiaApplied: false});
}
}
dotsRef.current = dots;
}, [dotSize, gap]);

useEffect(() => {
if (!circlePath) return;

let rafId: number;
const proxSq = proximity * proximity;

const draw = () => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
Copy link

Copilot AI Nov 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The canvas is cleared using logical dimensions (canvas.width, canvas.height) but should use physical dimensions. After scaling the context by dpr, you should clear using the logical dimensions:

ctx.clearRect(0, 0, canvas.width / (window.devicePixelRatio || 1), canvas.height / (window.devicePixelRatio || 1));

or store the logical width/height and use those instead.

Suggested change
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.clearRect(0, 0, canvas.width / (window.devicePixelRatio || 1), canvas.height / (window.devicePixelRatio || 1));

Copilot uses AI. Check for mistakes.

const {x: px, y: py} = pointerRef.current;

for (const dot of dotsRef.current) {
const ox = dot.cx + dot.xOffset;
const oy = dot.cy + dot.yOffset;
const dx = dot.cx - px;
const dy = dot.cy - py;
const dsq = dx * dx + dy * dy;

let fillColor = baseColor;
if (dsq <= proxSq) {
const normalizedSqDist = dsq / proxSq;
const index = Math.min(255, Math.max(0, Math.round(normalizedSqDist * 255)));
fillColor = colorGradient[index];
}

ctx.save();
ctx.translate(ox, oy);
ctx.fillStyle = fillColor;
ctx.fill(circlePath);
ctx.restore();
}

rafId = requestAnimationFrame(draw);
};

draw();
return () => cancelAnimationFrame(rafId);
}, [proximity, baseColor, colorGradient, circlePath]);

useEffect(() => {
buildGrid();
let ro: ResizeObserver | null = null;
if ('ResizeObserver' in window) {
ro = new ResizeObserver(buildGrid);
wrapperRef.current && ro.observe(wrapperRef.current);
} else {
(window as Window).addEventListener('resize', buildGrid);
}
return () => {
if (ro) ro.disconnect();
else window.removeEventListener('resize', buildGrid);
};
}, [buildGrid]);

useEffect(() => {
const onMove = (e: MouseEvent) => {
const now = performance.now();
const pr = pointerRef.current;
const dt = pr.lastTime ? now - pr.lastTime : 16;
Copy link

Copilot AI Nov 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The velocity calculation divides by dt which could be very small or even zero on the first call (when pr.lastTime is 0), potentially resulting in extremely large or infinite velocity values. While the maxSpeed clamping helps, it's safer to add a guard:

const dt = pr.lastTime ? Math.max(now - pr.lastTime, 1) : 16;

This ensures dt is never too small.

Suggested change
const dt = pr.lastTime ? now - pr.lastTime : 16;
const dt = pr.lastTime ? Math.max(now - pr.lastTime, 1) : 16;

Copilot uses AI. Check for mistakes.
const dx = e.clientX - pr.lastX;
const dy = e.clientY - pr.lastY;
let vx = (dx / dt) * 1000;
let vy = (dy / dt) * 1000;
let speed = Math.hypot(vx, vy);
if (speed > maxSpeed) {
const scale = maxSpeed / speed;
vx *= scale;
vy *= scale;
speed = maxSpeed;
}
pr.lastTime = now;
pr.lastX = e.clientX;
pr.lastY = e.clientY;
pr.vx = vx;
pr.vy = vy;
pr.speed = speed;

const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
pr.x = e.clientX - rect.left;
pr.y = e.clientY - rect.top;

for (const dot of dotsRef.current) {
const dist = Math.hypot(dot.cx - pr.x, dot.cy - pr.y);
if (speed > speedTrigger && dist < proximity && !dot._inertiaApplied) {
dot._inertiaApplied = true;
gsap.killTweensOf(dot);
const pushX = dot.cx - pr.x + vx * 0.005;
const pushY = dot.cy - pr.y + vy * 0.005;
gsap.to(dot, {
inertia: {xOffset: pushX, yOffset: pushY, resistance},
onComplete: () => {
gsap.to(dot, {
xOffset: 0,
yOffset: 0,
duration: returnDuration,
ease: 'elastic.out(1,0.75)',
});
dot._inertiaApplied = false;
},
});
}
}
};

const onClick = (e: MouseEvent) => {
const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
const cx = e.clientX - rect.left;
const cy = e.clientY - rect.top;
for (const dot of dotsRef.current) {
const dist = Math.hypot(dot.cx - cx, dot.cy - cy);
if (dist < shockRadius && !dot._inertiaApplied) {
dot._inertiaApplied = true;
gsap.killTweensOf(dot);
const falloff = Math.max(0, 1 - dist / shockRadius);
const pushX = (dot.cx - cx) * shockStrength * falloff;
const pushY = (dot.cy - cy) * shockStrength * falloff;
gsap.to(dot, {
inertia: {xOffset: pushX, yOffset: pushY, resistance},
onComplete: () => {
gsap.to(dot, {
xOffset: 0,
yOffset: 0,
duration: returnDuration,
ease: 'elastic.out(1,0.75)',
});
dot._inertiaApplied = false;
},
});
Comment on lines +249 to +290
Copy link

Copilot AI Nov 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate code: The inertia animation and return-to-origin logic is duplicated between the mouse move handler (lines 237-248) and click handler (lines 267-278). Consider extracting this into a reusable function to improve maintainability.

Copilot uses AI. Check for mistakes.
}
}
};

const throttledMove = throttle(onMove, 50) as (e: MouseEvent) => void;
const wrapper = wrapperRef.current;
if (wrapper) {
wrapper.addEventListener('mousemove', throttledMove, {passive: true});
wrapper.addEventListener('click', onClick);
}
return () => {
if (wrapper) {
wrapper.removeEventListener('mousemove', throttledMove);
wrapper.removeEventListener('click', onClick);
}
};
}, [maxSpeed, speedTrigger, proximity, resistance, returnDuration, shockRadius, shockStrength]);

return (
<section
className={cn('p-4 flex items-center justify-center h-full w-full relative', className)}
style={style}
role="presentation"
>
<div ref={wrapperRef} className="w-full h-full relative">
{/** biome-ignore lint/a11y/noAriaHiddenOnFocusable: <canvas is not focusable> */}
<canvas
ref={canvasRef}
className="absolute inset-0 w-full h-full pointer-events-none"
aria-hidden="true"
/>
</div>
</section>
);
}
1 change: 1 addition & 0 deletions libs/react/ui/src/components/dot-grid/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './dot-grid';
1 change: 1 addition & 0 deletions libs/react/ui/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from './badge';
export * from './button';
export * from './checkbox';
export * from './code-block';
export * from './dot-grid';
export * from './dynamic-item';
export * from './icon';
export * from './inline-tips';
Expand Down
Loading