ink-virtual-list 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 archcorsair
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 archcorsair
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,213 +1,213 @@
1
- # ink-virtual-list
2
-
3
- A virtualized list component for [Ink](https://github.com/vadimdemedes/ink) terminal applications. Only renders visible items for optimal performance with large datasets.
4
-
5
- ## Features
6
-
7
- - **Virtualized rendering** - Only renders items visible in the viewport
8
- - **Automatic scrolling** - Keeps selected item in view as you navigate
9
- - **Terminal-aware** - Responds to terminal resize events
10
- - **Flexible height** - Fixed height or auto-fill available terminal space
11
- - **Customizable indicators** - Override default overflow indicators ("▲ N more")
12
- - **TypeScript first** - Full type safety with generics
13
- - **Imperative API** - Programmatic scrolling via ref
14
-
15
- ## Installation
16
-
17
- ```bash
18
- # npm
19
- npm install ink-virtual-list
20
-
21
- # jsr
22
- npx jsr add @archcorsair/ink-virtual-list
23
-
24
- # bun
25
- bun add ink-virtual-list
26
- ```
27
-
28
- ## Usage
29
-
30
- ### Basic Example
31
-
32
- ```tsx
33
- import { VirtualList } from 'ink-virtual-list';
34
- import { Text } from 'ink';
35
- import { useState } from 'react';
36
-
37
- function App() {
38
- const [selectedIndex, setSelectedIndex] = useState(0);
39
- const items = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
40
-
41
- return (
42
- <VirtualList
43
- items={items}
44
- selectedIndex={selectedIndex}
45
- height={10}
46
- renderItem={({ item, isSelected }) => (
47
- <Text color={isSelected ? 'cyan' : 'white'}>
48
- {isSelected ? '> ' : ' '}
49
- {item}
50
- </Text>
51
- )}
52
- />
53
- );
54
- }
55
- ```
56
-
57
- ### Auto-fill Terminal Height
58
-
59
- ```tsx
60
- <VirtualList
61
- items={items}
62
- height="auto"
63
- reservedLines={5} // Reserve space for header/footer
64
- renderItem={({ item }) => <Text>{item}</Text>}
65
- />
66
- ```
67
-
68
- ### Custom Overflow Indicators
69
-
70
- ```tsx
71
- <VirtualList
72
- items={items}
73
- renderOverflowTop={(count) => <Text dimColor>↑ {count} hidden</Text>}
74
- renderOverflowBottom={(count) => <Text dimColor>↓ {count} hidden</Text>}
75
- renderItem={({ item }) => <Text>{item}</Text>}
76
- />
77
- ```
78
-
79
- ### Imperative Scrolling
80
-
81
- ```tsx
82
- import { useRef } from 'react';
83
- import type { VirtualListRef } from 'ink-virtual-list';
84
-
85
- function App() {
86
- const listRef = useRef<VirtualListRef>(null);
87
-
88
- const scrollToTop = () => {
89
- listRef.current?.scrollToIndex(0, 'top');
90
- };
91
-
92
- return (
93
- <VirtualList
94
- ref={listRef}
95
- items={items}
96
- renderItem={({ item }) => <Text>{item}</Text>}
97
- />
98
- );
99
- }
100
- ```
101
-
102
- ## API
103
-
104
- ### Props
105
-
106
- #### Required
107
-
108
- - **`items: T[]`** - Array of items to render
109
- - **`renderItem: (props: RenderItemProps<T>) => ReactNode`** - Render function for each visible item
110
- - Receives: `{ item: T, index: number, isSelected: boolean }`
111
-
112
- #### Optional
113
-
114
- - **`selectedIndex?: number`** - Index of currently selected item (default: `0`)
115
- - **`keyExtractor?: (item: T, index: number) => string`** - Custom key extractor for list items
116
- - **`height?: number | "auto"`** - Fixed height in lines or `"auto"` to fill terminal (default: `10`)
117
- - **`reservedLines?: number`** - Lines to reserve when using `height="auto"` (default: `0`)
118
- - **`itemHeight?: number`** - Height of each item in lines (default: `1`)
119
- - **`showOverflowIndicators?: boolean`** - Show "N more" indicators (default: `true`)
120
- - **`renderOverflowTop?: (count: number) => ReactNode`** - Custom top overflow indicator
121
- - **`renderOverflowBottom?: (count: number) => ReactNode`** - Custom bottom overflow indicator
122
- - **`renderScrollBar?: (viewport: ViewportState) => ReactNode`** - Custom scrollbar renderer
123
- - **`onViewportChange?: (viewport: ViewportState) => void`** - Callback when viewport changes
124
-
125
- ### Ref Methods
126
-
127
- ```typescript
128
- interface VirtualListRef {
129
- scrollToIndex: (index: number, alignment?: 'auto' | 'top' | 'center' | 'bottom') => void;
130
- getViewport: () => ViewportState;
131
- remeasure: () => void;
132
- }
133
- ```
134
-
135
- - **`scrollToIndex(index, alignment?)`** - Scroll to bring an index into view
136
- - `'auto'` (default) - Only scroll if needed
137
- - `'top'` - Align item to top of viewport
138
- - `'center'` - Center item in viewport
139
- - `'bottom'` - Align item to bottom of viewport
140
- - **`getViewport()`** - Get current viewport state (`{ offset, visibleCount, totalCount }`)
141
- - **`remeasure()`** - Force recalculation of viewport dimensions
142
-
143
- ### Types
144
-
145
- ```typescript
146
- interface RenderItemProps<T> {
147
- item: T;
148
- index: number;
149
- isSelected: boolean;
150
- }
151
-
152
- interface ViewportState {
153
- offset: number; // Items scrolled past
154
- visibleCount: number; // Items currently visible
155
- totalCount: number; // Total items
156
- }
157
- ```
158
-
159
- ## Advanced Example
160
-
161
- ```tsx
162
- import { VirtualList } from 'ink-virtual-list';
163
- import { Box, Text } from 'ink';
164
- import { useRef, useState } from 'react';
165
- import type { VirtualListRef } from 'ink-virtual-list';
166
-
167
- interface Todo {
168
- id: string;
169
- title: string;
170
- completed: boolean;
171
- }
172
-
173
- function TodoApp() {
174
- const [todos] = useState<Todo[]>([
175
- { id: '1', title: 'Learn Ink', completed: true },
176
- { id: '2', title: 'Build CLI', completed: false },
177
- // ... 1000s more
178
- ]);
179
- const [selectedIndex, setSelectedIndex] = useState(0);
180
- const listRef = useRef<VirtualListRef>(null);
181
-
182
- return (
183
- <Box flexDirection="column">
184
- <Text bold>My Todos ({todos.length})</Text>
185
-
186
- <VirtualList
187
- ref={listRef}
188
- items={todos}
189
- selectedIndex={selectedIndex}
190
- height="auto"
191
- reservedLines={3}
192
- keyExtractor={(todo) => todo.id}
193
- renderItem={({ item, isSelected }) => (
194
- <Box>
195
- <Text color={isSelected ? 'cyan' : 'white'}>
196
- {isSelected ? '❯ ' : ' '}
197
- {item.completed ? '✓' : '○'} {item.title}
198
- </Text>
199
- </Box>
200
- )}
201
- />
202
-
203
- <Text dimColor>
204
- {selectedIndex + 1} / {todos.length}
205
- </Text>
206
- </Box>
207
- );
208
- }
209
- ```
210
-
211
- ## License
212
-
213
- MIT
1
+ # ink-virtual-list
2
+
3
+ A virtualized list component for [Ink](https://github.com/vadimdemedes/ink) terminal applications. Only renders visible items for optimal performance with large datasets.
4
+
5
+ ## Features
6
+
7
+ - **Virtualized rendering** - Only renders items visible in the viewport
8
+ - **Automatic scrolling** - Keeps selected item in view as you navigate
9
+ - **Terminal-aware** - Responds to terminal resize events
10
+ - **Flexible height** - Fixed height or auto-fill available terminal space
11
+ - **Customizable indicators** - Override default overflow indicators ("▲ N more")
12
+ - **TypeScript first** - Full type safety with generics
13
+ - **Imperative API** - Programmatic scrolling via ref
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ # npm
19
+ npm install ink-virtual-list
20
+
21
+ # jsr
22
+ npx jsr add @archcorsair/ink-virtual-list
23
+
24
+ # bun
25
+ bun add ink-virtual-list
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ### Basic Example
31
+
32
+ ```tsx
33
+ import { VirtualList } from 'ink-virtual-list';
34
+ import { Text } from 'ink';
35
+ import { useState } from 'react';
36
+
37
+ function App() {
38
+ const [selectedIndex, setSelectedIndex] = useState(0);
39
+ const items = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
40
+
41
+ return (
42
+ <VirtualList
43
+ items={items}
44
+ selectedIndex={selectedIndex}
45
+ height={10}
46
+ renderItem={({ item, isSelected }) => (
47
+ <Text color={isSelected ? 'cyan' : 'white'}>
48
+ {isSelected ? '> ' : ' '}
49
+ {item}
50
+ </Text>
51
+ )}
52
+ />
53
+ );
54
+ }
55
+ ```
56
+
57
+ ### Auto-fill Terminal Height
58
+
59
+ ```tsx
60
+ <VirtualList
61
+ items={items}
62
+ height="auto"
63
+ reservedLines={5} // Reserve space for header/footer
64
+ renderItem={({ item }) => <Text>{item}</Text>}
65
+ />
66
+ ```
67
+
68
+ ### Custom Overflow Indicators
69
+
70
+ ```tsx
71
+ <VirtualList
72
+ items={items}
73
+ renderOverflowTop={(count) => <Text dimColor>↑ {count} hidden</Text>}
74
+ renderOverflowBottom={(count) => <Text dimColor>↓ {count} hidden</Text>}
75
+ renderItem={({ item }) => <Text>{item}</Text>}
76
+ />
77
+ ```
78
+
79
+ ### Imperative Scrolling
80
+
81
+ ```tsx
82
+ import { useRef } from 'react';
83
+ import type { VirtualListRef } from 'ink-virtual-list';
84
+
85
+ function App() {
86
+ const listRef = useRef<VirtualListRef>(null);
87
+
88
+ const scrollToTop = () => {
89
+ listRef.current?.scrollToIndex(0, 'top');
90
+ };
91
+
92
+ return (
93
+ <VirtualList
94
+ ref={listRef}
95
+ items={items}
96
+ renderItem={({ item }) => <Text>{item}</Text>}
97
+ />
98
+ );
99
+ }
100
+ ```
101
+
102
+ ## API
103
+
104
+ ### Props
105
+
106
+ #### Required
107
+
108
+ - **`items: T[]`** - Array of items to render
109
+ - **`renderItem: (props: RenderItemProps<T>) => ReactNode`** - Render function for each visible item
110
+ - Receives: `{ item: T, index: number, isSelected: boolean }`
111
+
112
+ #### Optional
113
+
114
+ - **`selectedIndex?: number`** - Index of currently selected item (default: `0`)
115
+ - **`keyExtractor?: (item: T, index: number) => string`** - Custom key extractor for list items
116
+ - **`height?: number | "auto"`** - Fixed height in lines or `"auto"` to fill terminal (default: `10`)
117
+ - **`reservedLines?: number`** - Lines to reserve when using `height="auto"` (default: `0`)
118
+ - **`itemHeight?: number`** - Height of each item in lines (default: `1`)
119
+ - **`showOverflowIndicators?: boolean`** - Show "N more" indicators (default: `true`)
120
+ - **`renderOverflowTop?: (count: number) => ReactNode`** - Custom top overflow indicator
121
+ - **`renderOverflowBottom?: (count: number) => ReactNode`** - Custom bottom overflow indicator
122
+ - **`renderScrollBar?: (viewport: ViewportState) => ReactNode`** - Custom scrollbar renderer
123
+ - **`onViewportChange?: (viewport: ViewportState) => void`** - Callback when viewport changes
124
+
125
+ ### Ref Methods
126
+
127
+ ```typescript
128
+ interface VirtualListRef {
129
+ scrollToIndex: (index: number, alignment?: 'auto' | 'top' | 'center' | 'bottom') => void;
130
+ getViewport: () => ViewportState;
131
+ remeasure: () => void;
132
+ }
133
+ ```
134
+
135
+ - **`scrollToIndex(index, alignment?)`** - Scroll to bring an index into view
136
+ - `'auto'` (default) - Only scroll if needed
137
+ - `'top'` - Align item to top of viewport
138
+ - `'center'` - Center item in viewport
139
+ - `'bottom'` - Align item to bottom of viewport
140
+ - **`getViewport()`** - Get current viewport state (`{ offset, visibleCount, totalCount }`)
141
+ - **`remeasure()`** - Force recalculation of viewport dimensions
142
+
143
+ ### Types
144
+
145
+ ```typescript
146
+ interface RenderItemProps<T> {
147
+ item: T;
148
+ index: number;
149
+ isSelected: boolean;
150
+ }
151
+
152
+ interface ViewportState {
153
+ offset: number; // Items scrolled past
154
+ visibleCount: number; // Items currently visible
155
+ totalCount: number; // Total items
156
+ }
157
+ ```
158
+
159
+ ## Advanced Example
160
+
161
+ ```tsx
162
+ import { VirtualList } from 'ink-virtual-list';
163
+ import { Box, Text } from 'ink';
164
+ import { useRef, useState } from 'react';
165
+ import type { VirtualListRef } from 'ink-virtual-list';
166
+
167
+ interface Todo {
168
+ id: string;
169
+ title: string;
170
+ completed: boolean;
171
+ }
172
+
173
+ function TodoApp() {
174
+ const [todos] = useState<Todo[]>([
175
+ { id: '1', title: 'Learn Ink', completed: true },
176
+ { id: '2', title: 'Build CLI', completed: false },
177
+ // ... 1000s more
178
+ ]);
179
+ const [selectedIndex, setSelectedIndex] = useState(0);
180
+ const listRef = useRef<VirtualListRef>(null);
181
+
182
+ return (
183
+ <Box flexDirection="column">
184
+ <Text bold>My Todos ({todos.length})</Text>
185
+
186
+ <VirtualList
187
+ ref={listRef}
188
+ items={todos}
189
+ selectedIndex={selectedIndex}
190
+ height="auto"
191
+ reservedLines={3}
192
+ keyExtractor={(todo) => todo.id}
193
+ renderItem={({ item, isSelected }) => (
194
+ <Box>
195
+ <Text color={isSelected ? 'cyan' : 'white'}>
196
+ {isSelected ? '❯ ' : ' '}
197
+ {item.completed ? '✓' : '○'} {item.title}
198
+ </Text>
199
+ </Box>
200
+ )}
201
+ />
202
+
203
+ <Text dimColor>
204
+ {selectedIndex + 1} / {todos.length}
205
+ </Text>
206
+ </Box>
207
+ );
208
+ }
209
+ ```
210
+
211
+ ## License
212
+
213
+ MIT
package/dist/index.js.map CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["src\\useTerminalSize.ts", "src\\VirtualList.tsx"],
3
+ "sources": ["src/useTerminalSize.ts", "src/VirtualList.tsx"],
4
4
  "sourcesContent": [
5
5
  "import { useStdout } from \"ink\";\nimport { useEffect, useState } from \"react\";\n\n/**\n * Represents the terminal dimensions.\n */\nexport interface TerminalSize {\n /** Number of rows (lines) in the terminal */\n rows: number;\n /** Number of columns (characters) in the terminal */\n columns: number;\n}\n\nconst DEFAULT_ROWS = 24;\nconst DEFAULT_COLUMNS = 80;\n\n/**\n * Hook that returns the current terminal size and updates on resize.\n * Uses Ink's stdout to detect terminal dimensions.\n */\nexport function useTerminalSize(): TerminalSize {\n const { stdout } = useStdout();\n const [size, setSize] = useState<TerminalSize>({\n rows: stdout.rows ?? DEFAULT_ROWS,\n columns: stdout.columns ?? DEFAULT_COLUMNS,\n });\n\n useEffect(() => {\n // Skip resize listener in non-TTY environments (CI, pipes)\n if (!stdout.isTTY) {\n return;\n }\n\n const handleResize = () => {\n setSize({\n rows: stdout.rows ?? DEFAULT_ROWS,\n columns: stdout.columns ?? DEFAULT_COLUMNS,\n });\n };\n\n stdout.on(\"resize\", handleResize);\n return () => {\n stdout.off(\"resize\", handleResize);\n };\n }, [stdout]);\n\n return size;\n}\n",
6
6
  "import { Box, Text } from \"ink\";\nimport { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from \"react\";\nimport type { RenderItemProps, ViewportState, VirtualListProps, VirtualListRef } from \"./types\";\nimport { useTerminalSize } from \"./useTerminalSize\";\n\nconst DEFAULT_HEIGHT = 10;\nconst DEFAULT_ITEM_HEIGHT = 1;\n\n/**\n * Attempts to extract a stable key from an item.\n * Checks for 'id' or 'key' properties on objects before falling back to index.\n */\nfunction getDefaultKey<T>(item: T, index: number): string {\n if (item && typeof item === \"object\") {\n const obj = item as Record<string, unknown>;\n if (\"id\" in obj && (typeof obj.id === \"string\" || typeof obj.id === \"number\")) {\n return String(obj.id);\n }\n if (\"key\" in obj && (typeof obj.key === \"string\" || typeof obj.key === \"number\")) {\n return String(obj.key);\n }\n }\n return String(index);\n}\n\n/**\n * Validates that itemHeight is a positive integer.\n * Throws an error if invalid.\n *\n * @param itemHeight - The height to validate\n */\nexport function validateItemHeight(itemHeight: number): void {\n if (!Number.isInteger(itemHeight) || itemHeight < 1) {\n throw new Error(`[ink-virtual-list] itemHeight must be a positive integer, got: ${itemHeight}`);\n }\n}\n\n/**\n * Calculates the new viewport offset (scroll position) to ensure the selected index is visible.\n *\n * @param selectedIndex - The currently selected item index\n * @param currentOffset - The current viewport offset (top visible index)\n * @param visibleCount - The number of items that fit in the viewport\n * @returns The new offset, clamped to ensure the selection is visible\n */\nfunction calculateViewportOffset(selectedIndex: number, currentOffset: number, visibleCount: number): number {\n // Selection above viewport - scroll up\n if (selectedIndex < currentOffset) {\n return selectedIndex;\n }\n\n // Selection below viewport - scroll down\n if (selectedIndex >= currentOffset + visibleCount) {\n return selectedIndex - visibleCount + 1;\n }\n\n // Selection visible - no change\n return currentOffset;\n}\n\n/**\n * Inner component for VirtualList.\n * Handles the actual rendering logic, state management, and ref exposure.\n */\nfunction VirtualListInner<T>(props: VirtualListProps<T>, ref: React.ForwardedRef<VirtualListRef>): React.JSX.Element {\n const {\n items,\n renderItem,\n selectedIndex = 0,\n keyExtractor,\n height = DEFAULT_HEIGHT,\n reservedLines = 0,\n itemHeight = DEFAULT_ITEM_HEIGHT,\n showOverflowIndicators = true,\n overflowIndicatorThreshold = 1,\n renderOverflowTop,\n renderOverflowBottom,\n renderScrollBar,\n onViewportChange,\n } = props;\n\n // Validate itemHeight\n validateItemHeight(itemHeight);\n\n const { rows: terminalRows } = useTerminalSize();\n\n // Calculate resolved height\n const resolvedHeight = useMemo(() => {\n if (typeof height === \"number\") {\n return height;\n }\n // 'auto' - use terminal rows minus reserved\n return Math.max(1, terminalRows - reservedLines);\n }, [height, terminalRows, reservedLines]);\n\n const resolvedItemHeight = itemHeight ?? DEFAULT_ITEM_HEIGHT;\n\n // Reserve space for overflow indicators within the height budget\n const indicatorLines = showOverflowIndicators ? 2 : 0;\n const availableHeight = Math.max(0, resolvedHeight - indicatorLines);\n\n // Calculate how many items fit in viewport\n const visibleCount = Math.floor(availableHeight / resolvedItemHeight);\n\n // Clamp selectedIndex to valid range\n const clampedSelectedIndex = Math.max(0, Math.min(selectedIndex, items.length - 1));\n\n // Lazy initial offset - positions selection at bottom of viewport if needed\n const [viewportOffset, setViewportOffset] = useState(() => {\n if (items.length === 0) return 0;\n const maxOffset = Math.max(0, items.length - visibleCount);\n if (clampedSelectedIndex >= visibleCount) {\n return Math.min(clampedSelectedIndex - visibleCount + 1, maxOffset);\n }\n return 0;\n });\n\n // Sync viewport when selection changes\n useEffect(() => {\n const maxOffset = Math.max(0, items.length - visibleCount);\n const targetOffset = calculateViewportOffset(clampedSelectedIndex, viewportOffset, visibleCount);\n const clampedOffset = Math.min(Math.max(0, targetOffset), maxOffset);\n if (clampedOffset !== viewportOffset) {\n setViewportOffset(clampedOffset);\n }\n }, [clampedSelectedIndex, viewportOffset, visibleCount, items.length]);\n\n // Build viewport state\n const viewport: ViewportState = useMemo(\n () => ({\n offset: viewportOffset,\n visibleCount,\n totalCount: items.length,\n }),\n [viewportOffset, visibleCount, items.length],\n );\n\n // Notify on viewport change\n useEffect(() => {\n onViewportChange?.(viewport);\n }, [viewport, onViewportChange]);\n\n // Imperative handle\n useImperativeHandle(\n ref,\n () => ({\n scrollToIndex: (index: number, alignment: \"auto\" | \"top\" | \"center\" | \"bottom\" = \"auto\") => {\n const clampedIndex = Math.max(0, Math.min(index, items.length - 1));\n let newOffset: number;\n\n switch (alignment) {\n case \"top\":\n newOffset = clampedIndex;\n break;\n case \"center\":\n newOffset = clampedIndex - Math.floor(visibleCount / 2);\n break;\n case \"bottom\":\n newOffset = clampedIndex - visibleCount + 1;\n break;\n default: // 'auto'\n newOffset = calculateViewportOffset(clampedIndex, viewportOffset, visibleCount);\n }\n\n const maxOffset = Math.max(0, items.length - visibleCount);\n setViewportOffset(Math.min(Math.max(0, newOffset), maxOffset));\n },\n getViewport: () => viewport,\n remeasure: () => {\n // Force recalculation by updating state\n setViewportOffset((prev) => {\n const maxOffset = Math.max(0, items.length - visibleCount);\n return Math.min(prev, maxOffset);\n });\n },\n }),\n [items.length, visibleCount, viewportOffset, viewport],\n );\n\n // Calculate overflow counts\n const overflowTop = viewportOffset;\n const overflowBottom = Math.max(0, items.length - viewportOffset - visibleCount);\n\n // Get visible items\n const visibleItems = items.slice(viewportOffset, viewportOffset + visibleCount);\n\n // Default overflow renderers (paddingLeft aligns with list content)\n const defaultOverflowTop = (count: number) => (\n <Box paddingLeft={2}>\n <Text dimColor>▲ {count} more</Text>\n </Box>\n );\n const defaultOverflowBottom = (count: number) => (\n <Box paddingLeft={2}>\n <Text dimColor>▼ {count} more</Text>\n </Box>\n );\n\n const topIndicator = renderOverflowTop ?? defaultOverflowTop;\n const bottomIndicator = renderOverflowBottom ?? defaultOverflowBottom;\n\n return (\n <Box flexDirection=\"column\">\n {showOverflowIndicators && overflowTop >= overflowIndicatorThreshold && topIndicator(overflowTop)}\n\n {visibleItems.map((item, idx) => {\n const actualIndex = viewportOffset + idx;\n const key = keyExtractor ? keyExtractor(item, actualIndex) : getDefaultKey(item, actualIndex);\n\n const itemProps: RenderItemProps<T> = {\n item,\n index: actualIndex,\n isSelected: actualIndex === clampedSelectedIndex,\n };\n\n return (\n <Box key={key} height={resolvedItemHeight} overflow=\"hidden\">\n {renderItem(itemProps)}\n </Box>\n );\n })}\n\n {showOverflowIndicators && overflowBottom >= overflowIndicatorThreshold && bottomIndicator(overflowBottom)}\n\n {renderScrollBar?.(viewport)}\n </Box>\n );\n}\n\n/**\n * A virtualized list component for Ink.\n *\n * Efficiently renders large lists by only rendering items currently visible in the viewport.\n * Supports keyboard navigation, scrolling, and dynamic resizing.\n *\n * @example\n * ```tsx\n * <VirtualList\n * items={['Item 1', 'Item 2']}\n * renderItem={({item}) => <Text>{item}</Text>}\n * />\n * ```\n */\nexport const VirtualList = forwardRef(VirtualListInner) as <T>(\n props: VirtualListProps<T> & { ref?: React.ForwardedRef<VirtualListRef> },\n) => ReturnType<typeof VirtualListInner>;\n"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ink-virtual-list",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "A virtualized list component for Ink terminal applications",
5
5
  "type": "module",
6
6
  "files": [