@zhangt58/svelte-vtable 0.0.1

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 ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 zhangt58
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.
22
+
package/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # @zhangt58/svelte-vtable
2
+
3
+ A Svelte 5 library providing virtualized data tables with sorting, selection, search, and pagination controls. Built with Svelte 5 runes for reactive state management.
4
+
5
+ ## Features
6
+
7
+ - 🚀 **Virtualized rendering** - Efficiently handles large datasets
8
+ - 🔄 **Sorting** - Click column headers to sort
9
+ - 🔍 **Search** - Built-in search filtering
10
+ - 📄 **Pagination** - Configurable page controls with ellipsis navigation
11
+ - ✅ **Selection** - Row selection with callback support
12
+ - 🎨 **Styling** - Tailwind CSS based with dark mode support
13
+ - 📱 **Responsive** - Flexible column widths with stretch weights
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @zhangt58/svelte-vtable
19
+ ```
20
+
21
+ ## Peer Dependencies
22
+
23
+ This library requires the following peer dependencies to be installed in your project:
24
+
25
+ ```bash
26
+ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-svelte-icons@^3.0.0 svelte-virtuallists@^1.0.0
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ```svelte
32
+ <script>
33
+ import { VirtualDataTable, DataTableControls } from '@zhangt58/svelte-vtable';
34
+
35
+ let items = $state([
36
+ { id: 1, name: 'Alice', email: 'alice@example.com' },
37
+ { id: 2, name: 'Bob', email: 'bob@example.com' },
38
+ // ... more items
39
+ ]);
40
+
41
+ const ui = $state({
42
+ searchQuery: '',
43
+ currentPage: 1,
44
+ perPage: 25,
45
+ sortKey: null,
46
+ sortDir: 'asc'
47
+ });
48
+
49
+ const visibleKeys = ['name', 'email'];
50
+ const colWidths = { name: 1, email: 2 }; // stretch weights
51
+ </script>
52
+
53
+ <DataTableControls
54
+ search={ui.searchQuery}
55
+ currentPage={ui.currentPage}
56
+ perPage={ui.perPage}
57
+ totalItems={items.length}
58
+ pagechange={(e) => ui.currentPage = e.currentPage}
59
+ searchchange={(e) => ui.searchQuery = e.search}
60
+ />
61
+
62
+ <VirtualDataTable
63
+ {items}
64
+ {visibleKeys}
65
+ sortKey={ui.sortKey}
66
+ sortDir={ui.sortDir}
67
+ sortCallback={(key) => { /* handle sort */ }}
68
+ selectCallback={(detail) => { /* handle selection */ }}
69
+ {colWidths}
70
+ >
71
+ {#snippet rowSnippet({item, index, select, selected})}
72
+ <tr onclick={select}>
73
+ <td>{item.name}</td>
74
+ <td>{item.email}</td>
75
+ </tr>
76
+ {/snippet}
77
+ </VirtualDataTable>
78
+ ```
79
+
80
+ ## Components
81
+
82
+ ### VirtualDataTable
83
+
84
+ A virtualized table component for efficient rendering of large datasets.
85
+
86
+ #### Props
87
+
88
+ | Prop | Type | Default | Description |
89
+ |------|------|---------|-------------|
90
+ | `items` | `Array` | `[]` | Array of data items to display |
91
+ | `visibleKeys` | `Array` | `[]` | Array of keys/titles to display as column headers |
92
+ | `sortKey` | `string \| null` | `null` | Current sort key (column header) |
93
+ | `sortDir` | `'asc' \| 'desc'` | `'asc'` | Sort direction |
94
+ | `className` | `string` | `''` | Additional CSS classes |
95
+ | `style` | `string` | `''` | Inline styles |
96
+ | `emptyMessage` | `string` | `'No items to display.'` | Message when no items |
97
+ | `colWidths` | `object \| Array` | `{}` | Column width configuration (stretch weights or pixel values) |
98
+ | `selected` | `any` | `null` | Currently selected item |
99
+ | `selectCallback` | `function` | `() => {}` | Callback when a row is selected: `({item, index}) => void` |
100
+ | `sortCallback` | `function` | `defaultSort` | Callback when sorting: `(headerKey) => void` |
101
+ | `rowSnippet` | `Snippet` | required | Svelte 5 snippet for rendering rows |
102
+
103
+ #### Row Snippet Parameters
104
+
105
+ The `rowSnippet` receives an object with:
106
+ - `item` - The current row data
107
+ - `index` - Row index in the current page
108
+ - `select` - Function to call to select this row
109
+ - `selected` - Currently selected item (for comparison)
110
+
111
+ #### Column Widths
112
+
113
+ Column widths can be specified as:
114
+ - **Stretch weights** (numbers): Distributed proportionally, e.g., `{ name: 1, description: 3 }`
115
+ - **Pixel values** (strings): Fixed widths, e.g., `{ id: '80px', name: '200px' }`
116
+
117
+ ### DataTableControls
118
+
119
+ Controls component for search and pagination.
120
+
121
+ #### Props
122
+
123
+ | Prop | Type | Default | Description |
124
+ |------|------|---------|-------------|
125
+ | `search` | `string` | `''` | Current search query |
126
+ | `currentPage` | `number` | `1` | Current page number |
127
+ | `perPage` | `number` | `25` | Items per page |
128
+ | `totalItems` | `number` | `0` | Total number of items |
129
+ | `pagechange` | `function` | `() => {}` | Callback for page changes: `({currentPage}) => void` |
130
+ | `searchchange` | `function` | `() => {}` | Callback for search changes: `({search}) => void` |
131
+
132
+ ## Styling
133
+
134
+ The library uses Tailwind CSS and includes built-in styles for:
135
+ - Light and dark mode
136
+ - Alternating row colors
137
+ - Hover states
138
+ - Selected row highlighting
139
+ - Sticky headers
140
+
141
+ You can import the styles explicitly if needed:
142
+
143
+ ```js
144
+ import '@zhangt58/svelte-vtable/styles.css';
145
+ ```
146
+
147
+ ### CSS Custom Properties
148
+
149
+ Override these CSS variables to customize appearance:
150
+
151
+ ```css
152
+ :root {
153
+ --tbl-head-bg: #f8f9fa; /* Header background */
154
+ }
155
+ ```
156
+
157
+ ## TypeScript
158
+
159
+ The library is written in JavaScript with JSDoc annotations. Type checking is available via `svelte-check`.
160
+
161
+ ## License
162
+
163
+ MIT © [zhangt58](https://github.com/zhangt58)
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@zhangt58/svelte-vtable",
3
+ "version": "0.0.1",
4
+ "description": "A Svelte 5 library for virtualized data tables with sorting, selection, and pagination controls.",
5
+ "type": "module",
6
+ "svelte": "./src/lib/index.js",
7
+ "main": "./src/lib/index.js",
8
+ "module": "./src/lib/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "svelte": "./src/lib/index.js",
12
+ "import": "./src/lib/index.js",
13
+ "default": "./src/lib/index.js"
14
+ },
15
+ "./styles.css": "./src/lib/styles.css"
16
+ },
17
+ "scripts": {
18
+ "check": "svelte-check --tsconfig ./jsconfig.json",
19
+ "prepublishOnly": "npm run check"
20
+ },
21
+ "keywords": [
22
+ "svelte",
23
+ "svelte5",
24
+ "table",
25
+ "virtual",
26
+ "data-table",
27
+ "sortable",
28
+ "pagination",
29
+ "virtualized"
30
+ ],
31
+ "author": "zhangt58",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/zhangt58/svelte-vtable"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/zhangt58/svelte-vtable/issues"
39
+ },
40
+ "homepage": "https://github.com/zhangt58/svelte-vtable#readme",
41
+ "peerDependencies": {
42
+ "flowbite-svelte": "^1.0.0",
43
+ "flowbite-svelte-icons": "^3.0.0",
44
+ "svelte": "^5.0.0",
45
+ "svelte-virtuallists": "^1.0.0",
46
+ "tailwindcss": "^4.0.0"
47
+ },
48
+ "devDependencies": {
49
+ "svelte": "^5.0.0",
50
+ "svelte-check": "^4.3.4",
51
+ "typescript": "^5.0.0"
52
+ },
53
+ "files": [
54
+ "src",
55
+ "README.md",
56
+ "LICENSE"
57
+ ]
58
+ }
@@ -0,0 +1,302 @@
1
+ <script>
2
+ import { Pagination, Search, Badge } from 'flowbite-svelte';
3
+ import { ChevronLeftOutline, ChevronRightOutline } from 'flowbite-svelte-icons';
4
+ import { onMount, onDestroy } from 'svelte';
5
+
6
+ // Props for search, pagination (but no per-page control)
7
+ let {
8
+ search = '',
9
+ currentPage = 1,
10
+ perPage = 25, // Fixed value, not user-configurable
11
+ totalItems = 0,
12
+ pagechange = () => {},
13
+ searchchange = () => {}
14
+ } = $props();
15
+
16
+ // totalPages derived from totalItems and perPage
17
+ const totalPages = $derived(() => Math.max(1, Math.ceil(totalItems / perPage)));
18
+
19
+ // clamp currentPage into valid range whenever currentPage or totalPages change
20
+ $effect(() => {
21
+ currentPage = Math.min(Math.max(1, +currentPage || 1), totalPages());
22
+ });
23
+
24
+ function goTo(p) {
25
+ const np = Math.min(Math.max(1, Math.floor(p)), totalPages());
26
+ if (np !== currentPage) {
27
+ currentPage = np;
28
+ pagechange?.({ currentPage });
29
+ }
30
+ }
31
+
32
+ // emit search changes for parent when search updates
33
+ $effect(() => {
34
+ if (typeof search !== 'undefined') searchchange?.({ search });
35
+ });
36
+
37
+ // Calculate range for display
38
+ const startItem = $derived(() => totalItems === 0 ? 0 : (currentPage - 1) * perPage + 1);
39
+ const endItem = $derived(() => Math.min(currentPage * perPage, totalItems));
40
+
41
+ // visiblePages: number of middle numeric buttons to show (not counting first/last)
42
+ const visiblePages = 5;
43
+
44
+ // stable id to query the pagination DOM if needed (fallback)
45
+ const paginationId = `pagination-${Math.random().toString(36).slice(2,9)}`;
46
+
47
+ // pages array for Pagination component (condensed with ellipses)
48
+ const pages = $derived(() => {
49
+ const total = totalPages();
50
+ const current = Math.min(Math.max(1, Math.floor(currentPage)), total);
51
+
52
+ // If small number of pages, show all
53
+ if (total <= visiblePages + 2) {
54
+ return Array.from({ length: total }, (_, i) => ({ name: String(i + 1), active: i + 1 === current }));
55
+ }
56
+
57
+ const pagesArr = [];
58
+ // always show first
59
+ pagesArr.push({ name: '1', active: current === 1 });
60
+
61
+ const half = Math.floor(visiblePages / 2);
62
+ let start = Math.max(2, current - half);
63
+ let end = Math.min(total - 1, current + half);
64
+
65
+ // adjust window when near the boundaries
66
+ if (current - 1 <= half) {
67
+ start = 2;
68
+ end = 1 + visiblePages;
69
+ }
70
+ if (total - current <= half) {
71
+ end = total - 1;
72
+ start = total - visiblePages;
73
+ }
74
+
75
+ if (start > 2) {
76
+ // compute left jump (midpoint of hidden range 2..start-1)
77
+ const leftHiddenStart = 2;
78
+ const leftHiddenEnd = start - 1;
79
+ const leftJump = Math.max(leftHiddenStart, Math.floor((leftHiddenStart + leftHiddenEnd) / 2));
80
+ pagesArr.push({ name: '…', active: false, ellipsis: 'left', jump: leftJump });
81
+ }
82
+
83
+ for (let i = start; i <= end; i++) pagesArr.push({ name: String(i), active: i === current });
84
+
85
+ if (end < total - 1) {
86
+ // compute right jump (midpoint of hidden range end+1..total-1)
87
+ const rightHiddenStart = end + 1;
88
+ const rightHiddenEnd = total - 1;
89
+ const rightJump = Math.min(rightHiddenEnd, Math.ceil((rightHiddenStart + rightHiddenEnd) / 2));
90
+ pagesArr.push({ name: '…', active: false, ellipsis: 'right', jump: rightJump });
91
+ }
92
+
93
+ // always show last
94
+ pagesArr.push({ name: String(total), active: current === total });
95
+
96
+ return pagesArr;
97
+ });
98
+
99
+ // previous / next callbacks for Pagination
100
+ function previous() {
101
+ goTo(currentPage - 1);
102
+ }
103
+ function next() {
104
+ goTo(currentPage + 1);
105
+ }
106
+
107
+ // DOM reference to the pagination container for decorating ellipsis buttons
108
+ let paginationContainerEl = null;
109
+
110
+ function decorateEllipsis() {
111
+ if (!paginationContainerEl) return;
112
+ const pageList = pages();
113
+ // find the <ul> inside the pagination container
114
+ let ul = null;
115
+ if (paginationContainerEl && typeof paginationContainerEl.querySelector === 'function') {
116
+ ul = paginationContainerEl.querySelector('ul');
117
+ } else {
118
+ // fallback: query by data attribute on the wrapper
119
+ ul = document.querySelector(`[data-pagination-id="${paginationId}"] ul`);
120
+ }
121
+ if (!ul) return;
122
+ // Ensure the <ul> has Tailwind utility classes for layout
123
+ ul.classList.remove('flex','gap-0.5','p-0','m-0','list-none','items-center');
124
+ ul.classList.add('flex','gap-0.5','p-0','m-0','list-none','items-center');
125
+ const lis = Array.from(ul.children || []);
126
+ // Build a list of page-button <li>s (skip prev/next controls) by checking their textContent
127
+ const pageLis = [];
128
+ for (const li of lis) {
129
+ const btn = li.querySelector('button, a');
130
+ if (!btn) continue;
131
+ const text = (btn.textContent || '').trim();
132
+ // consider numeric pages and ellipsis as page buttons
133
+ if (/^\d+$/.test(text) || text === '…') pageLis.push({ li, btn, text });
134
+ }
135
+
136
+ // Now map pageLis to pageList entries in order
137
+ pageLis.forEach(({ li, btn, text }, idx) => {
138
+ const pageObj = pageList[idx];
139
+ if (!pageObj) return;
140
+ // clear previous decorations
141
+ btn.classList.remove('ellipsis-page');
142
+ btn.removeAttribute('data-jump');
143
+ btn.removeAttribute('data-ellipsis');
144
+ btn.removeAttribute('title');
145
+
146
+ // Apply Tailwind utility classes instead of inline styles
147
+ // Remove any previously-applied utility classes we manage
148
+ btn.classList.remove(
149
+ 'px-2','py-1','text-sm','border','border-gray-300','bg-transparent','min-w-[2rem]',
150
+ 'inline-flex','items-center','justify-center','transition-colors','hover:bg-gray-100',
151
+ 'bg-green-100','text-green-600','border-transparent','opacity-60','cursor-default','pointer-events-none',
152
+ 'tw-ellipsis'
153
+ );
154
+
155
+ // Base Tailwind classes for pagination buttons
156
+ btn.classList.add(
157
+ 'px-2','py-1','text-sm','border','border-gray-300','bg-transparent','min-w-[2rem]',
158
+ 'inline-flex','items-center','justify-center','transition-colors','hover:bg-gray-100'
159
+ );
160
+
161
+ // active page styling
162
+ if (pageObj.active) {
163
+ btn.classList.add('bg-green-100','text-green-600','border-transparent');
164
+ btn.setAttribute('aria-current', 'page');
165
+ } else {
166
+ btn.removeAttribute('aria-current');
167
+ btn.classList.remove('bg-green-100','text-green-600','border-transparent');
168
+ }
169
+
170
+ // disabled styling
171
+ if (btn.disabled || btn.getAttribute('aria-disabled') === 'true') {
172
+ btn.classList.add('opacity-60','cursor-default','pointer-events-none');
173
+ } else {
174
+ btn.classList.remove('opacity-60','cursor-default','pointer-events-none');
175
+ }
176
+
177
+ if (pageObj.name === '…' && typeof pageObj['jump'] === 'number') {
178
+ btn.setAttribute('data-jump', String(pageObj['jump']));
179
+ btn.setAttribute('data-ellipsis', 'true');
180
+ // restore native tooltip for compatibility (browser tooltip)
181
+ btn.setAttribute('title', `Jump to page ${pageObj['jump']}`);
182
+ // visually indicate ellipsis (smaller text) via Tailwind
183
+ btn.classList.add('text-sm','opacity-90');
184
+ }
185
+ });
186
+ }
187
+
188
+ // run decoration whenever pages or currentPage change
189
+ $effect(() => {
190
+ pages();
191
+ currentPage;
192
+ // schedule decoration after the browser has painted the updated DOM
193
+ requestAnimationFrame(() => requestAnimationFrame(() => decorateEllipsis()));
194
+ });
195
+
196
+ // Re-apply decorations whenever the pagination DOM mutates (childList changes)
197
+ let _observer = null;
198
+ onMount(() => {
199
+ if (!paginationContainerEl) return;
200
+ const run = () => requestAnimationFrame(() => requestAnimationFrame(() => decorateEllipsis()));
201
+ _observer = new MutationObserver(run);
202
+ const root = paginationContainerEl instanceof Element ? paginationContainerEl : document.querySelector(`[data-pagination-id="${paginationId}"]`);
203
+ if (root) _observer.observe(root, { childList: true, subtree: true, attributes: true });
204
+ // initial run
205
+ run();
206
+ });
207
+
208
+ onDestroy(() => {
209
+ _observer?.disconnect();
210
+ _observer = null;
211
+ });
212
+
213
+ // handle clicks inside Pagination to detect page button clicks
214
+ function handlePaginationClick(e) {
215
+ const el = e.target instanceof Element ? e.target.closest('button, a') : null;
216
+ if (!el) return;
217
+ // find the parent li index so we can map to pages()
218
+ const li = el.closest('li');
219
+ if (!li) return;
220
+ const ul = li.parentElement;
221
+ if (!ul) return;
222
+ const lis = Array.from(ul.children);
223
+ // Find prev/next by detecting non-numeric/non-ellipsis buttons
224
+ const pageList = pages();
225
+ // Build ordered list of page-button lis (numeric and ellipsis)
226
+ const pageLis = [];
227
+ for (const item of lis) {
228
+ const btn = item.querySelector('button, a');
229
+ if (!btn) continue;
230
+ const text = (btn.textContent || '').trim();
231
+ if (/^\d+$/.test(text) || text === '…') pageLis.push({ li: item, btn, text });
232
+ }
233
+
234
+ // If clicked on prev/next controls, detect by checking whether clicked li is not in pageLis
235
+ const clickedIsPage = pageLis.some(p => p.li === li);
236
+ if (!clickedIsPage) {
237
+ // determine if it was prev (first li) or next (last li)
238
+ const firstLi = lis[0];
239
+ const lastLi = lis[lis.length - 1];
240
+ if (li === firstLi) {
241
+ previous();
242
+ } else if (li === lastLi) {
243
+ next();
244
+ }
245
+ return;
246
+ }
247
+
248
+ // Map clicked li to page index
249
+ const pageIdx = pageLis.findIndex(p => p.li === li);
250
+ if (pageIdx < 0 || pageIdx >= pageList.length) return;
251
+ const pageObj = pageList[pageIdx];
252
+ if (!pageObj) return;
253
+ if (pageObj.name === '…' && typeof pageObj['jump'] === 'number') {
254
+ goTo(pageObj['jump']);
255
+ return;
256
+ }
257
+ const n = Number(pageObj.name);
258
+ if (!Number.isNaN(n)) goTo(n);
259
+ }
260
+
261
+ // No external tooltip component in use; we rely on native title attribute for ellipses
262
+ </script>
263
+
264
+ <div class="flex items-center w-full gap-3 px-0 py-0">
265
+ <!-- Search field on the left -->
266
+ <div class="flex-1">
267
+ <Search size="sm" bind:value={search} placeholder="Search..." clearable
268
+ clearableOnClick={() => { search = ''; searchchange?.({ search }); }} />
269
+ </div>
270
+
271
+ <!-- Range count badge -->
272
+ <div class="flex-2">
273
+ <Badge rounded color="gray">
274
+ Showing {startItem()} to {endItem()} of {totalItems}
275
+ </Badge>
276
+ </div>
277
+
278
+ <!-- Pagination navigation: use Pagination with chevrons and page buttons -->
279
+ <div bind:this={paginationContainerEl} data-pagination-id={paginationId} class="flex items-center gap-0.5" aria-label="Pagination">
280
+ <Pagination
281
+ pages={pages()}
282
+ {previous}
283
+ {next}
284
+ ariaLabel="Pagination"
285
+ onclick={handlePaginationClick}
286
+ >
287
+ {#snippet prevContent()}
288
+ <span class="sr-only">Previous</span>
289
+ <ChevronLeftOutline class="shrink-0 h-6 w-6" />
290
+ {/snippet}
291
+
292
+ {#snippet nextContent()}
293
+ <span class="sr-only">Next</span>
294
+ <ChevronRightOutline class="shrink-0 h-6 w-6" />
295
+ {/snippet}
296
+ </Pagination>
297
+ </div>
298
+ </div>
299
+
300
+ <style>
301
+ @import '../lib/styles.css';
302
+ </style>
@@ -0,0 +1,193 @@
1
+ <script>
2
+ import { VirtualList } from 'svelte-virtuallists';
3
+
4
+ // shared default no-op function (accepts any args) so prop types allow being called with a payload
5
+ const DEFAULT_NOOP = (..._args) => {};
6
+
7
+ // Default sort behavior: sort by the header string alphabetically, toggling asc/desc
8
+ function defaultSort(key) {
9
+ if (sortKey === key) {
10
+ sortDir = sortDir === 'asc' ? 'desc' : 'asc';
11
+ } else {
12
+ sortKey = key;
13
+ sortDir = 'asc';
14
+ }
15
+ }
16
+
17
+ // Runic props: accept props via $props() so the component matches the
18
+ // project's runes-style components. Include the `select` callback prop.
19
+ let {
20
+ items = [],
21
+ visibleKeys = [],
22
+ // treat sortKey/sortDir as normal props; parent may control them and
23
+ // provide a `sort` callback to update them.
24
+ sortKey = null,
25
+ sortDir = 'asc',
26
+ className = '',
27
+ style = '',
28
+ emptyMessage = 'No items to display.',
29
+ colWidths = {},
30
+ selected = null,
31
+ // external selection callback with a safe default no-op
32
+ selectCallback = DEFAULT_NOOP,
33
+ // new prop name: sortCallback defaulting to `defaultSort` (alphabetical string sort)
34
+ sortCallback = defaultSort,
35
+ // <slot> -> @render migration
36
+ rowSnippet
37
+ } = $props();
38
+
39
+ // expose selection via the callback prop (if provided)
40
+ function selectItem(item, index) {
41
+ selected = item;
42
+ try { callSelectCallback({ item, index }); } catch (err) { try { console.error('selectCallback threw:', err); } catch (e) {} }
43
+ }
44
+
45
+ // Wrapper that casts the possibly-typed callback to any before invoking so callers may pass a payload
46
+ function callSelectCallback(payload) {
47
+ try {
48
+ (/** @type {any} */ (selectCallback))(payload);
49
+ } catch (err) {
50
+ try { console.error('selectCallback threw:', err); } catch (e) {}
51
+ }
52
+ }
53
+
54
+ // When header is clicked update the exported sortKey/sortDir so parents
55
+ // using bind:sortKey / bind:sortDir receive updates (no event dispatching).
56
+ function handleSort(key) {
57
+ // Delegate sorting to the configured callback (by default `defaultSort` will run)
58
+ try { sortCallback(key); } catch (err) { try { console.error('sortCallback threw:', err); } catch (e) {} }
59
+ }
60
+
61
+ // Normalize colWidths: handle object or array input, treat numeric as stretch weights.
62
+ // NOTE: percentage strings (e.g. '30%') are no longer supported and will be ignored with a warning.
63
+ function normalizeColWidths() {
64
+ const map = {};
65
+
66
+ // Build an ordered list of entries for visibleKeys
67
+ const entries = visibleKeys.map((key, i) => {
68
+ let v;
69
+ if (Array.isArray(colWidths)) v = colWidths[i];
70
+ else if (colWidths && typeof colWidths === 'object') v = colWidths[key];
71
+ else v = undefined;
72
+ return { key, v };
73
+ });
74
+
75
+ // Collect numeric stretch weights and pass-through non-percent strings
76
+ const numeric = [];
77
+ const otherStrings = [];
78
+
79
+ for (const e of entries) {
80
+ const v = e.v;
81
+ if (typeof v === 'number' && !Number.isNaN(v)) {
82
+ numeric.push({ key: e.key, w: v });
83
+ } else if (typeof v === 'string') {
84
+ const s = v.trim();
85
+ if (s.endsWith('%')) {
86
+ // Percent strings are intentionally unsupported now - ignore silently
87
+ } else {
88
+ // keep other string units (e.g., '120px')
89
+ otherStrings.push({ key: e.key, v: s });
90
+ }
91
+ }
92
+ }
93
+
94
+ const totalWeight = numeric.reduce((s, r) => s + r.w, 0);
95
+ const availablePct = 100;
96
+
97
+ if (numeric.length > 0 && totalWeight > 0) {
98
+ let acc = 0;
99
+ numeric.forEach((n, idx) => {
100
+ const pct = idx === numeric.length - 1
101
+ ? Math.max(0, Math.round((availablePct - acc) * 100) / 100)
102
+ : Math.round((n.w / totalWeight) * availablePct * 100) / 100;
103
+ map[n.key] = `${pct}%`;
104
+ acc += pct;
105
+ });
106
+ }
107
+
108
+ // Copy through non-percent strings (e.g. '120px')
109
+ for (const o of otherStrings) {
110
+ map[o.key] = o.v;
111
+ }
112
+
113
+ return map;
114
+ }
115
+
116
+ // Compute column width by key (fallback to even distribution)
117
+ function calcColWidth(key, index) {
118
+ try {
119
+ const norm = normalizeColWidths();
120
+ if (norm && norm[key] !== undefined) return String(norm[key]);
121
+
122
+ // Fallbacks: accept string widths (e.g. '120px') passed directly by the user.
123
+ // Numeric values should be provided as stretch weights and will be handled
124
+ // by normalizeColWidths(); if we encounter numeric values here, warn and ignore them.
125
+ if (Array.isArray(colWidths) && colWidths[index] !== undefined) {
126
+ const v = colWidths[index];
127
+ if (typeof v === 'string') {
128
+ const s = v.trim();
129
+ if (!s.endsWith('%')) {
130
+ return v; // e.g. '120px'
131
+ }
132
+ // percent strings are ignored silently
133
+ }
134
+ }
135
+ if (typeof colWidths === 'object' && colWidths[key] !== undefined) {
136
+ const v = colWidths[key];
137
+ if (typeof v === 'string') {
138
+ const s = v.trim();
139
+ if (!s.endsWith('%')) {
140
+ return v; // e.g. '120px'
141
+ }
142
+ // percent strings are ignored silently
143
+ }
144
+ }
145
+ } catch (err) {
146
+ // ignore and fall through to defaults
147
+ }
148
+ const n = Math.max(1, visibleKeys.length);
149
+ const pct = Math.floor(100 / n);
150
+ return pct + '%';
151
+ }
152
+
153
+ </script>
154
+
155
+ <section class="virtual-data-table {className}" style={style}>
156
+ {#if items && items.length > 0}
157
+ <VirtualList items={items} isTable class="datatable-table max-w-full max-h-full overflow-auto">
158
+ <!-- colgroup enforces the column widths so table-layout: fixed distributes as intended -->
159
+ {#snippet header()}
160
+ <colgroup>
161
+ {#each visibleKeys as key, i}
162
+ <col style="width: {calcColWidth(key, i)}" />
163
+ {/each}
164
+ </colgroup>
165
+ <thead class="sticky-header">
166
+ <tr>
167
+ {#each visibleKeys as key, i}
168
+ <th style="width: {calcColWidth(key, i)}" class="cursor-pointer select-none" onclick={() => handleSort(key)}
169
+ aria-sort={sortKey === key ? (sortDir === 'asc' ? 'ascending' : 'descending') : 'none'}>
170
+ <div class="inline-flex items-center gap-1">
171
+ <span>{key}</span>
172
+ {#if sortKey === key}
173
+ <span aria-hidden="true">{sortDir === 'asc' ? '▲' : '▼'}</span>
174
+ {/if}
175
+ </div>
176
+ </th>
177
+ {/each}
178
+ </tr>
179
+ </thead>
180
+ {/snippet}
181
+
182
+ {#snippet vl_slot({ index, item })}
183
+ {@render rowSnippet({item, index, select: () => selectItem(item, index), selected})}
184
+ {/snippet}
185
+ </VirtualList>
186
+ {:else}
187
+ <div class="p-4 text-center text-slate-500">{emptyMessage}</div>
188
+ {/if}
189
+ </section>
190
+
191
+ <style>
192
+ @import '../lib/styles.css';
193
+ </style>
@@ -0,0 +1,3 @@
1
+ export { default as VirtualDataTable } from '../components/VirtualDataTable.svelte';
2
+ export { default as DataTableControls } from '../components/DataTableControls.svelte';
3
+
@@ -0,0 +1,270 @@
1
+ .virtual-data-table {
2
+ display: block;
3
+ min-width: 0;
4
+ height: 100%;
5
+ overflow: auto;
6
+ }
7
+
8
+ :global(.datatable-table) {
9
+ display: table;
10
+ width: 100%;
11
+ min-width: 0;
12
+ border-collapse: collapse;
13
+ box-sizing: border-box;
14
+ font-size: 0.875rem; /* 14px - smaller, more compact */
15
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
16
+ line-height: 1.4;
17
+ border: none;
18
+ }
19
+
20
+ /* Sticky header support */
21
+ :global(.datatable-table) thead.sticky-header {
22
+ position: sticky;
23
+ top: 0;
24
+ z-index: 20;
25
+ }
26
+
27
+ /* Header visual styles - only bottom border */
28
+ :global(.datatable-table) thead th {
29
+ background-color: var(--tbl-head-bg, #f8f9fa);
30
+ font-size: 0.8125rem; /* 13px */
31
+ font-weight: 600;
32
+ text-transform: uppercase;
33
+ letter-spacing: 0.025em;
34
+ border-top: none;
35
+ border-left: none;
36
+ border-right: none;
37
+ border-bottom: 2px solid #dee2e6;
38
+ padding: 0.5rem 0.75rem;
39
+ text-align: left;
40
+ white-space: normal; /* Allow header text to wrap */
41
+ overflow: visible;
42
+ box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1); /* Keep border visible on scroll */
43
+ }
44
+
45
+ /* Row striping - alternating colors */
46
+ /* VirtualList may wrap rows, so we target tr directly */
47
+ :global(.datatable-table tbody tr:nth-of-type(even)) {
48
+ background-color: #ffffff;
49
+ }
50
+
51
+ :global(.datatable-table tbody tr:nth-of-type(odd)) {
52
+ background-color: #f8f9fa;
53
+ }
54
+
55
+ /* Also ensure tr elements themselves have background */
56
+ :global(.datatable-table tbody tr) {
57
+ background-color: inherit;
58
+ }
59
+
60
+ /* Hover effect */
61
+ :global(.datatable-table tbody tr:hover) {
62
+ background-color: #e7f1ff !important;
63
+ transition: background-color 0.15s ease-in-out;
64
+ }
65
+
66
+ /* Selesky-500 row overrides striping and hover */
67
+ :global(.datatable-table tbody tr.selected-row) {
68
+ background-color: #e0f2fe !important; /* light sky background */
69
+ box-shadow: inset 4px 0 0 0 #0369a1; /* left accent */
70
+ }
71
+
72
+ :global(.dark) :global(.datatable-table tbody tr.selected-row) {
73
+ /* brighter, higher-contrast selection in dark mode */
74
+ background-color: rgba(14,165,233,0.22) !important; /* stronger visible blue */
75
+ box-shadow: inset 6px 0 0 0 rgba(56,189,248,0.85); /* stronger left accent */
76
+ transition: background-color 0.12s ease-in-out, box-shadow 0.12s ease-in-out;
77
+ }
78
+
79
+ /* Also apply to cells to defeat any cell-level background from striping and ensure readable text */
80
+ :global(.datatable-table tbody tr.selected-row) td {
81
+ background-color: #e0f2fe !important;
82
+ }
83
+
84
+ :global(.dark) :global(.datatable-table tbody tr.selected-row) td {
85
+ background-color: rgba(14,165,233,0.22) !important;
86
+ color: #f0fbff !important; /* ensure high-contrast, very light text */
87
+ border-bottom-color: rgba(255,255,255,0.06);
88
+ }
89
+
90
+ /* Body cell defaults - only bottom border */
91
+ :global(.datatable-table tbody td) {
92
+ padding: 0.5rem 0.75rem;
93
+ border-top: none;
94
+ border-left: none;
95
+ border-right: none;
96
+ border-bottom: 1px solid #e9ecef;
97
+ vertical-align: middle;
98
+ text-align: left;
99
+ font-size: 0.875rem; /* 14px */
100
+ overflow: hidden;
101
+ white-space: normal; /* Allow wrapping by default */
102
+ word-wrap: break-word;
103
+ box-sizing: border-box;
104
+ }
105
+
106
+ /* No-wrap variant for cells that should truncate */
107
+ :global(.datatable-table tbody td.nowrap) {
108
+ white-space: nowrap;
109
+ text-overflow: ellipsis;
110
+ }
111
+
112
+ /* Compact variant */
113
+ :global(.datatable-table.compact tbody td) {
114
+ padding: 0.1rem 0.3rem;
115
+ }
116
+
117
+ /* Header content alignment helper */
118
+ :global(.datatable-table thead th > div) {
119
+ display: inline-flex;
120
+ align-items: center;
121
+ gap: 0.25rem;
122
+ }
123
+
124
+ /* Allow certain long cells to wrap fully if explicitly requested */
125
+ :global(.datatable-table td.wrap) {
126
+ white-space: normal;
127
+ word-break: break-word;
128
+ }
129
+
130
+ /* Dark mode variants for the datatable */
131
+ :global(.dark) :global(.datatable-table thead th) {
132
+ background-color: #1f2937;
133
+ border-bottom-color: #374151;
134
+ color: #f9fafb;
135
+ box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.3); /* Darker shadow for dark mode */
136
+ }
137
+
138
+ :global(.dark) :global(.datatable-table tbody tr:nth-of-type(even)) {
139
+ background-color: #111827;
140
+ }
141
+
142
+ :global(.dark) :global(.datatable-table tbody tr:nth-of-type(odd)) {
143
+ background-color: #1f2937;
144
+ }
145
+
146
+ :global(.dark) :global(.datatable-table tbody tr:hover) {
147
+ background-color: #374151 !important;
148
+ }
149
+
150
+ :global(.dark) :global(.datatable-table tbody td) {
151
+ border-bottom-color: #374151;
152
+ color: #e5e7eb;
153
+ }
154
+
155
+ /* Shared control styles (inputs, pagination, column filters) used by page components */
156
+ :global(.datatable-input) {
157
+ padding: 0.375rem 0.75rem;
158
+ font-size: 0.95rem;
159
+ border: 1px solid #ced4da;
160
+ border-radius: 0.25rem;
161
+ }
162
+
163
+ :global(.datatable-input:focus) {
164
+ border-color: #86b7fe;
165
+ outline: 0;
166
+ box-shadow: 0 0 0.1rem 0.2rem rgba(13, 110, 253, 0.25);
167
+ }
168
+
169
+ :global(.search-filtering-row) {
170
+ background-color: #f8f9fa;
171
+ }
172
+
173
+ :global(.search-filtering-row th) {
174
+ padding: 0.1rem 0.1rem;
175
+ border-bottom: 1px solid #dee2e6;
176
+ }
177
+
178
+ :global(.column-filter) {
179
+ width: 95%;
180
+ padding: 0.2rem 0.25rem;
181
+ font-size: 0.8rem;
182
+ border: 1px solid #ced4da;
183
+ border-radius: 0.25rem;
184
+ }
185
+
186
+ :global(.column-filter::placeholder) {
187
+ color: #adb5bd;
188
+ font-size: 0.75rem;
189
+ font-style: italic;
190
+ }
191
+
192
+ :global(.datatable-pagination) {
193
+ display: flex;
194
+ gap: 0.1rem;
195
+ margin-top: 0.6rem;
196
+ }
197
+
198
+ :global(.datatable-pagination li a),
199
+ :global(.datatable-pagination li button) {
200
+ padding: 0.3rem 0.7rem;
201
+ border: 1px solid #dee2e6;
202
+ border-radius: 0;
203
+ background-color: #fff;
204
+ color: #0d6efd;
205
+ text-decoration: none;
206
+ }
207
+
208
+ :global(.datatable-pagination li a:hover),
209
+ :global(.datatable-pagination li button:hover) {
210
+ background-color: #e9ecef;
211
+ }
212
+
213
+ :global(.datatable-pagination .datatable-active a),
214
+ :global(.datatable-pagination .datatable-active button) {
215
+ background-color: #0d6efd;
216
+ border-color: #0d6efd;
217
+ color: #fff;
218
+ }
219
+
220
+ /* Force the active/current page to use the green tokens (override flowbite's primary/orange).
221
+ Intentionally specific to reliably win over third-party rules. */
222
+ :global([data-pagination-id] ul li [aria-current="page"]) {
223
+ background-color: #dcfce7 !important; /* bg-green-100 */
224
+ color: #16a34a !important; /* text-green-600 */
225
+ border-color: transparent !important;
226
+ }
227
+
228
+ /* Ensure Prev/Next controls visually match the numeric buttons' border and rhythm
229
+ (keeps border, radius and min-width consistent). This is minimal and won't
230
+ override hover/text colors managed by Tailwind classes applied at runtime. */
231
+ :global([data-pagination-id] ul li:first-child > button),
232
+ :global([data-pagination-id] ul li:first-child > a),
233
+ :global([data-pagination-id] ul li:last-child > button),
234
+ :global([data-pagination-id] ul li:last-child > a) {
235
+ border: 1px solid #d1d5db; /* border-gray-300 */
236
+ min-width: 2rem; /* align with numeric buttons' min width */
237
+ background: transparent;
238
+ padding: 0.25rem 0.5rem; /* keep comfortable hit area */
239
+ }
240
+
241
+ /* Light mode: hover/focus for Prev/Next match numeric button hover */
242
+ :global([data-pagination-id] ul li:first-child > button:hover),
243
+ :global([data-pagination-id] ul li:first-child > a:hover),
244
+ :global([data-pagination-id] ul li:last-child > button:hover),
245
+ :global([data-pagination-id] ul li:last-child > a:hover),
246
+ :global([data-pagination-id] ul li:first-child > button:focus),
247
+ :global([data-pagination-id] ul li:first-child > a:focus),
248
+ :global([data-pagination-id] ul li:last-child > button:focus),
249
+ :global([data-pagination-id] ul li:last-child > a:focus) {
250
+ background-color: #f3f4f6; /* tailwind gray-100 */
251
+ outline: none;
252
+ }
253
+
254
+ /* Ellipsis styling: make clickable and visually lighter (JS sets data-ellipsis/data-jump) */
255
+ :global([data-pagination-id] ul li [data-ellipsis="true"]) {
256
+ cursor: pointer;
257
+ background: transparent !important;
258
+ color: inherit;
259
+ opacity: 0.9;
260
+ font-size: 0.875rem;
261
+ padding: 0.25rem 0.5rem;
262
+ }
263
+
264
+ /* Chevron sizing for Prev/Next so icons sit comfortably in the buttons */
265
+ :global([data-pagination-id] ul li:first-child svg),
266
+ :global([data-pagination-id] ul li:last-child svg) {
267
+ height: 1.25rem;
268
+ width: 1.25rem;
269
+ display: block;
270
+ }