({ messages }: { messages: ChatMessage[] })
| 7 | import { useDynamicRowHeight, useVirtualizer } from "react-window"; |
| 8 | |
| 9 | function Example({ messages }: { messages: ChatMessage[] }) { |
| 10 | const [element, setElement] = useState<HTMLDivElement | null>(null); |
| 11 | const itemSize = useDynamicRowHeight({ defaultRowHeight: 50 }); |
| 12 | |
| 13 | const { items, measureElement, totalSize } = useVirtualizer({ |
| 14 | count: messages.length, |
| 15 | element, |
| 16 | itemSize |
| 17 | }); |
| 18 | |
| 19 | return ( |
| 20 | <div className="h-full overflow-auto" ref={setElement}> |
| 21 | <div className="relative" style={{ height: totalSize }}> |
| 22 | {items.map(({ index, offset }) => { |
| 23 | const { sender, text } = messages[index]; |
| 24 | const isOutgoing = sender === "You"; |
| 25 | |
| 26 | return ( |
| 27 | <div |
| 28 | className={cn("absolute w-full flex flex-col px-2 py-1", { |
| 29 | "items-end": isOutgoing, |
| 30 | "items-start": !isOutgoing |
| 31 | })} |
| 32 | // Rows are measured after rendering, so they need their index |
| 33 | data-index={index} |
| 34 | key={index} |
| 35 | ref={measureElement} |
| 36 | style={{ transform: `translateY(${offset}px)` }} |
| 37 | > |
| 38 | <div className="text-xs opacity-50 px-1 pb-0.5">{sender}</div> |
| 39 | <div |
| 40 | className={cn("max-w-3/4 px-3 py-2 rounded-2xl", { |
| 41 | "bg-sky-700 text-white rounded-br-sm": isOutgoing, |
| 42 | "bg-ink/10 rounded-bl-sm": !isOutgoing |
| 43 | })} |
| 44 | > |
| 45 | {text} |
| 46 | </div> |
| 47 | </div> |
| 48 | ); |
| 49 | })} |
| 50 | </div> |
| 51 | </div> |
| 52 | ); |
| 53 | } |
| 54 | |
| 55 | // <end> |
| 56 |
nothing calls this directly
no test coverage detected