Elffuss BraidHub

kikocis/continue public

main · 1.9 KiBRawPermalink
1import { CSSProperties, useEffect, useRef } from "react";
2
3/**
4 * useRenderDebug
5 *
6 * Developer utility to visualize component re-renders.
7 *
8 * - Returns a `ref` to attach to a container element and a `count` that
9 * increments on every render of the component using this hook.
10 * - On each render, it briefly adds a CSS class (default: `rerender-flash`)
11 * to the element for a quick visual flash.
12 * - Use together with <RenderCountBadge /> to show the render count inline.
13 *
14 * Options:
15 * - enabled: boolean to toggle the effect (default true)
16 * - flashClassName: class added on each render (default `rerender-flash`)
17 * - flashDurationMs: duration of the flash animation in ms (default 180)
18 */
19
20export function useRenderDebug(options?: {
21 enabled?: boolean;
22 flashClassName?: string;
23 flashDurationMs?: number;
24}) {
25 const {
26 enabled = true,
27 flashClassName = "rerender-flash",
28 flashDurationMs = 180,
29 } = options || {};
30
31 const ref = useRef<HTMLElement | null>(null);
32 const countRef = useRef(0);
33 countRef.current += 1;
34
35 useEffect(() => {
36 if (!enabled || !ref.current) return;
37 const el = ref.current;
38 el.classList.add(flashClassName);
39 const t = setTimeout(
40 () => el.classList.remove(flashClassName),
41 flashDurationMs,
42 );
43 return () => {
44 clearTimeout(t);
45 // Ensure we don't leave the flash class applied on cleanup
46 el.classList.remove(flashClassName);
47 };
48 });
49
50 return { ref, count: countRef.current, countRef } as const;
51}
52
53export function RenderCountBadge(props: {
54 count: number;
55 title?: string;
56 style?: CSSProperties;
57 className?: string;
58}) {
59 // Simple badge for use with useRenderDebug; keep lightweight.
60 const { count, title = `Renders: ${count}`, style, className } = props;
61 return (
62 <span
63 className={`render-count ${className || ""}`}
64 title={title}
65 style={style}
66 >
67 R{count}
68 </span>
69 );
70}