Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/next-ts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@zag-js/tree-view": "workspace:*",
"@zag-js/types": "workspace:*",
"@zag-js/utils": "workspace:*",
"@zag-js/virtualizer": "workspace:*",
"form-serialize": "0.7.2",
"image-conversion": "2.1.1",
"lucide-react": "0.548.0",
Expand Down
205 changes: 205 additions & 0 deletions examples/next-ts/pages/grid-virtualizer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { GridVirtualizer } from "@zag-js/virtualizer"
import { useCallback, useReducer, useRef, useState } from "react"
import { flushSync } from "react-dom"

// Grid configuration
const TOTAL_ROWS = 1000
const TOTAL_COLUMNS = 50
const CELL_WIDTH = 120
const CELL_HEIGHT = 40

// Generate cell data
const generateCellData = (row: number, col: number) => ({
id: `${row}-${col}`,
value: `R${row + 1}C${col + 1}`,
color: `hsl(${((row + col) * 37) % 360}, 60%, 90%)`,
})

export default function Page() {
const isInitializedRef = useRef(false)
const [isSmooth, setIsSmooth] = useState(true)
const [, rerender] = useReducer(() => ({}), {})
const [virtualizer] = useState(() => {
return new GridVirtualizer({
rowCount: TOTAL_ROWS,
columnCount: TOTAL_COLUMNS,
estimatedRowSize: () => CELL_HEIGHT,
estimatedColumnSize: () => CELL_WIDTH,
overscan: { count: 3 },
gap: 0,
paddingStart: 0,
paddingEnd: 0,
observeScrollElementSize: true,
onRangeChange: () => {
if (!isInitializedRef.current) return
flushSync(rerender)
},
})
})

const setScrollElementRef = useCallback((element: HTMLDivElement | null) => {
if (!element) return
virtualizer.init(element)
isInitializedRef.current = true
rerender()
return () => virtualizer.destroy()
}, [])

const virtualCells = virtualizer.getVirtualCells()
const totalWidth = virtualizer.getTotalWidth()
const totalHeight = virtualizer.getTotalHeight()
const range = virtualizer.getRange()

const visibleRows = range.endRow - range.startRow + 1
const visibleCols = range.endColumn - range.startColumn + 1

return (
<main className="grid-virtualizer">
<div style={{ padding: "20px" }}>
<h1>Grid Virtualizer Example</h1>
<p>
Virtualizing a {TOTAL_ROWS.toLocaleString()} × {TOTAL_COLUMNS} grid (
{(TOTAL_ROWS * TOTAL_COLUMNS).toLocaleString()} cells)
</p>
<p style={{ fontSize: "14px", color: "#666" }}>
Scroll both horizontally and vertically - only visible cells are rendered!
</p>

<label style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, userSelect: "none" }}>
<input type="checkbox" checked={isSmooth} onChange={(e) => setIsSmooth(e.currentTarget.checked)} />
Smooth scroll
</label>

<div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 12 }}>
<button
type="button"
disabled={!isInitializedRef.current}
onClick={() => {
virtualizer.scrollToCell(0, 0, { behavior: isSmooth ? "smooth" : "auto" })
}}
>
Scroll to Top-Left
</button>
<button
type="button"
disabled={!isInitializedRef.current}
onClick={() => {
virtualizer.scrollToCell(Math.floor(TOTAL_ROWS / 2), Math.floor(TOTAL_COLUMNS / 2), {
behavior: isSmooth ? "smooth" : "auto",
})
}}
>
Scroll to Center
</button>
<button
type="button"
disabled={!isInitializedRef.current}
onClick={() => {
virtualizer.scrollToCell(TOTAL_ROWS - 1, TOTAL_COLUMNS - 1, { behavior: isSmooth ? "smooth" : "auto" })
}}
>
Scroll to Bottom-Right
</button>
</div>

<div
ref={setScrollElementRef}
onScroll={(e) => {
flushSync(() => {
virtualizer.handleScroll(e)
})
}}
{...virtualizer.getContainerAriaAttrs()}
style={{
height: "500px",
width: "100%",
maxWidth: "900px",
...virtualizer.getContainerStyle(),
border: "1px solid #ccc",
borderRadius: "8px",
marginTop: "16px",
}}
>
{/* Total scrollable area */}
<div
style={{
width: totalWidth,
height: totalHeight,
position: "relative",
}}
>
{/* Render only visible cells */}
{virtualCells.map((cell) => {
const data = generateCellData(cell.row, cell.column)
const style = virtualizer.getCellStyle(cell)

return (
<div
key={data.id}
{...virtualizer.getCellAriaAttrs(cell.row, cell.column)}
style={{
...style,
backgroundColor: data.color,
border: "1px solid rgba(0,0,0,0.1)",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "12px",
fontWeight: cell.row === 0 || cell.column === 0 ? "bold" : "normal",
color: cell.row === 0 || cell.column === 0 ? "#333" : "#666",
boxSizing: "border-box",
}}
>
{data.value}
</div>
)
})}
</div>
</div>

{/* Stats */}
<div
style={{
marginTop: "16px",
padding: "16px",
backgroundColor: "#f5f5f5",
borderRadius: "8px",
fontSize: "14px",
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
gap: "12px",
}}
>
<div>
<strong>Grid Size:</strong> {TOTAL_ROWS.toLocaleString()} rows × {TOTAL_COLUMNS} cols
</div>
<div>
<strong>Total Cells:</strong> {(TOTAL_ROWS * TOTAL_COLUMNS).toLocaleString()}
</div>
<div>
<strong>Rendered Cells:</strong> {virtualCells.length}
</div>
<div>
<strong>Visible Rows:</strong> {range.startRow} - {range.endRow} ({visibleRows} rows)
</div>
<div>
<strong>Visible Cols:</strong> {range.startColumn} - {range.endColumn} ({visibleCols} cols)
</div>
<div>
<strong>Total Size:</strong> {totalWidth}px × {totalHeight}px
</div>
<div style={{ gridColumn: "1 / -1" }}>
{virtualCells.length < 500 ? (
<span style={{ color: "green" }}>
✅ Virtualization working! Only {virtualCells.length} of {(TOTAL_ROWS * TOTAL_COLUMNS).toLocaleString()}{" "}
cells rendered
</span>
) : (
<span style={{ color: "orange" }}>⚠️ Many cells rendered</span>
)}
</div>
</div>
</div>
</main>
)
}
168 changes: 168 additions & 0 deletions examples/next-ts/pages/list-virtualizer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { ListVirtualizer } from "@zag-js/virtualizer"
import { useCallback, useReducer, useRef, useState } from "react"
import { flushSync } from "react-dom"

const generateItems = (count: number) =>
Array.from({ length: count }, (_, i) => ({
id: i,
name: `Item ${i + 1}`,
description: `This is the description for item ${i + 1}`,
}))

const items = generateItems(10000)

export default function Page() {
const isInitializedRef = useRef(false)
const [isSmooth, setIsSmooth] = useState(true)
const [virtualizer] = useState<ListVirtualizer | null>(() => {
return new ListVirtualizer({
count: items.length,
estimatedSize: () => 142,
overscan: { count: 5 },
gap: 0,
paddingStart: 0,
paddingEnd: 0,
onRangeChange: () => {
if (!isInitializedRef.current) return
flushSync(rerender)
},
})
})
const [, rerender] = useReducer(() => ({}), {})

// Callback ref to measure when element mounts
const setScrollElementRef = useCallback((element: HTMLDivElement | null) => {
if (!element) return
if (virtualizer) {
virtualizer.init(element)
isInitializedRef.current = true
rerender()
return () => virtualizer.destroy()
}
}, [])

const virtualItems = virtualizer.getVirtualItems()
const totalSize = virtualizer.getTotalSize()

return (
<main className="list-virtualizer">
<div style={{ padding: "20px" }}>
<h1>List Virtualizer Example</h1>
<p>Scrolling through {items.length.toLocaleString()} items efficiently</p>

<label style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, userSelect: "none" }}>
<input type="checkbox" checked={isSmooth} onChange={(e) => setIsSmooth(e.currentTarget.checked)} />
Smooth scroll
</label>

<div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 12 }}>
<button
type="button"
onClick={() => virtualizer?.scrollToIndex(0, { smooth: isSmooth })}
disabled={!isInitializedRef.current}
>
Scroll to Top
</button>
<button
type="button"
onClick={() =>
virtualizer?.scrollToIndex(Math.floor(items.length / 2), { align: "center", smooth: isSmooth })
}
disabled={!isInitializedRef.current}
>
Scroll to Middle
</button>
<button
type="button"
onClick={() => virtualizer?.scrollToIndex(items.length - 1, { smooth: isSmooth })}
disabled={!isInitializedRef.current}
>
Scroll to Bottom
</button>
</div>

<div
ref={setScrollElementRef}
onScroll={(e) => {
flushSync(() => {
virtualizer.handleScroll(e)
})
}}
{...virtualizer.getContainerAriaAttrs()}
style={{
...virtualizer.getContainerStyle(),
height: "400px",
border: "1px solid #ccc",
marginTop: "16px",
}}
>
<div
style={{
height: `${totalSize}px`,
width: "100%",
position: "relative",
}}
>
{virtualItems.map((virtualItem) => {
const item = items[virtualItem.index]
const style = virtualizer.getItemStyle(virtualItem)

return (
<div
key={virtualItem.index}
data-index={virtualItem.index}
{...virtualizer.getItemAriaAttrs(virtualItem.index)}
style={{
...style,
padding: "16px",
backgroundColor: virtualItem.index % 2 === 0 ? "#f8f9fa" : "#ffffff",
borderBottom: "1px solid #e1e5e9",
display: "flex",
flexDirection: "column",
gap: "8px",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
fontWeight: "600",
fontSize: "16px",
color: "#1a1a1a",
}}
>
{item.name}
</div>
<p>{item.description}</p>
<div
style={{
fontSize: "12px",
color: "#9ca3af",
fontFamily: "monospace",
}}
>
Virtual Index: {virtualItem.index} | Start: {virtualItem.start}px | Size: {virtualItem.size}px
</div>
</div>
)
})}
</div>
</div>

<div style={{ marginTop: "16px", fontSize: "14px", color: "#6b7280" }}>
<div>Total items: {items.length.toLocaleString()}</div>
<div>Rendered items: {virtualItems.length}</div>
<div>Total height: {totalSize}px</div>
<div>
Visible range: {virtualItems[0]?.index ?? 0} - {virtualItems[virtualItems.length - 1]?.index ?? 0}
</div>
{virtualItems.length > 100 && (
<div style={{ color: "orange" }}>⚠️ Many items rendered (fast scroll mode)</div>
)}
{virtualItems.length <= 100 && <div style={{ color: "green" }}>✅ Virtualization working!</div>}
</div>
</div>
</main>
)
}
Loading
Loading