RendyUI English

区块 / Build health

Build health

Developer tools · React / TypeScript Free

录制演示

Build health 实现预览

源码

dev-tools-build-health.tsx
/* Build health — free block published by UI Stacks (public page source).
   Kept verbatim: the author publishes this block free, in full, at https://uistacks.dev/blocks/dev-tools-build-health
   See replica/README.md for provenance. */
"use client";

import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { MotionConfig, motion } from "motion/react";
import { CircleAlert, CircleX, RotateCw } from "lucide-react";
import { Button } from "../components/button";
import { Skeleton, SkeletonGroup } from "../components/skeleton";

/* ── Sample data: replace with your own ─────────────────────── */

export type BuildDay = { day: string; date: string; runs: number; green: number };
export type BuildHealthState = "default" | "loading" | "error";

export type BuildHealth = {
  days: BuildDay[];
  /** First-try green target, in percent. */
  target: number;
  /** The chart's floor, in percent (the top is 100). */
  floor: number;
  /** A day under this rate is drawn in the warning colour. */
  warnBelow: number;
  /** Failed runs that passed on a re-run. */
  passedOnRerun: number;
  medianRun: string;
};

/** main and PRs, Mon 19 – Sun 25 Oct 2026: 1,486 runs, 1,400 green on the first try (94.21%), 86 failed. */
const SAMPLE: BuildHealth = {
  days: [
    { day: "Mon", date: "19 Oct", runs: 263, green: 250 },
    { day: "Tue", date: "20 Oct", runs: 261, green: 248 },
    { day: "Wed", date: "21 Oct", runs: 261, green: 247 },
    { day: "Thu", date: "22 Oct", runs: 259, green: 244 },
    { day: "Fri", date: "23 Oct", runs: 235, green: 220 },
    { day: "Sat", date: "24 Oct", runs: 116, green: 110 },
    { day: "Sun", date: "25 Oct", runs: 91, green: 81 },
  ],
  target: 95,
  floor: 85,
  warnBelow: 90,
  passedOnRerun: 71,
  medianRun: "6m 18s",
};

/* ── Block ──────────────────────────────────────────────────── */

export interface BuildHealthProps {
  className?: string;
  state?: BuildHealthState;
  data?: BuildHealth;
  /** "main and PRs · 19–25 Oct". */
  period?: string;
  /** View the failed runs (the header action). */
  onViewFailed?: () => void;
  /** Called by Retry in the error state. Without it, Retry reloads the sample locally. */
  onRetry?: () => void;
}

// Secondary buttons get a raised fill in Dark (white 15% over the card), as in the Figma.
const RAISED = "dark:bg-[color-mix(in_srgb,var(--fg)_15%,transparent)]";
// Figma chart/stack-2: the daily columns.
const STACK_2 = "bg-[#949499] dark:bg-[#747478]";
// From 560 px of room the chart and the detail rows sit side by side.
const WIDE = "flex flex-col gap-4 @min-[560px]:grid @min-[560px]:grid-cols-2 @min-[560px]:gap-x-10";
const PLOT = 72;

const n = (v: number) => v.toLocaleString("en-US");
const rate = (d: { runs: number; green: number }) => (d.runs ? (d.green / d.runs) * 100 : 0);

export default function DevToolsBuildHealthBlock({ className = "", state = "default", data = SAMPLE, period = "main and PRs · 19–25 Oct", onViewFailed, onRetry }: BuildHealthProps) {
  const id = useId();
  const [retry, setRetry] = useState<{ from: BuildHealthState; phase: "loading" | "done" } | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);
  const local = retry?.from === state ? retry : null;
  const shown: BuildHealthState = local ? (local.phase === "loading" ? "loading" : "default") : state;
  const [announce, setAnnounce] = useState("");

  const retryNow = () => {
    if (onRetry) return onRetry();
    setRetry({ from: state, phase: "loading" });
    setAnnounce("Loading CI runs");
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      setRetry({ from: state, phase: "done" });
      setAnnounce("CI runs loaded");
    }, 1200);
  };

  const runs = data.days.reduce((s, d) => s + d.runs, 0);
  const green = data.days.reduce((s, d) => s + d.green, 0);
  const failed = runs - green;
  const body = <Body data={data} runs={runs} green={green} failed={failed} />;
  // With a handler the action is yours; without one the demo says what would happen, so the button is never a dead end.
  const viewFailed = () => (onViewFailed ? onViewFailed() : setAnnounce(`Opening the ${n(failed)} failed runs`));

  return (
    <MotionConfig reducedMotion="user">
      <section
        aria-labelledby={id}
        aria-busy={shown === "loading" || undefined}
        className={"@container flex h-full w-full min-w-0 flex-col gap-4 rounded-[24px] bg-surface p-5 text-fg shadow-[var(--shadow-card)] " + className}
      >
        <header className="flex flex-col gap-1">
          <div className="flex h-8 items-center gap-2">
            <h2 id={id} className="min-w-0 flex-1 truncate text-[13px] font-medium leading-5">
              Build health
            </h2>
            {shown === "default" && (
              <Button variant="ghost" size="sm" className="-mr-3" leadingIcon={<CircleX strokeWidth={1.5} className="size-5!" />} onClick={viewFailed}>
                View {n(failed)} failed
              </Button>
            )}
            {shown === "loading" && <Skeleton width={104} height={12} radius={6} />}
          </div>
          <p className="truncate text-[12px] leading-4 text-fg-muted">{period}</p>
        </header>

        {shown === "default" ? (
          body
        ) : shown === "loading" ? (
          <LoadingBody />
        ) : (
          <div className="grid flex-1">
            <div aria-hidden className="invisible flex flex-col gap-4 [grid-area:1/1]">
              {body}
            </div>
            <StateMessage
              icon={<CircleAlert aria-hidden className="size-5" strokeWidth={1.5} />}
              title="Couldn't load CI runs"
              text="The request timed out after 30 s. Last updated 17:03 UTC."
              action="Retry"
              actionIcon={<RotateCw strokeWidth={1.5} className="size-5!" />}
              onAction={retryNow}
            />
          </div>
        )}
        <span className="sr-only" role="status" aria-live="polite">
          {announce}
        </span>
      </section>
    </MotionConfig>
  );
}

function Body({ data, runs, green, failed }: { data: BuildHealth; runs: number; green: number; failed: number }) {
  const overall = runs ? (green / runs) * 100 : 0;
  const gap = data.target - Math.round(overall * 10) / 10;
  const rows = [
    { label: "Green on the first try", value: `${n(green)} of ${n(runs)}` },
    { label: "Failed, then passed on re-run", value: `${n(data.passedOnRerun)} of ${n(failed)}` },
    { label: "Median run", value: data.medianRun },
  ];
  return (
    <div className={WIDE}>
      <div className="flex flex-col gap-4">
        <p className="flex min-w-0 items-baseline gap-2">
          <span className="text-[32px] font-medium leading-10 tracking-[-0.03em] tabular-nums">{overall.toFixed(1)}%</span>
          <span className="min-w-0 flex-1 truncate text-[12px] leading-4 text-fg-muted">
            green · {gap > 0 ? `${gap.toFixed(1)} pt below the ${data.target}% target` : `at or above the ${data.target}% target`}
          </span>
        </p>
        <Columns data={data} />
      </div>
      <dl className="flex flex-col gap-1">
        {rows.map((r) => (
          <div key={r.label} className="flex h-5 items-center gap-2 text-[13px] leading-5">
            <dt className="min-w-0 flex-1 truncate text-fg-muted">{r.label}</dt>
            <dd className="shrink-0 text-right font-medium tabular-nums">{r.value}</dd>
          </div>
        ))}
      </dl>
    </div>
  );
}

/**
 * Daily first-try green rate as columns from the floor (bottom) to 100% (top), with the target as a line over them.
 * Each column takes focus (one tab stop, arrows move) and shows its numbers in a tooltip.
 */
function Columns({ data }: { data: BuildHealth }) {
  const span = 100 - data.floor;
  const y = (v: number) => (Math.min(100, Math.max(data.floor, v)) - data.floor) / span;
  const target = y(data.target);
  const [active, setActive] = useState(data.days.length - 1);
  const [focused, setFocused] = useState(false);
  const [hovered, setHovered] = useState<number | null>(null);
  const refs = useRef<(HTMLSpanElement | null)[]>([]);
  const tip = hovered ?? (focused ? active : null);
  const worst = data.days.reduce((a, d) => (rate(d) < rate(a) ? d : a), data.days[0]);

  const onKey = (e: KeyboardEvent) => {
    const last = data.days.length - 1;
    const next = e.key === "ArrowRight" ? Math.min(last, active + 1) : e.key === "ArrowLeft" ? Math.max(0, active - 1) : e.key === "Home" ? 0 : e.key === "End" ? last : null;
    if (next === null) return;
    e.preventDefault();
    setActive(next);
    refs.current[next]?.focus();
  };

  return (
    <div className="flex flex-col gap-1 text-[12px] leading-4 text-fg-muted">
      <div className="flex gap-2">
        <div aria-hidden className="relative w-8 shrink-0 tabular-nums" style={{ height: PLOT }}>
          <span className="absolute left-0" style={{ top: (1 - target) * PLOT - 8 }}>
            {data.target}%
          </span>
          <span className="absolute bottom-0 left-0">{data.floor}%</span>
        </div>
        <div
          role="group"
          aria-label={`First-try green rate by day, ${data.days[0].date} to ${data.days[data.days.length - 1].date}, target ${data.target}%. Lowest ${worst.day} ${rate(worst).toFixed(1)}%. Use the arrow keys to read each day.`}
          className="relative flex min-w-0 flex-1 items-end gap-2"
          style={{ height: PLOT }}
          onKeyDown={onKey}
        >
          {data.days.map((d, i) => {
            const r = rate(d);
            return (
              <span
                key={d.date}
                ref={(el) => {
                  refs.current[i] = el;
                }}
                role="img"
                tabIndex={i === active ? 0 : -1}
                aria-label={`${d.day} ${d.date} · ${n(d.green)} of ${n(d.runs)} green · ${r.toFixed(1)}%`}
                onFocus={() => {
                  setActive(i);
                  setFocused(true);
                }}
                onBlur={() => setFocused(false)}
                onPointerEnter={() => setHovered(i)}
                onPointerLeave={() => setHovered(null)}
                className="relative flex h-full min-w-0 flex-1 items-end rounded-[4px] outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)]"
              >
                <motion.span
                  className={`block w-full origin-bottom rounded-t-[4px] ${r < data.warnBelow ? "bg-warning-text" : STACK_2}`}
                  style={{ height: Math.max(2, y(r) * PLOT) }}
                  initial={{ scaleY: 0 }}
                  animate={{ scaleY: 1 }}
                  transition={{ duration: 0.4, delay: i * 0.03, ease: [0.22, 1, 0.36, 1] }}
                />
                {tip === i && (
                  <span
                    aria-hidden
                    className={`pointer-events-none absolute bottom-full z-10 mb-1.5 whitespace-nowrap rounded-[8px] bg-fg px-2 py-1 text-[12px] leading-4 text-bg tabular-nums shadow-[var(--shadow-card)] ${
                      i === 0 ? "left-0" : i === data.days.length - 1 ? "right-0" : "left-1/2 -translate-x-1/2"
                    }`}
                  >
                    {d.day} {d.date} · {n(d.green)} of {n(d.runs)} green · {r.toFixed(1)}%
                  </span>
                )}
              </span>
            );
          })}
          <span aria-hidden className="pointer-events-none absolute inset-x-0 h-px bg-fg-subtle" style={{ top: (1 - target) * PLOT }} />
        </div>
      </div>
      <div aria-hidden className="flex gap-2">
        <span className="w-8 shrink-0" />
        <div className="flex min-w-0 flex-1 gap-2">
          {data.days.map((d) => (
            <span key={d.date} className="min-w-0 flex-1 truncate text-center">
              {d.day}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

function StateMessage({ icon, title, text, action, actionIcon, onAction }: { icon: ReactNode; title: string; text: string; action: string; actionIcon: ReactNode; onAction?: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center gap-2 text-center [grid-area:1/1]">
      {icon}
      <div role="status" className="flex flex-col items-center gap-2">
        <p className="text-[13px] font-medium leading-5">{title}</p>
        <p className="max-w-[320px] text-balance text-[12px] leading-4 text-fg-muted">{text}</p>
      </div>
      <div className="pt-2">
        <Button variant="secondary" size="sm" className={RAISED} leadingIcon={actionIcon} onClick={onAction}>
          {action}
        </Button>
      </div>
    </div>
  );
}

// Slots mirror the Default body (hero 40, chart 92, three rows of 20), so the card keeps its height.
function LoadingBody() {
  const heights = [48, 48, 46, 44, 41, 47, 19];
  return (
    <SkeletonGroup label="Loading Build health" className={WIDE}>
      <div className="flex flex-col gap-4">
        <div className="flex h-10 items-center gap-2">
          <Skeleton shape="block" width={84} height={24} radius={6} />
          <Skeleton width={148} height={10} radius={6} className="mt-2" />
        </div>
        <div className="flex flex-col gap-1">
          <div className="flex gap-2">
            <span className="w-8 shrink-0" />
            <div className="relative flex min-w-0 flex-1 items-end gap-2" style={{ height: PLOT }}>
              {heights.map((h, i) => (
                <Skeleton key={i} shape="block" width="auto" height={h} radius={4} delay={i * 0.05} className="min-w-0 flex-1" />
              ))}
              <span aria-hidden className="absolute inset-x-0 top-6 h-px bg-fg-subtle opacity-60" />
            </div>
          </div>
          <span className="h-4" />
        </div>
      </div>
      <div className="flex flex-col gap-1">
        {[132, 168, 72].map((w, i) => (
          <div key={i} className="flex h-5 items-center justify-between">
            <Skeleton width={w} height={12} radius={6} />
            <Skeleton width={[88, 44, 44][i]} height={12} radius={6} />
          </div>
        ))}
      </div>
    </SkeletonGroup>
  );
}

使用说明

把 TSX 加入 React 项目,并安装组件引用的依赖。页面样式依赖 Tailwind CSS 与 主题变量。

包依赖 · lucide-react、motion、react

共享源码 · button.tsx、skeleton.tsx