FLOWDocs
Components

数据展示

Table、Pagination、Carousel、Chart、Avatar、Item、PresenceIndicator、PresenceRing、ProfilePill。

Table

语义化的表格封装。导出:Table、TableHeader、TableBody、TableFooter、TableHead、TableRow、TableCell、TableCaption。

在 GitHub 上查看源码 →

用法:

import {
  Table, TableHeader, TableBody, TableRow, TableHead, TableCell, TableCaption,
} from "@flow-industries/ui/components/table";

<Table>
  <TableCaption>近期部署</TableCaption>
  <TableHeader>
    <TableRow>
      <TableHead>应用</TableHead>
      <TableHead>服务器</TableHead>
      <TableHead className="text-right">已运行</TableHead>
    </TableRow>
  </TableHeader>
  <TableBody>
    <TableRow>
      <TableCell>site</TableCell>
      <TableCell>fl-1</TableCell>
      <TableCell className="text-right">3d 4h</TableCell>
    </TableRow>
  </TableBody>
</Table>

源码:

components/ui/table.tsx
"use client";

import type * as React from "react";

import { cn } from "../../utils/cn";

function Table({ className, ...props }: React.ComponentProps<"table">) {
  return (
    <div
      data-slot="table-container"
      className="relative w-full overflow-x-auto"
    >
      <table
        data-slot="table"
        className={cn("w-full caption-bottom text-sm", className)}
        {...props}
      />
    </div>
  );
}

function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
  return (
    <thead
      data-slot="table-header"
      className={cn(
        "[&_tr]:border-b-[length:var(--border-width)] [&_tr]:hover:bg-transparent",
        className,
      )}
      {...props}
    />
  );
}

function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
  return (
    <tbody
      data-slot="table-body"
      className={cn("[&_tr:last-child]:border-0", className)}
      {...props}
    />
  );
}

function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
  return (
    <tfoot
      data-slot="table-footer"
      className={cn(
        "border-t-[length:var(--border-width)] bg-muted/50 font-medium [&>tr]:last:border-b-0",
        className,
      )}
      {...props}
    />
  );
}

function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
  return (
    <tr
      data-slot="table-row"
      className={cn(
        "border-b-[length:var(--border-width)] transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
        className,
      )}
      {...props}
    />
  );
}

function TableHead({ className, ...props }: React.ComponentProps<"th">) {
  return (
    <th
      data-slot="table-head"
      className={cn(
        "h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
        className,
      )}
      {...props}
    />
  );
}

function TableCell({ className, ...props }: React.ComponentProps<"td">) {
  return (
    <td
      data-slot="table-cell"
      className={cn(
        "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
        className,
      )}
      {...props}
    />
  );
}

function TableCaption({
  className,
  ...props
}: React.ComponentProps<"caption">) {
  return (
    <caption
      data-slot="table-caption"
      className={cn("mt-4 text-sm text-muted-foreground", className)}
      {...props}
    />
  );
}

export {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow,
};

Pagination

导出:Pagination、PaginationContent、PaginationEllipsis、PaginationItem、PaginationLink、PaginationNext、PaginationPrevious。

在 GitHub 上查看源码 →

用法:

import {
  Pagination, PaginationContent, PaginationItem,
  PaginationLink, PaginationPrevious, PaginationNext, PaginationEllipsis,
} from "@flow-industries/ui/components/pagination";

<Pagination>
  <PaginationContent>
    <PaginationItem><PaginationPrevious href="#" /></PaginationItem>
    <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
    <PaginationItem><PaginationLink href="#" isActive>2</PaginationLink></PaginationItem>
    <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
    <PaginationItem><PaginationEllipsis /></PaginationItem>
    <PaginationItem><PaginationNext href="#" /></PaginationItem>
  </PaginationContent>
</Pagination>

源码:

components/ui/pagination.tsx
import {
  ChevronLeftIcon,
  ChevronRightIcon,
  MoreHorizontalIcon,
} from "lucide-react";
import type * as React from "react";
import { cn } from "../../utils/cn";
import { Button } from "./button";

function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
  return (
    <nav
      aria-label="pagination"
      data-slot="pagination"
      className={cn("mx-auto flex w-full justify-center", className)}
      {...props}
    />
  );
}

function PaginationContent({
  className,
  ...props
}: React.ComponentProps<"ul">) {
  return (
    <ul
      data-slot="pagination-content"
      className={cn("flex items-center gap-0.5", className)}
      {...props}
    />
  );
}

function PaginationItem({ ...props }: React.ComponentProps<"li">) {
  return <li data-slot="pagination-item" {...props} />;
}

type PaginationLinkProps = {
  isActive?: boolean;
} & Pick<React.ComponentProps<typeof Button>, "size"> &
  React.ComponentProps<"a">;

function PaginationLink({
  className,
  isActive,
  size = "icon",
  ...props
}: PaginationLinkProps) {
  return (
    <Button
      variant={isActive ? "outline" : "ghost"}
      size={size}
      className={cn(className)}
      nativeButton={false}
      render={
        <a
          aria-current={isActive ? "page" : undefined}
          data-slot="pagination-link"
          data-active={isActive}
          {...props}
        />
      }
    />
  );
}

function PaginationPrevious({
  className,
  text = "Previous",
  ...props
}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
  return (
    <PaginationLink
      aria-label="Go to previous page"
      size="default"
      className={cn("pl-1.5!", className)}
      {...props}
    >
      <ChevronLeftIcon data-icon="inline-start" />
      <span className="hidden sm:block">{text}</span>
    </PaginationLink>
  );
}

function PaginationNext({
  className,
  text = "Next",
  ...props
}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
  return (
    <PaginationLink
      aria-label="Go to next page"
      size="default"
      className={cn("pr-1.5!", className)}
      {...props}
    >
      <span className="hidden sm:block">{text}</span>
      <ChevronRightIcon data-icon="inline-end" />
    </PaginationLink>
  );
}

function PaginationEllipsis({
  className,
  ...props
}: React.ComponentProps<"span">) {
  return (
    <span
      aria-hidden
      data-slot="pagination-ellipsis"
      className={cn(
        "flex size-8 items-center justify-center [&_svg:not([class*='size-'])]:size-4",
        className,
      )}
      {...props}
    >
      <MoreHorizontalIcon />
      <span className="sr-only">More pages</span>
    </span>
  );
}

export {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
};

由 Embla 驱动的图片轮播,支持键盘与滑动。导出:Carousel、CarouselContent、CarouselItem、CarouselPrevious、CarouselNext、useCarousel,以及 CarouselApi 类型。

在 GitHub 上查看源码 →

用法:

import {
  Carousel, CarouselContent, CarouselItem,
  CarouselPrevious, CarouselNext,
} from "@flow-industries/ui/components/carousel";

<Carousel>
  <CarouselContent>
    <CarouselItem><img src="/1.jpg" /></CarouselItem>
    <CarouselItem><img src="/2.jpg" /></CarouselItem>
    <CarouselItem><img src="/3.jpg" /></CarouselItem>
  </CarouselContent>
  <CarouselPrevious />
  <CarouselNext />
</Carousel>

源码:

components/ui/carousel.tsx
"use client";

import useEmblaCarousel, {
  type UseEmblaCarouselType,
} from "embla-carousel-react";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import * as React from "react";
import { cn } from "../../utils/cn";
import { Button } from "./button";

type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];

type CarouselProps = {
  opts?: CarouselOptions;
  plugins?: CarouselPlugin;
  orientation?: "horizontal" | "vertical";
  setApi?: (api: CarouselApi) => void;
};

type CarouselContextProps = {
  carouselRef: ReturnType<typeof useEmblaCarousel>[0];
  api: ReturnType<typeof useEmblaCarousel>[1];
  scrollPrev: () => void;
  scrollNext: () => void;
  canScrollPrev: boolean;
  canScrollNext: boolean;
} & CarouselProps;

const CarouselContext = React.createContext<CarouselContextProps | null>(null);

function useCarousel() {
  const context = React.useContext(CarouselContext);

  if (!context) {
    throw new Error("useCarousel must be used within a <Carousel />");
  }

  return context;
}

function Carousel({
  orientation = "horizontal",
  opts,
  setApi,
  plugins,
  className,
  children,
  ...props
}: React.ComponentProps<"div"> & CarouselProps) {
  const [carouselRef, api] = useEmblaCarousel(
    {
      ...opts,
      axis: orientation === "horizontal" ? "x" : "y",
    },
    plugins,
  );
  const [canScrollPrev, setCanScrollPrev] = React.useState(false);
  const [canScrollNext, setCanScrollNext] = React.useState(false);

  const onSelect = React.useCallback((api: CarouselApi) => {
    if (!api) return;
    setCanScrollPrev(api.canScrollPrev());
    setCanScrollNext(api.canScrollNext());
  }, []);

  const scrollPrev = React.useCallback(() => {
    api?.scrollPrev();
  }, [api]);

  const scrollNext = React.useCallback(() => {
    api?.scrollNext();
  }, [api]);

  const handleKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (event.key === "ArrowLeft") {
        event.preventDefault();
        scrollPrev();
      } else if (event.key === "ArrowRight") {
        event.preventDefault();
        scrollNext();
      }
    },
    [scrollPrev, scrollNext],
  );

  React.useEffect(() => {
    if (!api || !setApi) return;
    setApi(api);
  }, [api, setApi]);

  React.useEffect(() => {
    if (!api) return;
    onSelect(api);
    api.on("reInit", onSelect);
    api.on("select", onSelect);

    return () => {
      api?.off("select", onSelect);
    };
  }, [api, onSelect]);

  return (
    <CarouselContext.Provider
      value={{
        carouselRef,
        api: api,
        opts,
        orientation:
          orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
        scrollPrev,
        scrollNext,
        canScrollPrev,
        canScrollNext,
      }}
    >
      {/* biome-ignore lint/a11y/useSemanticElements: carousel region with aria-roledescription is the accepted embla/shadcn pattern */}
      <div
        onKeyDownCapture={handleKeyDown}
        className={cn("relative", className)}
        role="region"
        aria-roledescription="carousel"
        data-slot="carousel"
        {...props}
      >
        {children}
      </div>
    </CarouselContext.Provider>
  );
}

function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
  const { carouselRef, orientation } = useCarousel();

  return (
    <div
      ref={carouselRef}
      className="overflow-hidden"
      data-slot="carousel-content"
    >
      <div
        className={cn(
          "flex",
          orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
          className,
        )}
        {...props}
      />
    </div>
  );
}

function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
  const { orientation } = useCarousel();

  return (
    // biome-ignore lint/a11y/useSemanticElements: slide group with aria-roledescription is the accepted embla/shadcn pattern
    <div
      role="group"
      aria-roledescription="slide"
      data-slot="carousel-item"
      className={cn(
        "min-w-0 shrink-0 grow-0 basis-full",
        orientation === "horizontal" ? "pl-4" : "pt-4",
        className,
      )}
      {...props}
    />
  );
}

function CarouselPrevious({
  className,
  variant = "outline",
  size = "icon-sm",
  ...props
}: React.ComponentProps<typeof Button>) {
  const { orientation, scrollPrev, canScrollPrev } = useCarousel();

  return (
    <Button
      data-slot="carousel-previous"
      variant={variant}
      size={size}
      className={cn(
        "absolute touch-manipulation rounded-full",
        orientation === "horizontal"
          ? "top-1/2 -left-12 -translate-y-1/2 active:-translate-y-1/2!"
          : "-top-12 left-1/2 -translate-x-1/2 rotate-90 active:-translate-x-1/2!",
        className,
      )}
      disabled={!canScrollPrev}
      onClick={scrollPrev}
      {...props}
    >
      <ChevronLeftIcon />
      <span className="sr-only">Previous slide</span>
    </Button>
  );
}

function CarouselNext({
  className,
  variant = "outline",
  size = "icon-sm",
  ...props
}: React.ComponentProps<typeof Button>) {
  const { orientation, scrollNext, canScrollNext } = useCarousel();

  return (
    <Button
      data-slot="carousel-next"
      variant={variant}
      size={size}
      className={cn(
        "absolute touch-manipulation rounded-full",
        orientation === "horizontal"
          ? "top-1/2 -right-12 -translate-y-1/2 active:-translate-y-1/2!"
          : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90 active:-translate-x-1/2!",
        className,
      )}
      disabled={!canScrollNext}
      onClick={scrollNext}
      {...props}
    >
      <ChevronRightIcon />
      <span className="sr-only">Next slide</span>
    </Button>
  );
}

export {
  Carousel,
  type CarouselApi,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  useCarousel,
};

Chart

对 Recharts 的封装,支持 Flow token 主题。导出:ChartContainer、ChartTooltip、ChartTooltipContent、ChartLegend、ChartLegendContent、ChartStyle、ChartConfig(类型)。

在 GitHub 上查看源码 →

用法:

import {
  ChartContainer, ChartTooltip, ChartTooltipContent,
} from "@flow-industries/ui/components/chart";
import { Bar, BarChart, XAxis, YAxis } from "recharts";

const chartConfig = {
  visits: { label: "访问量", color: "var(--color-blue)" },
};

<ChartContainer config={chartConfig}>
  <BarChart data={data}>
    <XAxis dataKey="month" />
    <YAxis />
    <ChartTooltip content={<ChartTooltipContent />} />
    <Bar dataKey="visits" fill="var(--color-visits)" />
  </BarChart>
</ChartContainer>

Chart 组件约 390 行 Recharts 整合代码。需要 copy-paste 时请查看上面链接中的完整源码。颜色会解析为 Flow token,因此切换 .dark 时图表会随之自动换肤。

Avatar

带 fallback、角标与分组组合的用户头像。导出:Avatar、AvatarImage、AvatarFallback、AvatarGroup、AvatarGroupCount、AvatarBadge、AvatarPlaceholder。尺寸:sm、default、lg。头像使用 rounded-squircle 形状而非完整圆形,空的 AvatarFallback 默认渲染 AvatarPlaceholder——一个匿名的头肩剪影。

在 GitHub 上查看源码 →

用法:

import {
  Avatar, AvatarImage, AvatarFallback, AvatarGroup, AvatarBadge,
} from "@flow-industries/ui/components/avatar";

<Avatar>
  <AvatarImage src="/alice.jpg" alt="Alice" />
  <AvatarFallback>AL</AvatarFallback>
  <AvatarBadge />
</Avatar>

<AvatarGroup>
  <Avatar><AvatarImage src="/a.jpg" /><AvatarFallback>A</AvatarFallback></Avatar>
  <Avatar><AvatarImage src="/b.jpg" /><AvatarFallback>B</AvatarFallback></Avatar>
  <Avatar><AvatarImage src="/c.jpg" /><AvatarFallback>C</AvatarFallback></Avatar>
</AvatarGroup>

源码:

components/ui/avatar.tsx
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar";
import type * as React from "react";

import { cn } from "../../utils/cn";

function Avatar({
  className,
  size = "default",
  ...props
}: AvatarPrimitive.Root.Props & {
  size?: "default" | "sm" | "lg";
}) {
  return (
    <AvatarPrimitive.Root
      data-slot="avatar"
      data-size={size}
      className={cn(
        "group/avatar relative flex size-8 shrink-0 rounded-squircle select-none after:absolute after:inset-0 after:rounded-squircle after:border-[length:var(--border-width)] after:border-secondary after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
        // An offline presence ring draws nothing; the photo greys instead.
        "has-[>[data-slot=presence-ring][data-status=offline]]:opacity-55 has-[>[data-slot=presence-ring][data-status=offline]]:grayscale",
        className,
      )}
      {...props}
    />
  );
}

function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
  return (
    <AvatarPrimitive.Image
      data-slot="avatar-image"
      className={cn(
        "aspect-square size-full rounded-squircle object-cover",
        className,
      )}
      {...props}
    />
  );
}

/**
 * Anonymous head-and-shoulders silhouette — the stand-in for a user with no
 * avatar image. Scales to its box, so it works at any avatar size. The
 * shoulders are stroked with a round join so their base corners stay as soft
 * as the squircle they sit in.
 */
function AvatarPlaceholder({
  className,
  ...props
}: React.ComponentProps<"svg">) {
  return (
    <svg
      data-slot="avatar-placeholder"
      viewBox="0 0 48 48"
      fill="currentColor"
      aria-hidden="true"
      className={cn("size-full", className)}
      {...props}
    >
      <circle cx="24" cy="18" r="7.7" />
      <path
        d="M15 41.4a9 6 0 0 1 18 0Z"
        stroke="currentColor"
        strokeWidth="6"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function AvatarFallback({
  children,
  className,
  ...props
}: AvatarPrimitive.Fallback.Props) {
  return (
    <AvatarPrimitive.Fallback
      data-slot="avatar-fallback"
      className={cn(
        "flex size-full items-center justify-center rounded-squircle bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
        className,
      )}
      {...props}
    >
      {children ?? <AvatarPlaceholder />}
    </AvatarPrimitive.Fallback>
  );
}

function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
  return (
    <span
      data-slot="avatar-badge"
      className={cn(
        "absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
        "group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
        "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
        "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
        className,
      )}
      {...props}
    />
  );
}

function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="avatar-group"
      className={cn(
        "group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
        className,
      )}
      {...props}
    />
  );
}

function AvatarGroupCount({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="avatar-group-count"
      className={cn(
        "relative flex size-8 shrink-0 items-center justify-center rounded-squircle bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
        className,
      )}
      {...props}
    />
  );
}

export {
  Avatar,
  AvatarBadge,
  AvatarFallback,
  AvatarGroup,
  AvatarGroupCount,
  AvatarImage,
  AvatarPlaceholder,
};

PresenceIndicator

用户的可用状态,由调用方提供——两个组件都不发起任何请求,也不保存生命周期状态。PresenceRing 把它画成头像外的一圈环:把它放在 Avatar 内。环宽 2px,离头像 2px,圆角为头像半径加 4px,角形与头像相同,因此与 squircle 保持同心;它比头像向外多出 4px,请在头像周围留出这部分空间。ProfilePill 会替你画好。PresenceIndicator 是放在文字旁表示状态的小圆点,尺寸为 sm 和 default;当相邻文本已说明状态时,传入 aria-hidden。状态有 online、idle、busy、invisible 和 offline;缺失状态不渲染任何内容。invisible 仅在明确的自身视图(self)中显示,对其他人则显示为 offline。每种状态都有无障碍名称。导出:PresenceRing、PresenceIndicator,以及 PresenceStatus 类型。

在 GitHub 上查看源码 →

用法:

import { Avatar, AvatarFallback, AvatarImage } from "@flow-industries/ui/components/avatar";
import { PresenceIndicator, PresenceRing } from "@flow-industries/ui/components/presence-indicator";

<Avatar className="m-1">
  <AvatarImage src={member.image} alt="" />
  <AvatarFallback />
  <PresenceRing status="idle" away={12} />
</Avatar>

<PresenceIndicator status="online" />
<PresenceIndicator status="invisible" self />

PresenceRing 各状态的表现:

  • online —— 一圈完整的 --success-foreground 色环。
  • idle —— 一圈灰色环,从 12 点方向起顺时针留出缺口。away(闲置分钟数)离开越久缺口越大,并据此命名("Idle for 12 minutes")。
  • busy —— 一圈 --destructive 色环,被一条减号横条截断。
  • invisible —— 虚线环,仅在传入 self 时显示;其他人看到的是 offline。
  • offline —— 不画环;Avatar 会把照片变灰,并降至 55% 不透明度。
  • label —— 覆盖无障碍名称("Busy until 15:00")。

源码:

components/ui/presence-indicator.tsx
import { Circle, CircleMinus, EyeOff, Moon } from "lucide-react";
import type * as React from "react";

import { cn } from "../../utils/cn";

type PresenceStatus = "online" | "idle" | "busy" | "invisible" | "offline";

const presenceAppearance = {
  online: {
    label: "Online",
    icon: Circle,
    className: "fill-success text-foreground",
  },
  idle: {
    label: "Idle",
    icon: Moon,
    className: "fill-dark-orange text-foreground",
  },
  busy: {
    label: "Busy",
    icon: CircleMinus,
    className: "fill-destructive text-background",
  },
  invisible: {
    label: "Invisible",
    icon: EyeOff,
    className: "text-muted-foreground",
  },
  offline: {
    label: "Offline",
    icon: Circle,
    className: "text-muted-foreground",
  },
} satisfies Record<
  PresenceStatus,
  { label: string; icon: typeof Circle; className: string }
>;

/**
 * Availability supplied by the caller, with no fetching or lifecycle state.
 * Missing status renders nothing; Invisible is shown only for an explicit self
 * view. Use aria-hidden when adjacent text already names the status.
 */
function PresenceIndicator({
  status,
  self = false,
  size = "default",
  className,
  ...props
}: Omit<React.ComponentProps<"span">, "children"> & {
  status?: PresenceStatus | null;
  self?: boolean;
  size?: "sm" | "default";
}) {
  if (!status) return null;
  const visibleStatus = status === "invisible" && !self ? "offline" : status;
  const appearance = presenceAppearance[visibleStatus];
  if (!appearance) return null;
  const Icon = appearance.icon;

  return (
    <span
      data-slot="presence-indicator"
      data-status={visibleStatus}
      role="img"
      aria-label={appearance.label}
      className={cn(
        "inline-flex shrink-0 items-center justify-center rounded-full bg-background [corner-shape:round]",
        size === "sm" ? "size-3.5" : "size-4",
        className,
      )}
      {...props}
    >
      <Icon
        aria-hidden="true"
        className={cn("size-full", appearance.className)}
      />
    </span>
  );
}

const ringClassName = {
  online: "border-success-foreground",
  idle: "border-muted-foreground",
  busy: "border-destructive",
  invisible: "border-dashed border-muted-foreground",
  offline: "border-transparent",
} satisfies Record<PresenceStatus, string>;

function awayLabel(minutes: number) {
  if (minutes < 60) {
    const m = Math.max(1, Math.round(minutes));
    return `Idle for ${m} ${m === 1 ? "minute" : "minutes"}`;
  }
  const h = Math.floor(minutes / 60);
  return `Idle for ${h} ${h === 1 ? "hour" : "hours"}`;
}

/** Degrees the idle ring stays open, clockwise from 12 o'clock: wider the longer someone is away. */
function awayGap(minutes: number | undefined) {
  if (minutes === undefined) return 90;
  return Math.min(306, Math.max(30, 30 + minutes * 4.6));
}

/**
 * Availability as a ring around an avatar: 2px wide, 2px out, concentric with
 * the avatar's corners. Place it inside `Avatar`. Online is a full ring, idle a
 * grey ring left open clockwise by time away, busy a ring cut by a minus bar,
 * invisible (only in your own view) dashed; offline draws no ring and greys the
 * photo. Every state is named for assistive technology. Missing status renders
 * nothing.
 *
 * @param away  Minutes idle: opens the idle ring further and names it ("Idle for 12 minutes").
 * @param label Overrides the accessible name, e.g. "Busy until 15:00".
 */
function PresenceRing({
  status,
  self = false,
  away,
  label,
  className,
  style,
  ...props
}: Omit<React.ComponentProps<"span">, "children"> & {
  status?: PresenceStatus | null;
  self?: boolean;
  away?: number;
  label?: string;
}) {
  if (!status) return null;
  const visibleStatus = status === "invisible" && !self ? "offline" : status;
  const name =
    label ??
    (visibleStatus === "idle" && away !== undefined
      ? awayLabel(away)
      : presenceAppearance[visibleStatus].label);
  const gap = visibleStatus === "idle" ? awayGap(away) : null;

  return (
    <span
      data-slot="presence-ring"
      data-status={visibleStatus}
      role="img"
      aria-label={name}
      className={cn(
        // The ring is 8px wider than the avatar, so this keeps its radius at the
        // avatar's plus 4px: 50% stays 50%, the 35% fallback becomes 38.75%.
        "pointer-events-none absolute -inset-1 z-10 rounded-[calc(50%-(50%-var(--squircle-radius))*0.75)] border-2",
        ringClassName[visibleStatus],
        className,
      )}
      style={
        gap === null
          ? style
          : {
              maskImage: `conic-gradient(transparent 0deg ${gap}deg, #000 ${gap}deg)`,
              ...style,
            }
      }
      {...props}
    >
      {visibleStatus === "busy" ? (
        <span className="absolute -bottom-[3.5px] left-1/2 h-[5px] w-3 -translate-x-1/2 rounded-full bg-destructive shadow-[0_0_0_1.5px_var(--background)]" />
      ) : null}
    </span>
  );
}

export { PresenceIndicator, PresenceRing, type PresenceStatus };

ProfilePill

已登录用户的身份标识——用户名,随后是带在线状态环的头像——用于任何需要显示当前登录者的位置:FloatingHeader 的 end 插槽、Flow ID 自身的 pill、游戏菜单。它仅负责渲染:不保存任何会话状态,也不发起任何请求,因此调用方传入其已持有的身份信息即可。默认渲染为 button,这也使其可直接用作菜单触发器;传入 render={<span />} 可获得非交互式展示,悬停、聚焦和触控下限的处理仅在它是按钮或链接时才应用。它没有任何装饰:聚焦前没有填充或轮廓,聚焦时在环外 2px 处显示边框。尺寸:sm(默认值,也是页眉尺寸,头像 24px)、md(32px;0.28.0 之前名为 default)、lg(40px)。用户名超过 12rem 会截断;在窄到放不下几个字符的 FloatingHeader end 插槽中,用户名在视觉上隐藏(仍为辅助技术保留名称),只留下头像及其圆环。缺失或加载失败的 image 会回退到匿名剪影。传入 status 可在头像外画一个 PresenceRing;在用户自己的 pill 上传入 self,使 invisible 显示为虚线而不是离线;用 away 传入闲置分钟数;用 statusLabel 覆盖环的无障碍名称。头像始终保留环的 4px 空间,因此在线状态加载时 pill 不会移动。

在 GitHub 上查看源码 →

用法:

import { ProfilePill } from "@flow-industries/ui/components/profile-pill";
import { DropdownMenuTrigger } from "@flow-industries/ui/components/dropdown-menu";

<ProfilePill username={user.username} image={user.image} status="online" self />

<ProfilePill username={member.username} image={member.image} status="idle" away={12} render={<span />} />

<DropdownMenuTrigger
  render={<ProfilePill username={user.username} image={user.image} status="busy" statusLabel="Busy until 15:00" self />}
/>

源码:

components/ui/profile-pill.tsx
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cva, type VariantProps } from "class-variance-authority";

import { cn } from "../../utils/cn";
import { Avatar, AvatarFallback, AvatarImage } from "./avatar";
import { PresenceRing, type PresenceStatus } from "./presence-indicator";

const profilePillVariants = cva(
  // Bare: no fill or outline until focus, when a border shows 2px outside the
  // presence ring. `flow-profile-pill` lets the top row pull that 4px past its
  // inset, so the ring's outer edge, not the focus border, sits on the inset.
  // normal-case/tracking-tight are load-bearing: app headers commonly set
  // `uppercase tracking-widest` on the nav around it and both inherit, so the
  // pill restates the base layer's own defaults rather than accepting them.
  "flow-profile-pill group/profile-pill inline-flex w-fit max-w-full items-center rounded-full border-[length:var(--border-width)] border-transparent py-0.5 pr-0.5 pl-2 text-foreground normal-case tracking-tight outline-none transition-[color,border-color] duration-150 ease-(--ease-out) focus-visible:border-focus [&:is(a,button)]:pointer-coarse:min-h-11 [&:is(a,button):hover]:text-muted-foreground",
  {
    variants: {
      size: {
        sm: "gap-1.5 font-medium text-sm",
        md: "gap-1.5 font-medium text-base",
        lg: "gap-2 font-semibold text-lg",
      },
    },
    defaultVariants: {
      size: "sm",
    },
  },
);

const avatarSize = { sm: "sm", md: "default", lg: "lg" } as const;

/**
 * The signed-in user's identity — username, then their avatar with its presence
 * ring — used wherever an app shows who is signed in: the top row's end slot,
 * Flow ID's own pill, the game menu. Small (a 24px avatar) by default, which is
 * the header size. Rendering only: it holds no session state and fetches
 * nothing, so callers pass whatever identity they already have.
 *
 * Renders a `button` by default, which is also what makes it a drop-in trigger:
 *
 * ```tsx
 * <DropdownMenuTrigger render={<ProfilePill username={user.username} />} />
 * ```
 *
 * Pass `render={<span />}` for a non-interactive display; the hover, focus and
 * touch-floor treatment only apply while it is a button or a link. The avatar
 * always keeps the ring's 4px of room, so the pill doesn't move when presence
 * loads. The name truncates when space runs short; in a `FloatingHeader` end
 * slot too narrow for a few characters it is hidden visually (still named for
 * assistive technology), leaving the avatar and its ring.
 *
 * @param username    Shown as-is, truncated past 12rem — callers guard the
 *                    signed-out case rather than passing an empty string.
 * @param image       Avatar URL; falls back to the anonymous silhouette when it
 *                    is absent or fails to load.
 * @param status      Presence, drawn as a ring; none leaves the avatar unmarked.
 * @param self        The viewer's own pill: Invisible shows dashed rather than
 *                    as Offline.
 * @param away        Minutes idle: opens the idle ring and names it.
 * @param statusLabel Overrides the ring's accessible name ("Busy until 15:00").
 */
function ProfilePill({
  username,
  image,
  status,
  self,
  away,
  statusLabel,
  size = "sm",
  className,
  render,
  ...props
}: useRender.ComponentProps<"button"> &
  VariantProps<typeof profilePillVariants> & {
    username: string;
    image?: string | null;
    status?: PresenceStatus | null;
    self?: boolean;
    away?: number;
    statusLabel?: string;
  }) {
  return useRender({
    defaultTagName: "button",
    props: mergeProps<"button">(
      {
        // Only when we own the element: `type` on a caller-supplied `render`
        // element would be an invalid attribute (and the base layer turns any
        // [type=button] into a pointer cursor, even on a span).
        type: render ? undefined : ("button" as const),
        className: cn(profilePillVariants({ size, className })),
      },
      props,
      {
        children: (
          <>
            <span
              data-slot="profile-pill-name"
              className="max-w-[12rem] min-w-0 truncate"
            >
              {username}
            </span>
            <Avatar size={avatarSize[size ?? "sm"]} className="m-1">
              {image ? <AvatarImage src={image} alt="" /> : null}
              <AvatarFallback />
              <PresenceRing
                status={status}
                self={self}
                away={away}
                label={statusLabel}
              />
            </Avatar>
          </>
        ),
      },
    ),
    render,
    state: {
      slot: "profile-pill",
      size,
    },
  });
}

export { ProfilePill, profilePillVariants };

Item

通用的列表项原语,用于列表、命令面板和富选择行。导出:Item、ItemMedia、ItemContent、ItemActions、ItemGroup、ItemSeparator、ItemTitle、ItemDescription、ItemHeader、ItemFooter。

在 GitHub 上查看源码 →

用法:

import {
  Item, ItemMedia, ItemContent, ItemTitle, ItemDescription, ItemActions,
} from "@flow-industries/ui/components/item";

<Item>
  <ItemMedia variant="icon"><FolderIcon /></ItemMedia>
  <ItemContent>
    <ItemTitle>flow/docs</ItemTitle>
    <ItemDescription>React Router + Fumadocs 站点</ItemDescription>
  </ItemContent>
  <ItemActions>
    <Button size="sm">打开</Button>
  </ItemActions>
</Item>

Variant:default、outline、muted。尺寸:default、sm、xs。

源码:

components/ui/item.tsx
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";

import { cn } from "../../utils/cn";
import { Separator } from "./separator";

const ItemGroupContext = React.createContext(false);

function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <ItemGroupContext.Provider value={true}>
      {/* biome-ignore lint/a11y/useSemanticElements: role="list" on a styled div avoids ul default list styles */}
      <div
        role="list"
        data-slot="item-group"
        className={cn(
          "group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2",
          className,
        )}
        {...props}
      />
    </ItemGroupContext.Provider>
  );
}

function ItemSeparator({
  className,
  ...props
}: React.ComponentProps<typeof Separator>) {
  return (
    <Separator
      data-slot="item-separator"
      aria-hidden="true"
      orientation="horizontal"
      className={cn("my-2", className)}
      {...props}
    />
  );
}

const itemVariants = cva(
  "group/item flex w-full flex-wrap items-center rounded-lg border-[length:var(--border-width)] text-sm transition-colors duration-100 outline-none focus-visible:border-[length:var(--border-width-focus)] focus-visible:border-focus [a]:transition-colors [a]:hover:bg-muted",
  {
    variants: {
      variant: {
        default: "border-transparent",
        outline: "border-secondary",
        muted: "border-transparent bg-muted/50",
      },
      size: {
        default: "gap-2.5 px-3 py-2.5",
        sm: "gap-2.5 px-3 py-2.5",
        xs: "gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  },
);

function Item({
  className,
  variant = "default",
  size = "default",
  render,
  ...props
}: useRender.ComponentProps<"div"> & VariantProps<typeof itemVariants>) {
  const inGroup = React.useContext(ItemGroupContext);
  return useRender({
    defaultTagName: "div",
    props: mergeProps<"div">(
      {
        className: cn(itemVariants({ variant, size, className })),
        role: inGroup ? "listitem" : undefined,
      },
      props,
    ),
    render,
    state: {
      slot: "item",
      variant,
      size,
    },
  });
}

const itemMediaVariants = cva(
  "flex shrink-0 items-center justify-center gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start [&_svg]:pointer-events-none",
  {
    variants: {
      variant: {
        default: "bg-transparent",
        icon: "[&_svg:not([class*='size-'])]:size-4",
        image:
          "size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  },
);

function ItemMedia({
  className,
  variant = "default",
  ...props
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
  return (
    <div
      data-slot="item-media"
      data-variant={variant}
      className={cn(itemMediaVariants({ variant, className }))}
      {...props}
    />
  );
}

function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="item-content"
      className={cn(
        "flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none",
        className,
      )}
      {...props}
    />
  );
}

function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="item-title"
      className={cn(
        "line-clamp-1 flex w-fit items-center gap-2 text-sm font-medium underline-offset-4",
        className,
      )}
      {...props}
    />
  );
}

function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
  return (
    <p
      data-slot="item-description"
      className={cn(
        "line-clamp-2 text-left text-sm leading-normal font-normal text-muted-foreground group-data-[size=xs]/item:text-xs [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
        className,
      )}
      {...props}
    />
  );
}

function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="item-actions"
      className={cn("flex items-center gap-2", className)}
      {...props}
    />
  );
}

function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="item-header"
      className={cn(
        "flex basis-full items-center justify-between gap-2",
        className,
      )}
      {...props}
    />
  );
}

function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="item-footer"
      className={cn(
        "flex basis-full items-center justify-between gap-2",
        className,
      )}
      {...props}
    />
  );
}

export {
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemFooter,
  ItemGroup,
  ItemHeader,
  ItemMedia,
  ItemSeparator,
  ItemTitle,
};

On this page