@pdanpdan/virtual-scroll 0.3.0 → 0.5.0

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
@@ -2,15 +2,26 @@
2
2
 
3
3
  A high-performance, flexible virtual scrolling component for Vue 3.
4
4
 
5
- ## Features
5
+ ## Scaled Virtual Scroll
6
6
 
7
- - **High Performance**: Optimized for large lists using Fenwick Tree (_O(log n)_) for offset calculations.
7
+ To support massive datasets (billions of pixels) while staying within browser scroll limits, the library uses a dual-unit coordinate system:
8
+
9
+ * **VU (Virtual Units)**: The internal coordinate system representing the actual size of your content.
10
+ * **DU (Display Units)**: The browser's physical coordinate system (limited to `BROWSER_MAX_SIZE`).
11
+
12
+ The library automatically calculates a scaling factor and applies a specialized formula to ensure **1:1 movement** in the viewport during wheel and touch scrolling, while maintaining proportional positioning during scrollbar interaction.
13
+
14
+ ### Core Rendering Rule
15
+ Items are rendered at their VU size and positioned using `translateY()` based on the current display scroll position and their virtual offset. This prevents "jumping" and maintains sub-pixel precision even at extreme scales.
16
+ - **Virtual Scrollbars**: Highly optimized virtual scrollbars that replace native ones, providing consistent cross-browser styling and handling massive content scales. Supports custom slots for complete UI control.
17
+ - **Performance Optimized**: Uses CSS `@layer` for style isolation and `contain: layout` for improved rendering performance.
8
18
  - **Dynamic & Fixed Sizes**: Supports both uniform item sizes and variable sizes via `ResizeObserver`.
9
19
  - **Multi-Directional**: Works in `vertical`, `horizontal`, or `both` (grid) directions.
10
20
  - **Container Flexibility**: Can use a custom element or the browser `window`/`body` as the scroll container.
11
21
  - **SSR Support**: Built-in support for pre-rendering specific ranges for Server-Side Rendering.
12
22
  - **Feature Rich**: Supports infinite scroll, loading states, sticky sections, headers, footers, buffers, and programmatic scrolling.
13
23
  - **Scroll Restoration**: Automatically maintains scroll position when items are prepended to the list.
24
+ - **RTL Support**: Full support for Right-to-Left (RTL) layouts with automatic detection.
14
25
 
15
26
  ## Installation
16
27
 
@@ -36,11 +47,6 @@ import '@pdanpdan/virtual-scroll/style.css';
36
47
  </script>
37
48
  ```
38
49
 
39
- **Why use this?**
40
- - Fastest build times (no need to compile the component logic).
41
- - Maximum compatibility with different build tools.
42
- - Scoped CSS works perfectly as it is extracted into `style.css` with unique data attributes.
43
-
44
50
  ### 2. Original Vue SFC
45
51
 
46
52
  If you want to compile the component yourself using your own Vue compiler configuration, you can import the raw `.vue` file.
@@ -52,48 +58,15 @@ import VirtualScroll from '@pdanpdan/virtual-scroll/VirtualScroll.vue';
52
58
  </script>
53
59
  ```
54
60
 
55
- **Why use this?**
56
- - Allows for better tree-shaking and optimization by your own bundler.
57
- - Enables deep integration with your project's CSS-in-JS or specialized styling solutions.
58
- - Easier debugging of the component source in some IDEs.
59
-
60
61
  ### 3. CDN Usage
61
62
 
62
- You can use the library directly from a CDN like unpkg or jsdelivr.
63
-
64
63
  ```html
65
64
  <!-- Import Vue 3 first -->
66
65
  <script src="https://unpkg.com/vue@3"></script>
67
-
68
66
  <!-- Import VirtualScroll CSS -->
69
- <link rel="stylesheet" href="https://unpkg.com/@pdanpdan/virtual-scroll/dist/virtual-scroll.css">
70
-
67
+ <link rel="stylesheet" href="https://unpkg.com/@pdanpdan/virtual-scroll/dist/style.css">
71
68
  <!-- Import VirtualScroll JavaScript -->
72
69
  <script src="https://unpkg.com/@pdanpdan/virtual-scroll"></script>
73
-
74
- <div id="app">
75
- <div style="height: 400px; overflow: auto;">
76
- <virtual-scroll :items="items" :item-size="50">
77
- <template #item="{ item, index }">
78
- <div style="height: 50px;">{{ index }}: {{ item.label }}</div>
79
- </template>
80
- </virtual-scroll>
81
- </div>
82
- </div>
83
-
84
- <script>
85
- const { createApp, ref } = Vue;
86
- const { VirtualScroll } = window.VirtualScroll;
87
-
88
- createApp({
89
- setup() {
90
- const items = ref(Array.from({ length: 1000 }, (_, i) => ({ label: `Item ${i}` })));
91
- return { items };
92
- }
93
- })
94
- .component('VirtualScroll', VirtualScroll)
95
- .mount('#app');
96
- </script>
97
70
  ```
98
71
 
99
72
  ## Basic Usage
@@ -108,278 +81,298 @@ const items = Array.from({ length: 10000 }, (_, i) => ({ id: i, label: `Item ${
108
81
  </script>
109
82
 
110
83
  <template>
111
- <div class="my-container">
112
- <VirtualScroll :items="items" :item-size="50">
113
- <template #item="{ item, index }">
114
- <div class="my-item">
115
- {{ index }}: {{ item.label }}
116
- </div>
117
- </template>
118
- </VirtualScroll>
119
- </div>
84
+ <VirtualScroll :items="items" :item-size="50" class="my-container">
85
+ <template #item="{ item, index }">
86
+ <div class="my-item">{{ index }}: {{ item.label }}</div>
87
+ </template>
88
+ </VirtualScroll>
120
89
  </template>
121
90
 
122
91
  <style>
123
- .my-container {
124
- height: 500px;
125
- overflow: auto;
126
- }
127
- .my-item {
128
- height: 50px;
129
- }
92
+ .my-container { height: 500px; }
93
+ .my-item { height: 50px; }
130
94
  </style>
131
95
  ```
132
96
 
133
97
  ## Sizing Guide
134
98
 
135
- The component offers flexible ways to define item and column sizes. Understanding how these options interact is key to achieving smooth scrolling and correct layout.
136
-
137
- ### Sizing Options
138
-
139
99
  | Option Type | `itemSize` / `columnWidth` | Performance | Description |
140
100
  |-------------|----------------------------|-------------|-------------|
141
101
  | **Fixed** | `number` (e.g., `50`) | **Best** | Every item has the exact same size. Calculations are *O(1)*. |
142
102
  | **Array** | `number[]` (cols only) | **Great** | Each column has a fixed size from the array (cycles if shorter). |
143
- | **Function** | `(item, index) => number` | **Good** | Size is known but varies per item. No `ResizeObserver` overhead unless it differs from measured size. |
144
- | **Dynamic** | `0`, `null`, or `undefined` | **Fair** | Sizes are measured automatically via `ResizeObserver` after rendering. |
145
-
146
- ### How Sizing Works
147
-
148
- 1. **Initial Estimate**:
149
- - If a **fixed size** or **function** is provided, it's used as the initial size.
150
- - If **dynamic** is used, the component uses `defaultItemSize` (default: `40`) or `defaultColumnWidth` (default: `100`) as the initial estimate.
151
- 2. **Measurement**:
152
- - When an item is rendered, its actual size is measured using `ResizeObserver`.
153
- - If the measured size differs from the estimate (by more than 0.5px), the internal Fenwick Tree is updated.
154
- 3. **Refinement**:
155
- - All subsequent item positions are automatically adjusted based on the new measurement.
156
- - The total scrollable area (`totalWidth`/`totalHeight`) is updated to reflect the real content size.
157
-
158
- ### Fallback Logic
159
-
160
- - **Unset Props**: If `itemSize` or `columnWidth` are not provided, they default to `40` and `100` respectively (fixed).
161
- - **Dynamic Fallback**: When using dynamic sizing, `defaultItemSize` and `defaultColumnWidth` act as the source of truth for items that haven't been rendered yet.
162
- - **Function/Array Fallback**: If a function or array returns an invalid value, it falls back to the respective `default...` prop.
163
-
164
- ### Recommendations for Smooth Scrolling
103
+ | **Function** | `(item, index) => number` | **Good** | Size is known but varies per item. |
104
+ | **Dynamic** | `0`, `null`, or `undefined` | **Fair** | Sizes are measured automatically via `ResizeObserver`. |
165
105
 
166
- 1. **Accurate Estimates**: When using dynamic sizing, set `defaultItemSize` as close as possible to the *average* height of your items. This minimizes scrollbar "jumping".
167
- 2. **Avoid 0 sizes**: Ensure your items have a minimum height/width (e.g., via CSS `min-height`). Items with 0 size might not be detected correctly by the virtualizer.
168
- 3. **Box Sizing**: Use `box-sizing: border-box` on your items to ensure padding and borders are included in the measured size.
169
- 4. **Manual Refresh**: If you change external state that affects a sizing function's output without changing the function reference itself, call `virtualScrollRef.refresh()` to force a full re-calculation.
170
-
171
- ## Component Reference
172
-
173
- The `VirtualScroll` component provides a declarative interface for virtualizing lists and grids. It automatically manages the rendering lifecycle of items, measures dynamic sizes, and handles complex scroll behaviors like stickiness and restoration.
106
+ ## Component Reference: VirtualScroll
174
107
 
175
108
  ### Props
176
109
 
177
- #### Core Configuration
178
110
  | Prop | Type | Default | Description |
179
111
  |------|------|---------|-------------|
180
112
  | `items` | `T[]` | Required | Array of items to be virtualized. |
181
- | `itemSize` | `number \| ((item: T, index: number) => number) \| null` | `40` | Fixed size or function. Pass `0`/`null` for dynamic. |
113
+ | `itemSize` | `number \| fn \| null` | `40` | Fixed size or function. Pass `0`/`null` for dynamic. |
182
114
  | `direction` | `'vertical' \| 'horizontal' \| 'both'` | `'vertical'` | Scroll direction. |
183
- | `gap` | `number` | `0` | Spacing between items. |
184
-
185
- ### Grid Configuration (direction="both")
186
- | Prop | Type | Default | Description |
187
- |------|------|---------|-------------|
188
- | `columnCount` | `number` | `0` | Number of columns. |
189
- | `columnWidth` | `num \| num[] \| fn \| null` | `100` | Width for columns. |
190
- | `columnGap` | `number` | `0` | Spacing between columns. |
191
-
192
- ### Features & Behavior
193
- | Prop | Type | Default | Description |
194
- |------|------|---------|-------------|
115
+ | `columnCount` | `number` | `0` | Number of columns for grid mode. |
116
+ | `columnWidth` | `num \| num[] \| fn \| null` | `100` | Width for columns in grid mode. |
117
+ | `gap` / `columnGap` | `number` | `0` | Spacing between items/columns. |
195
118
  | `stickyIndices` | `number[]` | `[]` | Indices of items that should remain sticky. |
196
119
  | `stickyHeader` / `stickyFooter` | `boolean` | `false` | If true, measures and adds slot size to padding. |
197
- | `ssrRange` | `object` | `undefined` | Items to pre-render on server. |
198
- | `loading` | `boolean` | `false` | Shows loading state and prevents duplicate events. |
199
- | `loadDistance` | `number` | `200` | Distance from end to trigger `load` event. |
120
+ | `virtualScrollbar` | `boolean` | `false` | Whether to force virtual scrollbars. |
200
121
  | `restoreScrollOnPrepend` | `boolean` | `false` | Maintain position when items added to top. |
201
- | `initialScrollIndex` | `number` | `undefined` | Index to jump to on mount. |
202
- | `initialScrollAlign` | `string \| object` | `'start'` | Alignment for initial jump. |
203
-
204
- ### Advanced & Performance
205
- | Prop | Type | Default | Description |
206
- |------|------|---------|-------------|
207
- | `container` | `HTMLElement \| Window` | `host element` | The scrollable container element. |
122
+ | `container` | `HTMLElement \| Window` | `hostRef` | The scrollable container element. |
208
123
  | `scrollPaddingStart` / `End` | `num \| {x, y}` | `0` | Padding for scroll calculations. |
209
- | `containerTag` / `wrapperTag` / `itemTag` | `string` | `'div'` | HTML tags for component parts. |
210
124
  | `bufferBefore` / `bufferAfter` | `number` | `5` | Items to render outside the viewport. |
211
- | `defaultItemSize` | `number` | `40` | Initial estimate for items. |
212
- | `defaultColumnWidth` | `number` | `100` | Initial estimate for columns. |
213
- | `debug` | `boolean` | `false` | Enables debug visualization. |
214
-
215
- ## Slots
216
-
217
- - `item`: Scoped slot for individual items.
218
- - `item`: The data item.
219
- - `index`: The index of the item.
220
- - `columnRange`: `{ start, end, padStart, padEnd }` information for grid mode.
221
- - `getColumnWidth`: `(index: number) => number` helper for grid mode.
222
- - `isSticky`: Whether the item is configured to be sticky.
223
- - `isStickyActive`: Whether the item is currently stuck at the threshold.
224
- - `header`: Content prepended to the scrollable area.
225
- - `footer`: Content appended to the scrollable area.
226
- - `loading`: Content shown at the end of the list when `loading` prop is true.
227
-
228
- ## Events
229
-
230
- - `scroll`: Emitted when the container scrolls.
231
- - `details`: `ScrollDetails<T>` object containing current state.
232
- - `load`: Emitted when scrolling near the end of the content.
233
- - `direction`: `'vertical'` or `'horizontal'`.
234
- - `visibleRangeChange`: Emitted when the rendered items range or column range changes.
235
- - `range`: `{ start: number; end: number; colStart: number; colEnd: number; }`
236
-
237
- ## Keyboard Navigation
238
-
239
- When the container is focused, it supports the following keys:
240
- - `Home`: Scroll to the beginning of the list (index 0).
241
- - `End`: Scroll to the last item in the list.
242
- - `ArrowUp` / `ArrowDown`: Scroll up/down by 40px (or `DEFAULT_ITEM_SIZE`).
243
- - `ArrowLeft` / `ArrowRight`: Scroll left/right by 40px (or `DEFAULT_ITEM_SIZE`).
244
- - `PageUp` / `PageDown`: Scroll up/down (or left/right) by one viewport size.
245
-
246
- ## Methods (Exposed)
247
-
248
- - `scrollToIndex(rowIndex: number | null, colIndex: number | null, options?: ScrollAlignment | ScrollAlignmentOptions | ScrollToIndexOptions)`
249
- - `rowIndex`: Row index to scroll to. Pass `null` to only scroll horizontally.
250
- - `colIndex`: Column index to scroll to. Pass `null` to only scroll vertically.
251
- - `options`:
252
- - `align`: `'start' | 'center' | 'end' | 'auto'` or `{ x: ScrollAlignment, y: ScrollAlignment }`.
253
- - `behavior`: `'auto' | 'smooth'`.
254
- - `scrollToOffset(x: number | null, y: number | null, options?: { behavior?: 'auto' | 'smooth' })`
255
- - `x`: Pixel offset on X axis. Pass `null` to keep current position.
256
- - `y`: Pixel offset on Y axis. Pass `null` to keep current position.
257
- - `options`:
258
- - `behavior`: `'auto' | 'smooth'`.
259
- - `refresh()`: Resets all dynamic measurements and re-initializes sizes from current items and props.
260
- - `stopProgrammaticScroll()`: Immediately stops any active smooth scroll.
261
-
262
- ## Types
263
-
264
- ### ScrollDetails&lt;T&gt;
265
-
266
- The full state of the virtualizer, emitted in the `scroll` event and available via the `scrollDetails` ref.
267
-
268
- | Property | Type | Description |
269
- |----------|------|-------------|
270
- | `items` | `RenderedItem<T>[]` | List of items currently rendered with their offsets and sizes. |
271
- | `currentIndex` | `number` | Index of the first item partially or fully visible in the viewport. |
272
- | `currentColIndex` | `number` | Index of the first column partially or fully visible. |
273
- | `scrollOffset` | `{ x: number, y: number }` | Current scroll position relative to content start. |
274
- | `viewportSize` | `{ width: number, height: number }` | Dimensions of the visible area. |
275
- | `totalSize` | `{ width: number, height: number }` | Total calculated size of all items and gaps. |
276
- | `isScrolling` | `boolean` | Whether the container is currently being scrolled. |
277
- | `isProgrammaticScroll` | `boolean` | Whether the current scroll was initiated by a method call. |
278
- | `range` | `{ start: number, end: number }` | Current rendered item indices. |
279
- | `columnRange` | `{ start: number, end: number, padStart: number, padEnd: number }` | Visible column range and paddings. |
280
-
281
- ### RenderedItem&lt;T&gt;
282
-
283
- | Property | Type | Description |
284
- |----------|------|-------------|
285
- | `item` | `T` | The data item. |
286
- | `index` | `number` | The item's index in the original array. |
287
- | `offset` | `{ x: number, y: number }` | Calculated position for rendering. |
288
- | `size` | `{ width: number, height: number }` | Measured or estimated size. |
289
- | `originalX` / `originalY` | `number` | Raw offsets before sticky adjustments. |
290
- | `isSticky` | `boolean` | Whether the item is configured to be sticky. |
291
- | `isStickyActive` | `boolean` | Whether the item is currently stuck. |
292
- | `stickyOffset` | `{ x: number, y: number }` | Offset applied for the pushing effect. |
293
-
294
- ### ScrollAlignment
295
-
296
- - `'start'`: Aligns the item to the top/left of the viewport.
297
- - `'center'`: Aligns the item to the center of the viewport.
298
- - `'end'`: Aligns the item to the bottom/right of the viewport.
299
- - `'auto'`: Smart alignment - if the item is already visible, do nothing; if it's above/left, align to `start`; if it's below/right, align to `end`.
300
-
301
- ## CSS Classes
302
-
303
- - `.virtual-scroll-container`: Root container.
304
- - `.virtual-scroll--vertical`, `.virtual-scroll--horizontal`, `.virtual-scroll--both`: Direction modifier.
305
- - `.virtual-scroll-wrapper`: Items wrapper.
306
- - `.virtual-scroll-item`: Individual item.
307
- - `.virtual-scroll-header` / `.virtual-scroll-footer`: Header/Footer slots.
308
- - `.virtual-scroll-loading`: Loading slot container.
309
- - `.virtual-scroll--sticky`: Applied to sticky elements.
310
- - `.virtual-scroll--hydrated`: Applied when client-side mount is complete.
311
- - `.virtual-scroll--window`: Applied when using window/body scroll.
312
- - `.virtual-scroll--table`: Applied when `containerTag="table"` is used.
313
- - `.virtual-scroll--debug`: Applied when debug mode is enabled.
314
-
315
- ## SSR Support
316
-
317
- The component is designed to be SSR-friendly. You can pre-render a specific range of items on the server using the `ssrRange` prop.
125
+ | `initialScrollIndex` | `number` | `undefined` | Index to jump to on mount. |
126
+ | `initialScrollAlign` | `ScrollAlignment \| object` | `'start'` | Alignment for initial jump. See [ScrollAlignment](#scrollalignment). |
127
+ | `defaultItemSize` / `defaultColumnWidth` | `number` | `40 / 100` | Estimate for dynamic items/columns. |
128
+
129
+ ### Slots
130
+
131
+ - `item`: Scoped slot for individual items. Provides `item`, `index`, `columnRange`, `getColumnWidth`, `gap`, `columnGap`, `isSticky`, `isStickyActive`.
132
+ - `header` / `footer`: Content rendered at the top/bottom of the scrollable area.
133
+ - `loading`: Content shown at the end when `loading` prop is true.
134
+ - `scrollbar`: Scoped slot for custom scrollbar. Called once for each active axis.
135
+ - `axis`: `'vertical' | 'horizontal'`
136
+ - `positionPercent`: current position (0-1).
137
+ - `viewportPercent`: viewport percentage (0-1).
138
+ - `trackProps`: Attributes/listeners for the track. Bind with `v-bind="trackProps"`.
139
+ - `thumbProps`: Attributes/listeners for the thumb. Bind with `v-bind="thumbProps"`.
140
+ - `scrollbarProps`: Grouped props for the `VirtualScrollbar` component.
141
+ - `axis`: `'vertical' | 'horizontal'`
142
+ - `totalSize`: virtual content size in pixels.
143
+ - `position`: current virtual scroll offset.
144
+ - `viewportSize`: virtual visible area size.
145
+ - `scrollToOffset`: `(offset: number) => void`
146
+ - `containerId`: unique ID of the container.
147
+ - `isRtl`: `boolean` (current RTL state).
148
+
149
+ ### Exposed Members
150
+
151
+ The following properties and methods are available on the `VirtualScroll` component instance (via template `ref`).
152
+
153
+ #### Properties
154
+ - **All Props**: All properties defined in [Props](#props) are available on the instance.
155
+ - [`scrollDetails`](#scrolldetails): Full reactive state of the virtual scroll system.
156
+ - [`columnRange`](#columnrange): Information about the current visible range of columns.
157
+ - `isHydrated`: `true` when the component is mounted and hydrated.
158
+ - `isRtl`: `true` if the container is in Right-to-Left mode.
159
+ - [`scrollbarPropsVertical`](#scrollbarslotprops) / [`scrollbarPropsHorizontal`](#scrollbarslotprops): Reactive [ScrollbarSlotProps](#scrollbarslotprops).
160
+ - `scaleX` / `scaleY`: Current coordinate scaling factors (VU/DU).
161
+ - `renderedWidth` / `renderedHeight`: Physical dimensions in DOM (clamped, DU).
162
+ - `componentOffset`: Absolute offset of the component within its container (DU).
163
+
164
+ #### Methods
165
+ - `scrollToIndex(row, col, options)`: Programmatic scroll to index.
166
+ - `scrollToOffset(x, y, options)`: Programmatic scroll to pixel position.
167
+ - `refresh()`: Resets all measurements and state.
168
+ - `stopProgrammaticScroll()`: Halt smooth scroll animations.
169
+ - `updateDirection()`: Manually trigger direction detection.
170
+ - `getRowHeight(index)`: Returns the calculated height of a row.
171
+ - `getColumnWidth(index)`: Returns the calculated width of a column.
172
+ - `getRowOffset(index)`: Returns the virtual offset of a row.
173
+ - `getColumnOffset(index)`: Returns the virtual offset of a column.
174
+ - `getItemOffset(index)`: Returns the virtual offset of an item.
175
+ - `getItemSize(index)`: Returns the size of an item along the scroll axis.
176
+
177
+ ## Virtual Scrollbars
178
+
179
+ Virtual scrollbars are automatically enabled when content size exceeds browser limits, but can be forced via the `virtualScrollbar` prop.
180
+
181
+ **Note:** Virtual scrollbars and coordinate scaling are automatically disabled when the `container` is the browser `window` or `body`. In these cases, native scrolling behavior is used.
182
+
183
+ ### Using the `VirtualScrollbar` Component
184
+
185
+ You can use the built-in `VirtualScrollbar` independently if needed.
186
+
187
+ ```vue
188
+ <script setup>
189
+ import { VirtualScrollbar } from '@pdanpdan/virtual-scroll';
190
+ import { ref } from 'vue';
191
+
192
+ const scrollX = ref(0);
193
+ const scrollY = ref(0);
194
+ </script>
195
+
196
+ <template>
197
+ <div class="my-container relative overflow-hidden">
198
+ <VirtualScrollbar
199
+ axis="vertical"
200
+ :total-size="10000"
201
+ :viewport-size="500"
202
+ :position="scrollY"
203
+ @scroll-to-offset="val => scrollY = val"
204
+ />
205
+ <VirtualScrollbar
206
+ axis="horizontal"
207
+ :total-size="10000"
208
+ :viewport-size="800"
209
+ :position="scrollX"
210
+ @scroll-to-offset="val => scrollX = val"
211
+ />
212
+ </div>
213
+ </template>
214
+ ```
215
+
216
+ ### Using the `scrollbar` Slot
217
+
218
+ The `scrollbar` slot provides everything needed to build a fully custom interface using `v-bind`. It is called once for each active axis.
318
219
 
319
220
  ```vue
320
- <VirtualScroll
321
- :items="items"
322
- :ssr-range="{ start: 100, end: 120, colStart: 50, colEnd: 70 }"
323
- >
324
- <!-- ... -->
325
- </VirtualScroll>
221
+ <template>
222
+ <VirtualScroll :items="items" direction="both" virtual-scrollbar>
223
+ <template #scrollbar="{ trackProps, thumbProps, axis }">
224
+ <!-- Handle axes separately -->
225
+ <div v-if="axis === 'vertical'" v-bind="trackProps" class="custom-v-track">
226
+ <div v-bind="thumbProps" class="custom-v-thumb" />
227
+ </div>
228
+ <div v-else v-bind="trackProps" class="custom-h-track">
229
+ <div v-bind="thumbProps" class="custom-h-thumb" />
230
+ </div>
231
+ </template>
232
+ </VirtualScroll>
233
+ </template>
326
234
  ```
327
235
 
328
- When `ssrRange` is provided:
329
- 1. **Server-Side**: Only the specified range of items is rendered. Items are rendered in-flow (relative positioning) with their offsets adjusted so the specified range appears at the top-left of the container.
330
- 2. **Client-Side Hydration**:
331
- - The component initially renders the SSR content to match the server-generated HTML.
332
- - On mount, it expands the container size and automatically scrolls to exactly match the pre-rendered range using `align: 'start'`.
333
- - It then seamlessly transitions to virtual mode (absolute positioning) while maintaining the scroll position.
236
+ ### CSS Variables for Default Scrollbar
334
237
 
335
- ## Composable API
238
+ The default scrollbar uses CSS `@layer components` for better isolation and customization.
336
239
 
337
- For advanced use cases, you can use the underlying logic via the `useVirtualScroll` composable.
240
+ | Variable | Default (Light/Dark) | Description |
241
+ |----------|-----------------|-------------|
242
+ | `--vs-scrollbar-bg` | `rgba(230,230,230,0.9) / rgba(30,30,30,0.9)` | Track background color. |
243
+ | `--vs-scrollbar-thumb-bg` | `rgba(0,0,0,0.3) / rgba(255,255,255,0.3)` | Thumb background color. |
244
+ | `--vs-scrollbar-thumb-hover-bg` | `rgba(0,0,0,0.6) / rgba(255,255,255,0.6)` | Thumb background on hover/active. |
245
+ | `--vs-scrollbar-size` | `8px` | Width/height of the scrollbar. |
246
+ | `--vs-scrollbar-radius` | `4px` | Border radius for track and thumb. |
247
+ | `--vs-scrollbar-cross-gap` | `var(--vs-scrollbar-size)` | Size of gap to use where scrollbars meet. |
248
+ | `--vs-scrollbar-has-cross-gap` | `0` | If gap should be shown where scrollbars meet. |
338
249
 
339
- ### Example
250
+ ## Composables
340
251
 
341
- ```typescript
342
- /* eslint-disable unused-imports/no-unused-vars */
343
- import { useVirtualScroll } from '@pdanpdan/virtual-scroll';
344
- import { computed, ref } from 'vue';
252
+ ### `useVirtualScroll`
253
+
254
+ Provides the core logic for virtualization.
255
+
256
+ ```ts
257
+ /* eslint-disable unused-imports/no-unused-vars, no-undef */
258
+ const { renderedItems, scrollDetails, scrollToIndex } = useVirtualScroll(props);
259
+ ```
345
260
 
346
- const items = ref([ { id: 1 }, { id: 2 } ]);
347
- const containerRef = ref<HTMLElement | null>(null);
261
+ ### `useVirtualScrollbar`
348
262
 
349
- const props = computed(() => ({
350
- items: items.value,
351
- itemSize: 50,
352
- container: containerRef.value,
353
- direction: 'vertical' as const,
354
- }));
263
+ Provides the logic for scrollbar interactions.
355
264
 
356
- const { renderedItems, scrollDetails, totalHeight } = useVirtualScroll(props);
265
+ ```ts
266
+ /* eslint-disable unused-imports/no-unused-vars, no-undef */
267
+ const { trackProps, thumbProps } = useVirtualScrollbar(props);
357
268
  ```
358
269
 
359
- ### Return Values
360
-
361
- | Member | Type | Description |
362
- |--------|------|-------------|
363
- | `renderedItems` | `Ref<RenderedItem<T>[]>` | List of items to be rendered. |
364
- | `scrollDetails` | `Ref<ScrollDetails<T>>` | Full state of the virtualizer. |
365
- | `totalWidth` / `totalHeight` | `Ref<number>` | Calculated total dimensions. |
366
- | `columnRange` | `Ref<object>` | Visible column range. |
367
- | `isHydrated` | `Ref<boolean>` | Whether hydration is complete. |
368
- | `scrollToIndex` | `Function` | Programmatic scroll to index. |
369
- | `scrollToOffset` | `Function` | Programmatic scroll to offset. |
370
- | `refresh` | `Function` | Resets and recalculates all sizes. |
371
- | `updateItemSize` | `Function` | Manually update an item's size. |
372
-
373
- ## Utilities
374
-
375
- The library exports several utility functions and classes:
376
-
377
- - `isElement(val: any): val is HTMLElement`: Checks if value is an `HTMLElement` (excludes `window`).
378
- - `isScrollableElement(val: any): val is HTMLElement | Window`: Checks if value has scroll properties.
379
- - `isScrollToIndexOptions(val: any): val is ScrollToIndexOptions`: Type guard for scroll options.
380
- - `getPaddingX / getPaddingY`: Internal helpers for extraction of padding from props.
381
- - `FenwickTree`: The underlying data structure for efficient size and offset management.
382
- - `DEFAULT_ITEM_SIZE / DEFAULT_COLUMN_WIDTH / DEFAULT_BUFFER`: The default values used by the library.
270
+ ## Utility Functions
271
+
272
+ - **Type Guards**:
273
+ - `isElement(val: any): val is HTMLElement`: Checks if value is a standard `HTMLElement` (excludes `window`).
274
+ - `isWindow(val: any): val is Window`: Checks for the global `window` object.
275
+ - `isBody(val: any): val is HTMLElement`: Checks for the `document.body` element.
276
+ - `isWindowLike(val: any): boolean`: Returns `true` if the value is `window` or `body`.
277
+ - `isScrollableElement(val: any): val is HTMLElement | Window`: Checks if value has scroll properties.
278
+ - `isScrollToIndexOptions(val: any): val is ScrollToIndexOptions`: Type guard for scroll options.
279
+ - `getPaddingX(p: number | object, dir: string): number`: Internal helper for padding.
280
+ - `getPaddingY(p: number | object, dir: string): number`: Internal helper for padding.
281
+ - **Coordinate Mapping**:
282
+ - `displayToVirtual(displayPos, hostOffset, scale): number`: Display pixels to virtual pixels.
283
+ - `virtualToDisplay(virtualPos, hostOffset, scale): number`: Virtual pixels to display pixels.
284
+ - `isItemVisible(itemPos, itemSize, scrollPos, viewSize, stickyOffset?): boolean`: Check item visibility.
285
+ - `FenwickTree`: Highly efficient data structure for size and offset management.
286
+ - **Default Constants**:
287
+ - `BROWSER_MAX_SIZE`: 10,000,000 (coordinate scaling threshold).
288
+ - `DEFAULT_ITEM_SIZE`: 40px (default row height).
289
+ - `DEFAULT_COLUMN_WIDTH`: 100px (default column width).
290
+ - `DEFAULT_BUFFER`: 5 items (default buffer before/after).
291
+
292
+ ## API Reference
293
+
294
+ ### Types
295
+
296
+ #### `ScrollDirection`
297
+ Values: `'vertical' | 'horizontal' | 'both'`
298
+
299
+ #### `ScrollAxis`
300
+ Values: `'vertical' | 'horizontal'`
301
+
302
+ #### `ScrollAlignment`
303
+ Values: `'start' | 'center' | 'end' | 'auto'`
304
+
305
+ #### `ScrollToIndexOptions`
306
+ - `align`: `ScrollAlignment | ScrollAlignmentOptions`
307
+ - `behavior`: `'auto' | 'smooth'`
308
+
309
+ #### `ScrollAlignmentOptions`
310
+ - `x`: `ScrollAlignment`
311
+ - `y`: `ScrollAlignment`
312
+
313
+ #### `ScrollbarSlotProps`
314
+ - `positionPercent`: current position as a percentage (0 to 1).
315
+ - `viewportPercent`: viewport as a percentage of total size (0 to 1).
316
+ - `thumbSizePercent`: calculated thumb size as a percentage of the track (0 to 100).
317
+ - `thumbPositionPercent`: calculated thumb position as a percentage of the track (0 to 100).
318
+ - `trackProps`: attributes/listeners for track. Bind with `v-bind="trackProps"`.
319
+ - `thumbProps`: attributes/listeners for thumb. Bind with `v-bind="thumbProps"`.
320
+ - `scrollbarProps`: grouped props for `VirtualScrollbar` component.
321
+ - `axis`: `'vertical' | 'horizontal'`
322
+ - `totalSize`: virtual content size in pixels.
323
+ - `position`: current virtual scroll offset.
324
+ - `viewportSize`: virtual visible area size.
325
+ - `scrollToOffset`: `(offset: number) => void`
326
+ - `containerId`: unique ID of the container.
327
+ - `isRtl`: `boolean`
328
+ - `isDragging`: whether the scrollbar thumb is currently being dragged.
329
+
330
+ #### `ScrollDetails`
331
+ - `items`: `RenderedItem<T>[]`
332
+ - `currentIndex`: number (first visible row index below header)
333
+ - `currentColIndex`: number (first visible column index after sticky)
334
+ - `currentEndIndex`: number
335
+ - `currentEndColIndex`: number
336
+ - `scrollOffset`: `{ x, y }` (VU)
337
+ - `displayScrollOffset`: `{ x, y }` (DU)
338
+ - `viewportSize`: `{ width, height }` (VU)
339
+ - `displayViewportSize`: `{ width, height }` (DU)
340
+ - `totalSize`: `{ width, height }` (VU)
341
+ - `isScrolling`: boolean
342
+ - `isProgrammaticScroll`: boolean
343
+ - `range`: `{ start, end }`
344
+ - `columnRange`: `ColumnRange`
345
+
346
+ #### `ColumnRange`
347
+ - `start`: number
348
+ - `end`: number
349
+ - `padStart`: number (VU)
350
+ - `padEnd`: number (VU)
351
+
352
+ #### `RenderedItem`
353
+ - `item`: `T`
354
+ - `index`: number
355
+ - `offset`: `{ x, y }` (DU)
356
+ - `size`: `{ width, height }` (VU)
357
+ - `originalX` / `originalY`: number (VU)
358
+ - `isSticky`: boolean
359
+ - `isStickyActive`: boolean
360
+ - `stickyOffset`: `{ x, y }` (DU)
361
+
362
+ ### Methods
363
+
364
+ The following methods are exposed by the `VirtualScroll` component and the `useVirtualScroll` composable:
365
+
366
+ - `scrollToIndex(rowIndex, colIndex, options)`: Ensures a specific item is visible.
367
+ - `scrollToOffset(x, y, options)`: Scrolls to an absolute pixel position.
368
+ - `refresh()`: Resets all dynamic measurements and state.
369
+ - `getRowHeight(index)` / `getColumnWidth(index)`: Returns calculated sizes.
370
+ - `updateItemSize` / `updateItemSizes`: Manually registers new measurements.
371
+ - `updateHostOffset()`: Recalculates the component's relative position.
372
+ - `updateDirection()`: Manually triggers RTL/LTR detection.
373
+ - `stopProgrammaticScroll()`: Halts any active smooth scroll animation.
374
+
375
+ For detailed type definitions and utility functions, see the [Full API Reference](https://pdandev.github.io/virtual-scroll/docs).
383
376
 
384
377
  ## License
385
378