File size: 10,360 Bytes
52efc7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { render } from '../../../test-utils/render.js';
import { waitFor } from '../../../test-utils/async.js';
import { VirtualizedList, type VirtualizedListRef } from './VirtualizedList.js';
import { Text, Box } from 'ink';
import {
createRef,
act,
useEffect,
createContext,
useContext,
useState,
} from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
describe('<VirtualizedList />', () => {
const keyExtractor = (item: string) => item;
beforeEach(() => {
vi.clearAllMocks();
});
describe('with 10px height and 100 items', () => {
const longData = Array.from({ length: 100 }, (_, i) => `Item ${i}`);
// We use 1px for items. Container is 10px.
// Viewport shows 10 items. Overscan adds 10 items.
const itemHeight = 1;
const renderItem1px = ({ item }: { item: string }) => (
<Box height={itemHeight}>
<Text>{item}</Text>
</Box>
);
it.each([
{
name: 'top',
initialScrollIndex: undefined,
visible: ['Item 0', 'Item 7'],
notVisible: ['Item 8', 'Item 15', 'Item 50', 'Item 99'],
},
{
name: 'scrolled to bottom',
initialScrollIndex: 99,
visible: ['Item 99', 'Item 92'],
notVisible: ['Item 91', 'Item 85', 'Item 50', 'Item 0'],
},
])(
'renders only visible items ($name)',
async ({ initialScrollIndex, visible, notVisible }) => {
const { lastFrame, unmount } = await render(
<Box height={10} width={100} borderStyle="round">
<VirtualizedList
data={longData}
renderItem={renderItem1px}
keyExtractor={keyExtractor}
estimatedItemHeight={() => itemHeight}
initialScrollIndex={initialScrollIndex}
/>
</Box>,
);
const output = lastFrame();
visible.forEach((item) => {
expect(output).toContain(item);
});
notVisible.forEach((item) => {
expect(output).not.toContain(item);
});
expect(output).toMatchSnapshot();
unmount();
},
);
it('sticks to bottom when new items added', async () => {
const { lastFrame, rerender, waitUntilReady, unmount } = await render(
<Box height={10} width={100} borderStyle="round">
<VirtualizedList
data={longData}
renderItem={renderItem1px}
keyExtractor={keyExtractor}
estimatedItemHeight={() => itemHeight}
initialScrollIndex={99}
/>
</Box>,
);
expect(lastFrame()).toContain('Item 99');
// Add items
const newData = [...longData, 'Item 100', 'Item 101'];
await act(async () => {
rerender(
<Box height={10} width={100} borderStyle="round">
<VirtualizedList
data={newData}
renderItem={renderItem1px}
keyExtractor={keyExtractor}
estimatedItemHeight={() => itemHeight}
// We don't need to pass initialScrollIndex again for it to stick,
// but passing it doesn't hurt. The component should auto-stick because it was at bottom.
/>
</Box>,
);
});
await waitUntilReady();
const frame = lastFrame();
expect(frame).toContain('Item 101');
expect(frame).not.toContain('Item 0');
unmount();
});
it('scrolls down to show new items when requested via ref', async () => {
const ref = createRef<VirtualizedListRef<string>>();
const { lastFrame, waitUntilReady, unmount } = await render(
<Box height={10} width={100} borderStyle="round">
<VirtualizedList
ref={ref}
data={longData}
renderItem={renderItem1px}
keyExtractor={keyExtractor}
estimatedItemHeight={() => itemHeight}
/>
</Box>,
);
expect(lastFrame()).toContain('Item 0');
// Scroll to bottom via ref
await act(async () => {
ref.current?.scrollToEnd();
});
await waitUntilReady();
const frame = lastFrame();
expect(frame).toContain('Item 99');
unmount();
});
it.each([
{ initialScrollIndex: 0, expectedMountedCount: 5 },
{ initialScrollIndex: 500, expectedMountedCount: 6 },
{ initialScrollIndex: 999, expectedMountedCount: 5 },
])(
'mounts only visible items with 1000 items and 10px height (scroll: $initialScrollIndex)',
async ({ initialScrollIndex, expectedMountedCount }) => {
let mountedCount = 0;
const tallItemHeight = 5;
const ItemWithEffect = ({ item }: { item: string }) => {
useEffect(() => {
mountedCount++;
return () => {
mountedCount--;
};
}, []);
return (
<Box height={tallItemHeight}>
<Text>{item}</Text>
</Box>
);
};
const veryLongData = Array.from(
{ length: 1000 },
(_, i) => `Item ${i}`,
);
const { lastFrame, unmount } = await render(
<Box height={20} width={100} borderStyle="round">
<VirtualizedList
data={veryLongData}
renderItem={({ item }) => (
<ItemWithEffect key={item} item={item} />
)}
keyExtractor={keyExtractor}
estimatedItemHeight={() => tallItemHeight}
initialScrollIndex={initialScrollIndex}
/>
</Box>,
);
const frame = lastFrame();
expect(mountedCount).toBe(expectedMountedCount);
expect(frame).toMatchSnapshot();
unmount();
},
);
});
it('renders more items when a visible item shrinks via context update', async () => {
const SizeContext = createContext<{
firstItemHeight: number;
setFirstItemHeight: (h: number) => void;
}>({
firstItemHeight: 10,
setFirstItemHeight: () => {},
});
const items = Array.from({ length: 20 }, (_, i) => ({
id: `Item ${i}`,
}));
const ItemWithContext = ({
item,
index,
}: {
item: { id: string };
index: number;
}) => {
const { firstItemHeight } = useContext(SizeContext);
const height = index === 0 ? firstItemHeight : 1;
return (
<Box height={height}>
<Text>{item.id}</Text>
</Box>
);
};
const TestComponent = () => {
const [firstItemHeight, setFirstItemHeight] = useState(10);
return (
<SizeContext.Provider value={{ firstItemHeight, setFirstItemHeight }}>
<Box height={10} width={100}>
<VirtualizedList
data={items}
renderItem={({ item, index }) => (
<ItemWithContext item={item} index={index} />
)}
keyExtractor={(item) => item.id}
estimatedItemHeight={() => 1}
/>
</Box>
{/* Expose setter for testing */}
<TestControl setFirstItemHeight={setFirstItemHeight} />
</SizeContext.Provider>
);
};
let setHeightFn: (h: number) => void = () => {};
const TestControl = ({
setFirstItemHeight,
}: {
setFirstItemHeight: (h: number) => void;
}) => {
setHeightFn = setFirstItemHeight;
return null;
};
const { lastFrame, unmount, waitUntilReady } = await render(
<TestComponent />,
);
// Initially, only Item 0 (height 10) fills the 10px viewport
expect(lastFrame()).toContain('Item 0');
expect(lastFrame()).not.toContain('Item 1');
// Shrink Item 0 to 1px via context
await act(async () => {
setHeightFn(1);
});
await waitUntilReady();
// Now Item 0 is 1px, so Items 1-9 should also be visible to fill 10px
await waitFor(() => {
expect(lastFrame()).toContain('Item 0');
expect(lastFrame()).toContain('Item 1');
expect(lastFrame()).toContain('Item 9');
});
unmount();
});
it('updates scroll position correctly when scrollBy is called multiple times in the same tick', async () => {
const ref = createRef<VirtualizedListRef<string>>();
const longData = Array.from({ length: 100 }, (_, i) => `Item ${i}`);
const itemHeight = 1;
const renderItem1px = ({ item }: { item: string }) => (
<Box height={itemHeight}>
<Text>{item}</Text>
</Box>
);
const keyExtractor = (item: string) => item;
const { unmount, waitUntilReady } = await render(
<Box height={10} width={100} borderStyle="round">
<VirtualizedList
ref={ref}
data={longData}
renderItem={renderItem1px}
keyExtractor={keyExtractor}
estimatedItemHeight={() => itemHeight}
/>
</Box>,
);
expect(ref.current?.getScrollState().scrollTop).toBe(0);
await act(async () => {
ref.current?.scrollBy(1);
ref.current?.scrollBy(1);
});
await waitUntilReady();
expect(ref.current?.getScrollState().scrollTop).toBe(2);
await act(async () => {
ref.current?.scrollBy(2);
});
await waitUntilReady();
expect(ref.current?.getScrollState().scrollTop).toBe(4);
unmount();
});
it('renders correctly in copyModeEnabled when scrolled', async () => {
const longData = Array.from({ length: 100 }, (_, i) => `Item ${i}`);
// Use copy mode
const { lastFrame, unmount } = await render(
<Box height={10} width={100}>
<VirtualizedList
data={longData}
renderItem={({ item }) => (
<Box height={1}>
<Text>{item}</Text>
</Box>
)}
keyExtractor={(item) => item}
estimatedItemHeight={() => 1}
initialScrollIndex={50}
copyModeEnabled={true}
/>
</Box>,
);
// Item 50 should be visible
expect(lastFrame()).toContain('Item 50');
// And surrounding items
expect(lastFrame()).toContain('Item 59');
// But far away items should not be (ensures we are actually scrolled)
expect(lastFrame()).not.toContain('Item 0');
unmount();
});
});
|