برنتی / می‌نویسم که فکر کنم

← آزمایش‌ها

شمارنده

§ شمارنده

یک کامپوننت‌ ساده با state داخلی؛ هر کلیک در جدول خروجی زیرِ آن ثبت می‌شود.

پیش‌نمایش

0

خروجی

هنوز چیزی ثبت نشده.

کد

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button.tsx";
import { Typography } from "@/components/ui/typography.tsx";
import { useLogger } from "@/components/pages/tests/experiment.tsx";

function formatTime(date: Date) {
  return date.toLocaleTimeString("en-GB", { hour12: false });
}

export function CounterDemo() {
  const [count, setCount] = useState(0);
  const { log, logTable } = useLogger();

  useEffect(() => {
    log("کامپوننت بارگذاری شد");
  }, [log]);

  function apply(delta: number, action: string) {
    const value = count + delta;
    setCount(value);
    logTable([{ time: formatTime(new Date()), action, value }], action);
  }

  return (
    <div className="flex items-center gap-4">
      <Button
        variant="secondary"
        aria-label="کاهش"
        onClick={() => apply(-1, "کاهش")}
        className="w-9 h-9 p-0"
      >
        −
      </Button>
      <Typography as="span" variant="mono" className="text-2xl text-text w-10 text-center">
        {count}
      </Typography>
      <Button
        variant="secondary"
        aria-label="افزایش"
        onClick={() => apply(1, "افزایش")}
        className="w-9 h-9 p-0"
      >
        +
      </Button>
    </div>
  );
}