@humanspeak/svelte-headless-table 6.0.3 → 6.0.4

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/README.md CHANGED
@@ -60,6 +60,7 @@ Easily extend Svelte Headless Table with complex **sorting**, **filtering**, **g
60
60
  - [x] [addSelectedRows](https://table.svelte.page/docs/plugins/add-selected-rows)
61
61
  - [x] [addResizedColumns](https://table.svelte.page/docs/plugins/add-resized-columns)
62
62
  - [x] [addGridLayout](https://table.svelte.page/docs/plugins/add-grid-layout)
63
+ - [x] [addVirtualScroll](https://table.svelte.page/docs/plugins/add-virtual-scroll)
63
64
 
64
65
  ## Examples
65
66
 
@@ -0,0 +1,37 @@
1
+ import type { NewTablePropSet, TablePlugin } from '../types/TablePlugin.js';
2
+ import type { ScrollToIndexOptions, VirtualScrollConfig, VirtualScrollRowProps, VirtualScrollState, VisibleRange } from './addVirtualScroll.types.js';
3
+ export type { ScrollToIndexOptions, VirtualScrollConfig, VirtualScrollState, VisibleRange };
4
+ /**
5
+ * Creates a virtual scroll plugin that enables virtualized table rendering.
6
+ * Only renders rows that are visible in the viewport plus a buffer, dramatically
7
+ * improving performance for large datasets.
8
+ *
9
+ * @template Item - The type of data items in the table.
10
+ * @param config - Configuration options for virtual scrolling.
11
+ * @returns A TablePlugin that provides virtualization functionality.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const table = createTable(data, {
16
+ * virtualScroll: addVirtualScroll({
17
+ * estimatedRowHeight: 48,
18
+ * bufferSize: 5,
19
+ * onLoadMore: async () => {
20
+ * const more = await fetchMoreItems()
21
+ * data.update(d => [...d, ...more])
22
+ * },
23
+ * hasMore: hasMoreStore
24
+ * })
25
+ * })
26
+ *
27
+ * const {
28
+ * virtualScroll,
29
+ * topSpacerHeight,
30
+ * bottomSpacerHeight,
31
+ * visibleRange
32
+ * } = table.pluginStates.virtualScroll
33
+ * ```
34
+ */
35
+ export declare const addVirtualScroll: <Item>({ onLoadMore, hasMore: hasMoreConfig, loadMoreThreshold, estimatedRowHeight, bufferSize, getRowHeight }?: VirtualScrollConfig<Item>) => TablePlugin<Item, VirtualScrollState<Item>, Record<string, never>, NewTablePropSet<{
36
+ "tbody.tr": VirtualScrollRowProps;
37
+ }>>;
@@ -0,0 +1,302 @@
1
+ import { derived, get, readable, writable } from 'svelte/store';
2
+ import { HeightManager } from '../utils/HeightManager.js';
3
+ /**
4
+ * Default configuration values for virtual scroll.
5
+ */
6
+ const DEFAULTS = {
7
+ estimatedRowHeight: 40,
8
+ bufferSize: 10,
9
+ loadMoreThreshold: 200
10
+ };
11
+ /**
12
+ * Creates a virtual scroll plugin that enables virtualized table rendering.
13
+ * Only renders rows that are visible in the viewport plus a buffer, dramatically
14
+ * improving performance for large datasets.
15
+ *
16
+ * @template Item - The type of data items in the table.
17
+ * @param config - Configuration options for virtual scrolling.
18
+ * @returns A TablePlugin that provides virtualization functionality.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * const table = createTable(data, {
23
+ * virtualScroll: addVirtualScroll({
24
+ * estimatedRowHeight: 48,
25
+ * bufferSize: 5,
26
+ * onLoadMore: async () => {
27
+ * const more = await fetchMoreItems()
28
+ * data.update(d => [...d, ...more])
29
+ * },
30
+ * hasMore: hasMoreStore
31
+ * })
32
+ * })
33
+ *
34
+ * const {
35
+ * virtualScroll,
36
+ * topSpacerHeight,
37
+ * bottomSpacerHeight,
38
+ * visibleRange
39
+ * } = table.pluginStates.virtualScroll
40
+ * ```
41
+ */
42
+ export const addVirtualScroll = ({ onLoadMore, hasMore: hasMoreConfig, loadMoreThreshold = DEFAULTS.loadMoreThreshold, estimatedRowHeight = DEFAULTS.estimatedRowHeight, bufferSize = DEFAULTS.bufferSize, getRowHeight } = {}) => () => {
43
+ // Height management
44
+ const heightManager = new HeightManager(estimatedRowHeight);
45
+ // Scroll state
46
+ const scrollTop = writable(0);
47
+ const viewportHeight = writable(0);
48
+ // Row IDs array (set by derivePageRows, used for calculations)
49
+ // This is a simple array, not derived from rows to avoid circular deps
50
+ const rowIds = writable([]);
51
+ // Loading state
52
+ const isLoading = writable(false);
53
+ const hasMoreStore = typeof hasMoreConfig === 'object' && hasMoreConfig !== null
54
+ ? hasMoreConfig
55
+ : writable(hasMoreConfig ?? false);
56
+ // Track whether we've already triggered a load to prevent duplicates
57
+ let loadMorePending = false;
58
+ // Scroll container reference (set by the action)
59
+ let scrollContainer = null;
60
+ // Cache for row lookup (set by derivePageRows)
61
+ let allRowsCache = [];
62
+ // Visible range calculation
63
+ const visibleRange = derived([rowIds, scrollTop, viewportHeight], ([$rowIds, $scrollTop, $viewportHeight]) => {
64
+ return heightManager.getVisibleRange($rowIds, $scrollTop, $viewportHeight, bufferSize);
65
+ });
66
+ // Total height of all rows
67
+ const totalHeight = derived(rowIds, ($rowIds) => {
68
+ return heightManager.getTotalHeight($rowIds);
69
+ });
70
+ // Spacer heights
71
+ const topSpacerHeight = derived([rowIds, visibleRange], ([$rowIds, $range]) => {
72
+ return heightManager.getOffsetForIndex($rowIds, $range.start);
73
+ });
74
+ const bottomSpacerHeight = derived([rowIds, visibleRange, totalHeight], ([$rowIds, $range, $total]) => {
75
+ const endOffset = heightManager.getOffsetForIndex($rowIds, $range.end);
76
+ return Math.max(0, $total - endOffset);
77
+ });
78
+ // Total and rendered row counts
79
+ const totalRows = derived(rowIds, ($rowIds) => $rowIds.length);
80
+ const renderedRows = derived(visibleRange, ($range) => $range.end - $range.start);
81
+ /**
82
+ * Check if we should load more data and trigger the callback.
83
+ */
84
+ const checkLoadMore = () => {
85
+ if (!onLoadMore || loadMorePending || !get(hasMoreStore)) {
86
+ return;
87
+ }
88
+ const $scrollTop = get(scrollTop);
89
+ const $viewportHeight = get(viewportHeight);
90
+ const $totalHeight = get(totalHeight);
91
+ const distanceFromBottom = $totalHeight - ($scrollTop + $viewportHeight);
92
+ if (distanceFromBottom <= loadMoreThreshold) {
93
+ loadMorePending = true;
94
+ isLoading.set(true);
95
+ const result = onLoadMore();
96
+ if (result instanceof Promise) {
97
+ result.finally(() => {
98
+ loadMorePending = false;
99
+ isLoading.set(false);
100
+ });
101
+ }
102
+ else {
103
+ loadMorePending = false;
104
+ isLoading.set(false);
105
+ }
106
+ }
107
+ };
108
+ /**
109
+ * Handle scroll events from the container.
110
+ */
111
+ const handleScroll = (event) => {
112
+ const target = event.target;
113
+ const newScrollTop = target.scrollTop;
114
+ scrollTop.set(newScrollTop);
115
+ checkLoadMore();
116
+ };
117
+ /**
118
+ * Svelte action to attach to the scroll container.
119
+ */
120
+ const virtualScroll = (node) => {
121
+ scrollContainer = node;
122
+ // Set initial viewport height
123
+ const initialHeight = node.clientHeight;
124
+ viewportHeight.set(initialHeight);
125
+ // Create ResizeObserver to track viewport size changes
126
+ const resizeObserver = new ResizeObserver((entries) => {
127
+ for (const entry of entries) {
128
+ viewportHeight.set(entry.contentRect.height);
129
+ }
130
+ });
131
+ resizeObserver.observe(node);
132
+ // Attach scroll listener
133
+ node.addEventListener('scroll', handleScroll, { passive: true });
134
+ // Check if we need to load more initially
135
+ checkLoadMore();
136
+ return {
137
+ destroy() {
138
+ scrollContainer = null;
139
+ node.removeEventListener('scroll', handleScroll);
140
+ resizeObserver.disconnect();
141
+ }
142
+ };
143
+ };
144
+ /**
145
+ * Scroll to a specific row index.
146
+ */
147
+ const scrollToIndex = (index, options = {}) => {
148
+ if (!scrollContainer) {
149
+ return;
150
+ }
151
+ const { align = 'start', behavior = 'auto' } = options;
152
+ const $rowIds = get(rowIds);
153
+ if (index < 0 || index >= $rowIds.length) {
154
+ return;
155
+ }
156
+ const targetOffset = heightManager.getOffsetForIndex($rowIds, index);
157
+ const rowHeight = heightManager.getHeight($rowIds[index]);
158
+ const $viewportHeight = get(viewportHeight);
159
+ let scrollPosition;
160
+ switch (align) {
161
+ case 'center':
162
+ scrollPosition = targetOffset - ($viewportHeight - rowHeight) / 2;
163
+ break;
164
+ case 'end':
165
+ scrollPosition = targetOffset - $viewportHeight + rowHeight;
166
+ break;
167
+ case 'auto': {
168
+ // Check if already visible
169
+ const $scrollTop = get(scrollTop);
170
+ const visibleStart = $scrollTop;
171
+ const visibleEnd = $scrollTop + $viewportHeight;
172
+ const rowStart = targetOffset;
173
+ const rowEnd = targetOffset + rowHeight;
174
+ if (rowStart >= visibleStart && rowEnd <= visibleEnd) {
175
+ // Already fully visible
176
+ return;
177
+ }
178
+ else if (rowStart < visibleStart) {
179
+ scrollPosition = rowStart;
180
+ }
181
+ else {
182
+ scrollPosition = rowEnd - $viewportHeight;
183
+ }
184
+ break;
185
+ }
186
+ case 'start':
187
+ default:
188
+ scrollPosition = targetOffset;
189
+ break;
190
+ }
191
+ scrollContainer.scrollTo({
192
+ top: Math.max(0, scrollPosition),
193
+ behavior
194
+ });
195
+ };
196
+ /**
197
+ * Notify the plugin that a row has been measured.
198
+ */
199
+ const measureRow = (rowId, height) => {
200
+ // If getRowHeight is provided, prefer that
201
+ if (getRowHeight) {
202
+ const row = allRowsCache.find((r) => r.id === rowId);
203
+ if (row?.isData() && row.original) {
204
+ const specifiedHeight = getRowHeight(row.original);
205
+ if (specifiedHeight !== height) {
206
+ height = specifiedHeight;
207
+ }
208
+ }
209
+ }
210
+ const changed = heightManager.setHeight(rowId, height);
211
+ if (changed) {
212
+ // Force recalculation of derived stores by updating rowIds
213
+ // (touching it with the same value)
214
+ rowIds.update((v) => v);
215
+ }
216
+ };
217
+ /**
218
+ * Svelte action to automatically measure row height.
219
+ * Attach to each <tr> element: <tr use:measureRowAction={row.id}>
220
+ */
221
+ const measureRowAction = (node, rowId) => {
222
+ // Measure initial height
223
+ const measure = () => {
224
+ const height = node.getBoundingClientRect().height;
225
+ if (height > 0) {
226
+ measureRow(rowId, height);
227
+ }
228
+ };
229
+ // Measure on mount
230
+ measure();
231
+ // Use ResizeObserver to track height changes
232
+ const resizeObserver = new ResizeObserver(() => {
233
+ measure();
234
+ });
235
+ resizeObserver.observe(node);
236
+ return {
237
+ update(newRowId) {
238
+ rowId = newRowId;
239
+ measure();
240
+ },
241
+ destroy() {
242
+ resizeObserver.disconnect();
243
+ }
244
+ };
245
+ };
246
+ // Plugin state
247
+ const pluginState = {
248
+ scrollTop: { subscribe: scrollTop.subscribe },
249
+ viewportHeight: { subscribe: viewportHeight.subscribe },
250
+ visibleRange,
251
+ totalHeight,
252
+ topSpacerHeight,
253
+ bottomSpacerHeight,
254
+ isLoading: { subscribe: isLoading.subscribe },
255
+ hasMore: { subscribe: hasMoreStore.subscribe },
256
+ virtualScroll,
257
+ scrollToIndex,
258
+ measureRow,
259
+ measureRowAction,
260
+ totalRows,
261
+ renderedRows
262
+ };
263
+ /**
264
+ * Derive visible rows from all page rows.
265
+ * Re-runs when rows, scroll position, or viewport height changes.
266
+ */
267
+ const derivePageRows = (rows) => {
268
+ return derived([rows, scrollTop, viewportHeight], ([$rows, $scrollTop, $viewportHeight], set) => {
269
+ // Cache rows for lookup in measureRow and hooks
270
+ allRowsCache = $rows;
271
+ // Extract row IDs and update the store (only if changed)
272
+ const ids = $rows.map((r) => r.id);
273
+ const currentIds = get(rowIds);
274
+ if (ids.length !== currentIds.length ||
275
+ ids.some((id, i) => id !== currentIds[i])) {
276
+ rowIds.set(ids);
277
+ }
278
+ // Calculate visible range
279
+ const range = heightManager.getVisibleRange(ids, $scrollTop, $viewportHeight, bufferSize);
280
+ // Return only the visible subset
281
+ const visibleRows = $rows.slice(range.start, range.end);
282
+ set(visibleRows);
283
+ });
284
+ };
285
+ // Hooks to add virtual index props to rows
286
+ const hooks = {
287
+ 'tbody.tr': (row) => {
288
+ const virtualIndex = allRowsCache.findIndex((r) => r.id === row.id);
289
+ return {
290
+ props: readable({
291
+ virtualIndex: virtualIndex >= 0 ? virtualIndex : 0,
292
+ isVirtual: true
293
+ })
294
+ };
295
+ }
296
+ };
297
+ return {
298
+ pluginState,
299
+ derivePageRows,
300
+ hooks
301
+ };
302
+ };
@@ -0,0 +1,139 @@
1
+ import type { Action } from 'svelte/action';
2
+ import type { Readable, Writable } from 'svelte/store';
3
+ /**
4
+ * Configuration options for the addVirtualScroll plugin.
5
+ *
6
+ * @template Item - The type of data items in the table.
7
+ */
8
+ export interface VirtualScrollConfig<Item> {
9
+ /**
10
+ * Callback fired when more data should be loaded (infinite scroll).
11
+ * Return a promise to indicate when loading is complete.
12
+ */
13
+ onLoadMore?: () => void | Promise<void>;
14
+ /**
15
+ * Whether there is more data available to load.
16
+ * Can be a boolean or a Writable store.
17
+ */
18
+ hasMore?: Writable<boolean> | boolean;
19
+ /**
20
+ * Number of pixels from the bottom to trigger onLoadMore.
21
+ * @default 200
22
+ */
23
+ loadMoreThreshold?: number;
24
+ /**
25
+ * Estimated height of each row in pixels.
26
+ * Used for initial calculations before rows are measured.
27
+ * @default 40
28
+ */
29
+ estimatedRowHeight?: number;
30
+ /**
31
+ * Number of rows to render above and below the visible area.
32
+ * Higher values reduce flicker during fast scrolling but render more DOM nodes.
33
+ * @default 10
34
+ */
35
+ bufferSize?: number;
36
+ /**
37
+ * Optional function to get the height of a specific row.
38
+ * If provided, enables variable row heights.
39
+ */
40
+ getRowHeight?: (_item: Item) => number;
41
+ }
42
+ /**
43
+ * Visible range of rows.
44
+ */
45
+ export interface VisibleRange {
46
+ /** Index of the first visible row (0-based). */
47
+ start: number;
48
+ /** Index of the last visible row (exclusive). */
49
+ end: number;
50
+ }
51
+ /**
52
+ * Options for scrollToIndex method.
53
+ */
54
+ export interface ScrollToIndexOptions {
55
+ /** Alignment of the target row within the viewport. */
56
+ align?: 'start' | 'center' | 'end' | 'auto';
57
+ /** Scroll behavior. */
58
+ behavior?: ScrollBehavior;
59
+ }
60
+ /**
61
+ * State exposed by the addVirtualScroll plugin.
62
+ *
63
+ * @template Item - The type of data items in the table.
64
+ */
65
+ export interface VirtualScrollState<Item> {
66
+ /**
67
+ * Current scroll position of the container.
68
+ */
69
+ scrollTop: Readable<number>;
70
+ /**
71
+ * Height of the scroll container viewport.
72
+ */
73
+ viewportHeight: Readable<number>;
74
+ /**
75
+ * Range of currently visible row indices.
76
+ */
77
+ visibleRange: Readable<VisibleRange>;
78
+ /**
79
+ * Total height of all rows (for scroll container sizing).
80
+ */
81
+ totalHeight: Readable<number>;
82
+ /**
83
+ * Height of the top spacer element.
84
+ */
85
+ topSpacerHeight: Readable<number>;
86
+ /**
87
+ * Height of the bottom spacer element.
88
+ */
89
+ bottomSpacerHeight: Readable<number>;
90
+ /**
91
+ * Whether more data is currently being loaded.
92
+ */
93
+ isLoading: Readable<boolean>;
94
+ /**
95
+ * Whether there is more data available to load.
96
+ */
97
+ hasMore: Readable<boolean>;
98
+ /**
99
+ * Svelte action to attach to the scroll container.
100
+ * Handles scroll event listeners and viewport tracking.
101
+ */
102
+ virtualScroll: Action<HTMLElement>;
103
+ /**
104
+ * Scroll to a specific row index.
105
+ */
106
+ scrollToIndex: (_index: number, _options?: ScrollToIndexOptions) => void;
107
+ /**
108
+ * Notify the plugin that a row has been measured.
109
+ * Called automatically when rows are rendered.
110
+ * @internal
111
+ */
112
+ measureRow: (_rowId: string, _height: number) => void;
113
+ /**
114
+ * Svelte action to attach to each table row for automatic height measurement.
115
+ * Usage: <tr use:measureRowAction={row.id}>
116
+ */
117
+ measureRowAction: Action<HTMLElement, string>;
118
+ /**
119
+ * Total number of rows (before virtualization).
120
+ */
121
+ totalRows: Readable<number>;
122
+ /**
123
+ * Number of rows currently rendered in the DOM.
124
+ */
125
+ renderedRows: Readable<number>;
126
+ }
127
+ /**
128
+ * Props added to body rows by the virtual scroll plugin.
129
+ */
130
+ export interface VirtualScrollRowProps {
131
+ /**
132
+ * Index of this row in the full dataset.
133
+ */
134
+ virtualIndex: number;
135
+ /**
136
+ * Whether this row is currently in the visible range.
137
+ */
138
+ isVirtual: boolean;
139
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -12,4 +12,5 @@ export * from './addSelectedRows';
12
12
  export * from './addSortBy';
13
13
  export * from './addSubRows';
14
14
  export * from './addTableFilter';
15
+ export * from './addVirtualScroll';
15
16
  export * from '../types/TablePlugin';
@@ -12,5 +12,6 @@ export * from './addSelectedRows';
12
12
  export * from './addSortBy';
13
13
  export * from './addSubRows';
14
14
  export * from './addTableFilter';
15
+ export * from './addVirtualScroll';
15
16
  // plugin helper types
16
17
  export * from '../types/TablePlugin';
@@ -0,0 +1,107 @@
1
+ /**
2
+ * HeightManager handles row height caching and calculations for virtual scrolling.
3
+ * It maintains a cache of measured row heights and provides methods to calculate
4
+ * scroll positions, visible ranges, and total heights.
5
+ */
6
+ export declare class HeightManager {
7
+ /** Cache of measured row heights by row ID. */
8
+ private heightCache;
9
+ /** Estimated height for unmeasured rows. */
10
+ private estimatedRowHeight;
11
+ /** Sum of all measured heights. */
12
+ private totalMeasuredHeight;
13
+ /** Number of measured rows. */
14
+ private measuredCount;
15
+ /**
16
+ * Creates a new HeightManager.
17
+ *
18
+ * @param estimatedRowHeight - Initial estimated height for unmeasured rows.
19
+ */
20
+ constructor(estimatedRowHeight?: number);
21
+ /**
22
+ * Set or update the height for a specific row.
23
+ *
24
+ * @param rowId - The unique identifier of the row.
25
+ * @param height - The measured height of the row in pixels.
26
+ * @returns True if the height changed, false otherwise.
27
+ */
28
+ setHeight(rowId: string, height: number): boolean;
29
+ /**
30
+ * Get the height for a specific row.
31
+ * Returns the measured height if available, otherwise the estimated height.
32
+ *
33
+ * @param rowId - The unique identifier of the row.
34
+ * @returns The height of the row in pixels.
35
+ */
36
+ getHeight(rowId: string): number;
37
+ /**
38
+ * Check if a row has been measured.
39
+ *
40
+ * @param rowId - The unique identifier of the row.
41
+ * @returns True if the row has been measured.
42
+ */
43
+ hasMeasurement(rowId: string): boolean;
44
+ /**
45
+ * Get the average height of measured rows.
46
+ * Falls back to the estimated height if no rows have been measured.
47
+ *
48
+ * @returns The average row height in pixels.
49
+ */
50
+ getAverageHeight(): number;
51
+ /**
52
+ * Calculate the total height for a given number of rows.
53
+ *
54
+ * @param rowIds - Array of row IDs in order.
55
+ * @returns The total height in pixels.
56
+ */
57
+ getTotalHeight(rowIds: string[]): number;
58
+ /**
59
+ * Calculate the offset (top position) for a given row index.
60
+ *
61
+ * @param rowIds - Array of row IDs in order.
62
+ * @param index - The index of the target row.
63
+ * @returns The offset from the top in pixels.
64
+ */
65
+ getOffsetForIndex(rowIds: string[], index: number): number;
66
+ /**
67
+ * Calculate which rows are visible given a scroll position and viewport height.
68
+ *
69
+ * @param rowIds - Array of row IDs in order.
70
+ * @param scrollTop - Current scroll position.
71
+ * @param viewportHeight - Height of the visible area.
72
+ * @param bufferSize - Number of extra rows to render above/below.
73
+ * @returns Object with start and end indices of visible rows.
74
+ */
75
+ getVisibleRange(rowIds: string[], scrollTop: number, viewportHeight: number, bufferSize: number): {
76
+ start: number;
77
+ end: number;
78
+ };
79
+ /**
80
+ * Find the row index at a given scroll position.
81
+ *
82
+ * @param rowIds - Array of row IDs in order.
83
+ * @param scrollTop - The scroll position to find.
84
+ * @returns The index of the row at that position.
85
+ */
86
+ getIndexAtOffset(rowIds: string[], scrollTop: number): number;
87
+ /**
88
+ * Clear all cached heights.
89
+ */
90
+ clear(): void;
91
+ /**
92
+ * Remove a specific row from the cache.
93
+ *
94
+ * @param rowId - The unique identifier of the row to remove.
95
+ */
96
+ remove(rowId: string): void;
97
+ /**
98
+ * Get the number of measured rows.
99
+ */
100
+ get size(): number;
101
+ /**
102
+ * Update the estimated row height.
103
+ *
104
+ * @param height - New estimated height in pixels.
105
+ */
106
+ setEstimatedRowHeight(height: number): void;
107
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * HeightManager handles row height caching and calculations for virtual scrolling.
3
+ * It maintains a cache of measured row heights and provides methods to calculate
4
+ * scroll positions, visible ranges, and total heights.
5
+ */
6
+ export class HeightManager {
7
+ /** Cache of measured row heights by row ID. */
8
+ heightCache = new Map();
9
+ /** Estimated height for unmeasured rows. */
10
+ estimatedRowHeight;
11
+ /** Sum of all measured heights. */
12
+ totalMeasuredHeight = 0;
13
+ /** Number of measured rows. */
14
+ measuredCount = 0;
15
+ /**
16
+ * Creates a new HeightManager.
17
+ *
18
+ * @param estimatedRowHeight - Initial estimated height for unmeasured rows.
19
+ */
20
+ constructor(estimatedRowHeight = 40) {
21
+ this.estimatedRowHeight = estimatedRowHeight;
22
+ }
23
+ /**
24
+ * Set or update the height for a specific row.
25
+ *
26
+ * @param rowId - The unique identifier of the row.
27
+ * @param height - The measured height of the row in pixels.
28
+ * @returns True if the height changed, false otherwise.
29
+ */
30
+ setHeight(rowId, height) {
31
+ const existing = this.heightCache.get(rowId);
32
+ if (existing === height) {
33
+ return false;
34
+ }
35
+ if (existing !== undefined) {
36
+ // Update existing measurement
37
+ this.totalMeasuredHeight -= existing;
38
+ this.totalMeasuredHeight += height;
39
+ }
40
+ else {
41
+ // New measurement
42
+ this.totalMeasuredHeight += height;
43
+ this.measuredCount++;
44
+ }
45
+ this.heightCache.set(rowId, height);
46
+ return true;
47
+ }
48
+ /**
49
+ * Get the height for a specific row.
50
+ * Returns the measured height if available, otherwise the estimated height.
51
+ *
52
+ * @param rowId - The unique identifier of the row.
53
+ * @returns The height of the row in pixels.
54
+ */
55
+ getHeight(rowId) {
56
+ return this.heightCache.get(rowId) ?? this.getAverageHeight();
57
+ }
58
+ /**
59
+ * Check if a row has been measured.
60
+ *
61
+ * @param rowId - The unique identifier of the row.
62
+ * @returns True if the row has been measured.
63
+ */
64
+ hasMeasurement(rowId) {
65
+ return this.heightCache.has(rowId);
66
+ }
67
+ /**
68
+ * Get the average height of measured rows.
69
+ * Falls back to the estimated height if no rows have been measured.
70
+ *
71
+ * @returns The average row height in pixels.
72
+ */
73
+ getAverageHeight() {
74
+ if (this.measuredCount === 0) {
75
+ return this.estimatedRowHeight;
76
+ }
77
+ return this.totalMeasuredHeight / this.measuredCount;
78
+ }
79
+ /**
80
+ * Calculate the total height for a given number of rows.
81
+ *
82
+ * @param rowIds - Array of row IDs in order.
83
+ * @returns The total height in pixels.
84
+ */
85
+ getTotalHeight(rowIds) {
86
+ const avgHeight = this.getAverageHeight();
87
+ let total = 0;
88
+ for (const rowId of rowIds) {
89
+ total += this.heightCache.get(rowId) ?? avgHeight;
90
+ }
91
+ return total;
92
+ }
93
+ /**
94
+ * Calculate the offset (top position) for a given row index.
95
+ *
96
+ * @param rowIds - Array of row IDs in order.
97
+ * @param index - The index of the target row.
98
+ * @returns The offset from the top in pixels.
99
+ */
100
+ getOffsetForIndex(rowIds, index) {
101
+ const avgHeight = this.getAverageHeight();
102
+ let offset = 0;
103
+ for (let i = 0; i < index && i < rowIds.length; i++) {
104
+ offset += this.heightCache.get(rowIds[i]) ?? avgHeight;
105
+ }
106
+ return offset;
107
+ }
108
+ /**
109
+ * Calculate which rows are visible given a scroll position and viewport height.
110
+ *
111
+ * @param rowIds - Array of row IDs in order.
112
+ * @param scrollTop - Current scroll position.
113
+ * @param viewportHeight - Height of the visible area.
114
+ * @param bufferSize - Number of extra rows to render above/below.
115
+ * @returns Object with start and end indices of visible rows.
116
+ */
117
+ getVisibleRange(rowIds, scrollTop, viewportHeight, bufferSize) {
118
+ if (rowIds.length === 0) {
119
+ return { start: 0, end: 0 };
120
+ }
121
+ const avgHeight = this.getAverageHeight();
122
+ let offset = 0;
123
+ let start = 0;
124
+ let end = rowIds.length;
125
+ // Find start index (first row that's at least partially visible)
126
+ for (let i = 0; i < rowIds.length; i++) {
127
+ const height = this.heightCache.get(rowIds[i]) ?? avgHeight;
128
+ if (offset + height > scrollTop) {
129
+ start = Math.max(0, i - bufferSize);
130
+ break;
131
+ }
132
+ offset += height;
133
+ }
134
+ // Find end index (first row that's completely below the viewport)
135
+ const bottomEdge = scrollTop + viewportHeight;
136
+ for (let i = start; i < rowIds.length; i++) {
137
+ const height = this.heightCache.get(rowIds[i]) ?? avgHeight;
138
+ if (offset >= bottomEdge) {
139
+ end = Math.min(rowIds.length, i + bufferSize);
140
+ break;
141
+ }
142
+ offset += height;
143
+ }
144
+ // If we reached the end without finding bottomEdge, show all remaining rows
145
+ if (end === rowIds.length) {
146
+ end = rowIds.length;
147
+ }
148
+ return { start, end };
149
+ }
150
+ /**
151
+ * Find the row index at a given scroll position.
152
+ *
153
+ * @param rowIds - Array of row IDs in order.
154
+ * @param scrollTop - The scroll position to find.
155
+ * @returns The index of the row at that position.
156
+ */
157
+ getIndexAtOffset(rowIds, scrollTop) {
158
+ const avgHeight = this.getAverageHeight();
159
+ let offset = 0;
160
+ for (let i = 0; i < rowIds.length; i++) {
161
+ const height = this.heightCache.get(rowIds[i]) ?? avgHeight;
162
+ if (offset + height > scrollTop) {
163
+ return i;
164
+ }
165
+ offset += height;
166
+ }
167
+ return Math.max(0, rowIds.length - 1);
168
+ }
169
+ /**
170
+ * Clear all cached heights.
171
+ */
172
+ clear() {
173
+ this.heightCache.clear();
174
+ this.totalMeasuredHeight = 0;
175
+ this.measuredCount = 0;
176
+ }
177
+ /**
178
+ * Remove a specific row from the cache.
179
+ *
180
+ * @param rowId - The unique identifier of the row to remove.
181
+ */
182
+ remove(rowId) {
183
+ const height = this.heightCache.get(rowId);
184
+ if (height !== undefined) {
185
+ this.totalMeasuredHeight -= height;
186
+ this.measuredCount--;
187
+ this.heightCache.delete(rowId);
188
+ }
189
+ }
190
+ /**
191
+ * Get the number of measured rows.
192
+ */
193
+ get size() {
194
+ return this.measuredCount;
195
+ }
196
+ /**
197
+ * Update the estimated row height.
198
+ *
199
+ * @param height - New estimated height in pixels.
200
+ */
201
+ setEstimatedRowHeight(height) {
202
+ this.estimatedRowHeight = height;
203
+ }
204
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@humanspeak/svelte-headless-table",
3
- "version": "6.0.3",
3
+ "version": "6.0.4",
4
4
  "description": "A powerful, headless table library for Svelte that provides complete control over table UI while handling complex data operations like sorting, filtering, pagination, grouping, and row expansion. Build custom, accessible data tables with zero styling opinions.",
5
5
  "keywords": [
6
6
  "svelte",
@@ -69,13 +69,13 @@
69
69
  "@faker-js/faker": "^10.2.0",
70
70
  "@playwright/test": "^1.58.1",
71
71
  "@sveltejs/adapter-auto": "^7.0.0",
72
- "@sveltejs/kit": "^2.50.1",
72
+ "@sveltejs/kit": "^2.50.2",
73
73
  "@sveltejs/package": "^2.5.7",
74
74
  "@sveltejs/vite-plugin-svelte": "^6.2.4",
75
75
  "@testing-library/jest-dom": "^6.9.1",
76
76
  "@testing-library/svelte": "^5.3.1",
77
77
  "@types/eslint": "9.6.1",
78
- "@types/node": "^25.1.0",
78
+ "@types/node": "^25.2.0",
79
79
  "@typescript-eslint/eslint-plugin": "^8.54.0",
80
80
  "@typescript-eslint/parser": "^8.54.0",
81
81
  "@vitest/coverage-v8": "^4.0.18",
@@ -85,7 +85,7 @@
85
85
  "eslint-plugin-import": "2.32.0",
86
86
  "eslint-plugin-svelte": "3.14.0",
87
87
  "eslint-plugin-unused-imports": "4.3.0",
88
- "globals": "^17.2.0",
88
+ "globals": "^17.3.0",
89
89
  "husky": "^9.1.7",
90
90
  "prettier": "^3.8.1",
91
91
  "prettier-plugin-organize-imports": "^4.3.0",
@@ -94,9 +94,9 @@
94
94
  "prettier-plugin-tailwindcss": "^0.7.2",
95
95
  "publint": "^0.3.17",
96
96
  "svelte": "^5.49.1",
97
- "svelte-check": "^4.3.5",
97
+ "svelte-check": "^4.3.6",
98
98
  "tslib": "^2.8.1",
99
- "type-fest": "^5.4.2",
99
+ "type-fest": "^5.4.3",
100
100
  "typescript": "^5.9.3",
101
101
  "typescript-eslint": "^8.54.0",
102
102
  "vite": "^7.3.1",