metis-desk/packages/rdx-ui/src/components/collection-preview.tsx
2026-10-25 01:19:17 +02:00

53 lines
1.5 KiB
TypeScript

import { Button } from "@repo/shadcn-ui/components/button";
import type { ReactNode } from "react";
import { useId, useState } from "react";
/** Resumen local con ampliación explícita: ningún elemento queda inaccesible. */
export function CollectionPreview<T>({
items,
limit,
expandLabel,
collapseLabel,
children,
expanded: controlledExpanded,
onExpandedChange,
}: {
items: readonly T[];
limit: number;
expandLabel: string;
collapseLabel: string;
children: (items: readonly T[]) => ReactNode;
expanded?: boolean;
onExpandedChange?: (expanded: boolean) => void;
}) {
const [localExpanded, setLocalExpanded] = useState(false);
const expanded = controlledExpanded ?? localExpanded;
const id = useId();
const previewLimit = Number.isSafeInteger(limit) && limit > 0 ? limit : items.length;
const limited = items.length > previewLimit;
return (
<div className="flex min-w-0 flex-col gap-2" data-slot="collection-preview">
<div id={id}>{children(limited && !expanded ? items.slice(0, previewLimit) : items)}</div>
{limited && (
<Button
aria-controls={id}
aria-expanded={expanded}
className="w-fit"
onClick={() => {
if (controlledExpanded === undefined) {
setLocalExpanded(!expanded);
}
onExpandedChange?.(!expanded);
}}
size="sm"
type="button"
variant="ghost"
>
{expanded ? collapseLabel : expandLabel}
</Button>
)}
</div>
);
}