@zhangt58/svelte-vtable 0.0.4 → 0.1.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
@@ -1,16 +1,17 @@
1
1
  # @zhangt58/svelte-vtable
2
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.
3
+ A Svelte 5 library providing virtualized data tables with sorting, selection, search, filtering, and pagination controls. Built with Svelte 5 runes for reactive state management.
4
4
 
5
5
  ## Features
6
6
 
7
7
  - 🚀 **Virtualized rendering** - Efficiently handles large datasets
8
8
  - 🔄 **Sorting** - Click column headers to sort
9
9
  - 🔍 **Search** - Built-in search filtering
10
+ - 🎯 **Multi-select filters** - Column-based filtering with OR/AND logic
10
11
  - 📄 **Pagination** - Configurable page controls with ellipsis navigation
11
12
  - ✅ **Selection** - Row selection with callback support
12
13
  - 🎨 **Styling** - Tailwind CSS based with light/dark mode support
13
- - 📱 **Responsive** - Flexible column widths with stretch weights
14
+ - 📱 **Responsive** - Flexible column widths and layouts
14
15
 
15
16
  ## Installation
16
17
 
@@ -30,11 +31,11 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
30
31
 
31
32
  ```svelte
32
33
  <script>
33
- import { VirtualDataTable, DataTableControls } from '@zhangt58/svelte-vtable';
34
+ import { VirtualDataTable, DataTableControls, DataTableFilters } from '@zhangt58/svelte-vtable';
34
35
 
35
36
  let items = $state([
36
- { id: 1, name: 'Alice', email: 'alice@example.com' },
37
- { id: 2, name: 'Bob', email: 'bob@example.com' },
37
+ { id: 1, name: 'Alice', email: 'alice@example.com', dept: 'Engineering' },
38
+ { id: 2, name: 'Bob', email: 'bob@example.com', dept: 'Sales' },
38
39
  // ... more items
39
40
  ]);
40
41
 
@@ -46,10 +47,24 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
46
47
  sortDir: 'asc'
47
48
  });
48
49
 
49
- const visibleKeys = ['name', 'email'];
50
- const colWidths = { name: 1, email: 2 }; // stretch weights
50
+ const visibleKeys = ['name', 'email', 'dept'];
51
+ const colWidths = { name: 1, email: 2, dept: 1 }; // stretch weights
52
+
53
+ // For filtering
54
+ let activeFilters = $state({});
55
+ const columnFilters = [
56
+ { key: 'dept', label: 'Department', uniqueValues: ['Engineering', 'Sales'] }
57
+ ];
51
58
  </script>
52
59
 
60
+ <!-- Multi-select filters -->
61
+ <DataTableFilters
62
+ {columnFilters}
63
+ {activeFilters}
64
+ filterChange={({allFilters}) => activeFilters = allFilters}
65
+ />
66
+
67
+ <!-- Search and pagination controls -->
53
68
  <DataTableControls
54
69
  search={ui.searchQuery}
55
70
  currentPage={ui.currentPage}
@@ -59,6 +74,7 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
59
74
  searchchange={(e) => ui.searchQuery = e.search}
60
75
  />
61
76
 
77
+ <!-- Virtualized table -->
62
78
  <VirtualDataTable
63
79
  {items}
64
80
  {visibleKeys}
@@ -72,6 +88,7 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
72
88
  <tr onclick={select}>
73
89
  <td>{item.name}</td>
74
90
  <td>{item.email}</td>
91
+ <td>{item.dept}</td>
75
92
  </tr>
76
93
  {/snippet}
77
94
  </VirtualDataTable>
@@ -108,12 +125,63 @@ The `rowSnippet` receives an object with:
108
125
  - `select` - Function to call to select this row
109
126
  - `selected` - Currently selected item (for comparison)
110
127
 
128
+ ### Filter example (filterCallback)
129
+
130
+ Below is a minimal example showing how to wire the `filterCallback` prop on `VirtualDataTable` to apply per-column inline filters emitted by the header inputs. The idea: keep a small `filters` map in your component, compute a derived `filteredItems` list, and update `filters` when the table emits a column filter change.
131
+
132
+ ```svelte
133
+ <script>
134
+ import { VirtualDataTable } from '@zhangt58/svelte-vtable';
135
+
136
+ // raw dataset you want to display/filter
137
+ const rawItems = [
138
+ { id: 1, name: 'Alice', email: 'alice@example.com' },
139
+ { id: 2, name: 'Bob', email: 'bob@example.com' },
140
+ { id: 3, name: 'Carol', email: 'carol@example.com' }
141
+ ];
142
+
143
+ // per-column filter values
144
+ let filters = {};
145
+
146
+ // derived, reactive filtered list
147
+ $: filteredItems = rawItems.filter(item =>
148
+ Object.entries(filters).every(([k, v]) => !v || String(item[k] ?? '').toLowerCase().includes(v.toLowerCase()))
149
+ );
150
+
151
+ // called when a ColumnHeader emits a filter event: { key, value }
152
+ function handleFilter({ key, value }) {
153
+ filters = { ...filters, [key]: value };
154
+ }
155
+ </script>
156
+
157
+ <VirtualDataTable
158
+ items={filteredItems}
159
+ visibleKeys={['name', 'email']}
160
+ filterCallback={handleFilter}
161
+ >
162
+ {#snippet rowSnippet({item, index, select, selected})}
163
+ <tr onclick={select}>
164
+ <td>{item.name}</td>
165
+ <td>{item.email}</td>
166
+ </tr>
167
+ {/snippet}
168
+ </VirtualDataTable>
169
+ ```
170
+
111
171
  #### Column Widths
112
172
 
113
173
  Column widths can be specified as:
114
174
  - **Stretch weights** (numbers): Distributed proportionally, e.g., `{ name: 1, description: 3 }`
115
175
  - **Pixel values** (strings): Fixed widths, e.g., `{ id: '80px', name: '200px' }`
116
176
 
177
+ #### Row Snippet Parameters
178
+
179
+ The `rowSnippet` receives an object with:
180
+ - `item` - The current row data
181
+ - `index` - Row index in the current page
182
+ - `select` - Function to call to select this row
183
+ - `selected` - Currently selected item (for comparison)
184
+
117
185
  ### DataTableControls
118
186
 
119
187
  Controls component for search and pagination.
@@ -129,6 +197,90 @@ Controls component for search and pagination.
129
197
  | `pagechange` | `function` | `() => {}` | Callback for page changes: `({currentPage}) => void` |
130
198
  | `searchchange` | `function` | `() => {}` | Callback for search changes: `({search}) => void` |
131
199
 
200
+ ### DataTableFilters
201
+
202
+ Multi-select filter component with flexible layout options. Implements OR logic within columns and AND logic across columns.
203
+
204
+ #### Props
205
+
206
+ | Prop | Type | Default | Description |
207
+ |------|------|---------|-------------|
208
+ | `columnFilters` | `Array` | `[]` | Array of filter configurations (see below) |
209
+ | `direction` | `'horizontal' \| 'vertical'` | `'horizontal'` | Layout direction for filter grid |
210
+ | `activeFilters` | `Object` | `{}` | Current active filters `{ columnKey: [selectedValues] }` |
211
+ | `filterChange` | `function` | `() => {}` | Callback when filters change |
212
+ | `className` | `string` | `''` | Additional CSS classes |
213
+ | `showCounts` | `boolean` | `true` | Whether to show value counts |
214
+
215
+ #### columnFilters Structure
216
+
217
+ Each item in `columnFilters` should have:
218
+ ```javascript
219
+ {
220
+ key: 'columnKey', // Column identifier
221
+ label: 'Column Label', // Display label
222
+ uniqueValues: [...], // Array of unique values
223
+ counts: { value: count } // Optional: value frequency map
224
+ }
225
+ ```
226
+
227
+ #### Filter Logic
228
+
229
+ - **OR within column**: Selecting multiple values in one filter matches rows with ANY of those values
230
+ - **AND across columns**: All active column filters must match for a row to pass
231
+
232
+ Example usage with data filtering:
233
+ ```svelte
234
+ <script>
235
+ import { DataTableFilters } from '@zhangt58/svelte-vtable';
236
+
237
+ const data = [
238
+ { name: 'Alice', dept: 'Engineering', status: 'Active' },
239
+ { name: 'Bob', dept: 'Sales', status: 'Active' },
240
+ // ...
241
+ ];
242
+
243
+ let activeFilters = $state({});
244
+
245
+ const columnFilters = [
246
+ {
247
+ key: 'dept',
248
+ label: 'Department',
249
+ uniqueValues: ['Engineering', 'Sales'],
250
+ counts: { 'Engineering': 5, 'Sales': 3 }
251
+ },
252
+ {
253
+ key: 'status',
254
+ label: 'Status',
255
+ uniqueValues: ['Active', 'Inactive'],
256
+ counts: { 'Active': 7, 'Inactive': 1 }
257
+ }
258
+ ];
259
+
260
+ // Apply filters
261
+ const filteredData = $derived(() => {
262
+ return data.filter(item => {
263
+ for (const [key, values] of Object.entries(activeFilters)) {
264
+ if (values?.length > 0 && !values.includes(item[key])) {
265
+ return false; // AND logic across columns
266
+ }
267
+ }
268
+ return true;
269
+ });
270
+ });
271
+ </script>
272
+
273
+ <DataTableFilters
274
+ {columnFilters}
275
+ {activeFilters}
276
+ filterChange={({allFilters}) => activeFilters = allFilters}
277
+ direction="horizontal"
278
+ showCounts={true}
279
+ />
280
+ ```
281
+
282
+ For complete examples, see [DATATABLEFILTERS_README.md](./DATATABLEFILTERS_README.md).
283
+
132
284
  ## Styling (important)
133
285
 
134
286
  This library ships with built-in CSS to provide sensible default visuals (light/dark mode, striping, hover, selection, sticky headers, and pagination control styling). There are two important details to understand so the styles work correctly for both local development and package consumers:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhangt58/svelte-vtable",
3
- "version": "0.0.4",
3
+ "version": "0.1.0",
4
4
  "description": "A Svelte 5 library for virtualized data tables with sorting, selection, and pagination controls.",
5
5
  "type": "module",
6
6
  "svelte": "./src/lib/index.js",
@@ -41,15 +41,20 @@
41
41
  },
42
42
  "homepage": "https://github.com/zhangt58/svelte-vtable#readme",
43
43
  "peerDependencies": {
44
- "flowbite-svelte": "^1.0.0",
45
- "svelte": "^5.0.0",
46
- "svelte-virtuallists": "^1.0.0",
47
- "tailwindcss": "^4.0.0"
44
+ "flowbite-svelte": "^1.28.1",
45
+ "flowbite-svelte-icons": "^3.0.0",
46
+ "svelte": "^5.43.5",
47
+ "svelte-virtuallists": "^1.4.2",
48
+ "tailwindcss": "^4.1.17"
48
49
  },
49
50
  "devDependencies": {
51
+ "@sveltejs/vite-plugin-svelte": "^6.2.1",
52
+ "flowbite-svelte": "^1.28.1",
53
+ "flowbite-svelte-icons": "^3.0.0",
50
54
  "svelte": "^5.0.0",
51
55
  "svelte-check": "^4.3.4",
52
- "typescript": "^5.0.0"
56
+ "svelte-virtuallists": "^1.4.2",
57
+ "vite": "^7.2.2"
53
58
  },
54
59
  "files": [
55
60
  "src",
@@ -1,5 +1,7 @@
1
1
  <script>
2
2
  import { Pagination, Search, Badge } from 'flowbite-svelte';
3
+ import { FilterOutline } from 'flowbite-svelte-icons';
4
+ import FiltersModal from './FiltersModal.svelte';
3
5
  // Inline SVGs are used instead of importing icons to avoid the dependency on flowbite-svelte-icons
4
6
  import { onMount, onDestroy } from 'svelte';
5
7
 
@@ -10,9 +12,30 @@
10
12
  perPage = 25, // Fixed value, not user-configurable
11
13
  totalItems = 0,
12
14
  pagechange = () => {},
13
- searchchange = () => {}
15
+ searchchange = () => {},
16
+ // control visibility of DataTableFilters above the controls
17
+ filtersVisible = true,
18
+ // callback when toggle changes: filterstoggle({ filtersVisible })
19
+ filterstoggle = () => {},
20
+ // optional DataTableFilters inputs - when provided, this component will render the filters
21
+ columnFilters = [],
22
+ activeFilters = {},
23
+ /** @type {(..._args: any[]) => void} */
24
+ filterChange = (..._args) => {},
25
+ direction = 'horizontal',
26
+ showCounts = true,
27
+ className = ''
14
28
  } = $props();
15
29
 
30
+ // count of active filters (sum of selected values per column)
31
+ const activeFilterCount = $derived(() => {
32
+ try {
33
+ return Object.values(activeFilters || {}).reduce((sum, v) => sum + (Array.isArray(v) ? v.length : 0), 0);
34
+ } catch (e) {
35
+ return 0;
36
+ }
37
+ });
38
+
16
39
  // totalPages derived from totalItems and perPage
17
40
  const totalPages = $derived(() => Math.max(1, Math.ceil(totalItems / perPage)));
18
41
 
@@ -34,6 +57,20 @@
34
57
  if (typeof search !== 'undefined') searchchange?.({ search });
35
58
  });
36
59
 
60
+ // call filterstoggle when filtersVisible changes (avoid on:change typing issues)
61
+ let _prevFiltersVisible = undefined;
62
+ $effect(() => {
63
+ // initialize previous value on first run without emitting
64
+ if (_prevFiltersVisible === undefined) {
65
+ _prevFiltersVisible = filtersVisible;
66
+ return;
67
+ }
68
+ if (filtersVisible !== _prevFiltersVisible) {
69
+ try { filterstoggle?.({ filtersVisible }); } catch (err) {}
70
+ _prevFiltersVisible = filtersVisible;
71
+ }
72
+ });
73
+
37
74
  // Calculate range for display
38
75
  const startItem = $derived(() => totalItems === 0 ? 0 : (currentPage - 1) * perPage + 1);
39
76
  const endItem = $derived(() => Math.min(currentPage * perPage, totalItems));
@@ -135,7 +172,7 @@
135
172
 
136
173
  // Now map pageLis to pageList entries in order
137
174
  pageLis.forEach((p, idx) => {
138
- const { li, btn, text } = p;
175
+ const btn = p.btn;
139
176
  const pageObj = pageList[idx];
140
177
  if (!pageObj) return;
141
178
  // clear previous decorations
@@ -262,48 +299,87 @@
262
299
  // No external tooltip component in use; we rely on native title attribute for ellipses
263
300
  </script>
264
301
 
265
- <div class="flex items-center w-full gap-3 px-0 py-0">
266
- <!-- Search field on the left -->
267
- <div class="flex-1">
268
- <Search size="sm" bind:value={search} placeholder="Search..." clearable
269
- clearableOnClick={() => { search = ''; searchchange?.({ search }); }} />
270
- </div>
271
-
272
- <!-- Range count badge -->
273
- <div class="flex-2">
274
- <Badge rounded color="gray">
275
- Showing {startItem()} to {endItem()} of {totalItems}
276
- </Badge>
277
- </div>
278
-
279
- <!-- Pagination navigation: use Pagination with chevrons and page buttons -->
280
- <div bind:this={paginationContainerEl} data-pagination-id={paginationId} class="flex items-center gap-0.5" aria-label="Pagination">
281
- <Pagination
282
- pages={pages()}
283
- {previous}
284
- {next}
285
- ariaLabel="Pagination"
286
- onclick={handlePaginationClick}
287
- >
288
- {#snippet prevContent()}
289
- <span class="sr-only">Previous</span>
290
- <!-- Left chevron SVG (replaces ChevronLeftOutline) -->
291
- <svg class="shrink-0 h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
292
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M15 19l-7-7 7-7" />
293
- </svg>
294
- {/snippet}
295
-
296
- {#snippet nextContent()}
297
- <span class="sr-only">Next</span>
298
- <!-- Right chevron SVG (replaces ChevronRightOutline) -->
299
- <svg class="shrink-0 h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
300
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 5l7 7-7 7" />
301
- </svg>
302
- {/snippet}
303
- </Pagination>
302
+ <div class="w-full">
303
+ <div class="flex items-center w-full gap-3 px-0 py-0">
304
+ <!-- Search field on the left -->
305
+ <div class="flex-1">
306
+ <div class="flex items-center gap-2">
307
+ <!-- Styled button to open/close filters modal -->
308
+ <div class="flex items-center gap-1 relative">
309
+ <button
310
+ type="button"
311
+ class={
312
+ "inline-flex items-center gap-2 px-3 py-1 text-sm rounded-md border transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-green-500 dark:focus-visible:ring-green-400 " +
313
+ (filtersVisible
314
+ ? 'bg-slate-100 dark:bg-slate-700 border-slate-300 dark:border-slate-600 text-slate-900 dark:text-slate-100'
315
+ : 'bg-transparent border-transparent text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700')
316
+ }
317
+ aria-pressed={filtersVisible}
318
+ aria-label="Toggle filters"
319
+ title="Filters"
320
+ onclick={() => { filtersVisible = !filtersVisible; }}
321
+ >
322
+ <!-- Funnel icon (Flowbite icon component) -->
323
+ <FilterOutline class="h-4 w-4 shrink-0" />
324
+ <span class="text-sm">Filters</span>
325
+ </button>
326
+
327
+ {#if activeFilterCount() > 0}
328
+ <!-- positioned badge -->
329
+ <span class="absolute top-0 right-0 -translate-y-1/2 translate-x-1/2 inline-flex items-center justify-center h-5 min-w-[1.25rem] px-1.5 rounded-full bg-green-600 text-white text-xs font-medium">{activeFilterCount()}</span>
330
+ {/if}
331
+ </div>
332
+
333
+ <Search size="sm" bind:value={search} placeholder="Search..." clearable
334
+ clearableOnClick={() => { search = ''; searchchange?.({ search }); }} />
335
+ </div>
336
+ </div>
337
+
338
+ <!-- Range count badge -->
339
+ <div class="flex-2">
340
+ <Badge rounded color="gray">
341
+ Showing {startItem()} to {endItem()} of {totalItems}
342
+ </Badge>
343
+ </div>
344
+
345
+ <!-- Pagination navigation: use Pagination with chevrons and page buttons -->
346
+ <div bind:this={paginationContainerEl} data-pagination-id={paginationId} class="flex items-center gap-0.5" aria-label="Pagination">
347
+ <Pagination
348
+ pages={pages()}
349
+ {previous}
350
+ {next}
351
+ ariaLabel="Pagination"
352
+ onclick={handlePaginationClick}
353
+ >
354
+ {#snippet prevContent()}
355
+ <span class="sr-only">Previous</span>
356
+ <!-- Left chevron SVG (replaces ChevronLeftOutline) -->
357
+ <svg class="shrink-0 h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
358
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M15 19l-7-7 7-7" />
359
+ </svg>
360
+ {/snippet}
361
+
362
+ {#snippet nextContent()}
363
+ <span class="sr-only">Next</span>
364
+ <!-- Right chevron SVG (replaces ChevronRightOutline) -->
365
+ <svg class="shrink-0 h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
366
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 5l7 7-7 7" />
367
+ </svg>
368
+ {/snippet}
369
+ </Pagination>
370
+ </div>
304
371
  </div>
305
372
  </div>
306
373
 
374
+ <FiltersModal bind:open={filtersVisible}
375
+ columnFilters={columnFilters}
376
+ activeFilters={activeFilters}
377
+ filterChange={(...args) => { try { return filterChange(...args); } catch (e) {} }}
378
+ direction={direction}
379
+ showCounts={showCounts}
380
+ className={className}
381
+ />
382
+
307
383
  <style>
308
- @import '../lib/dist/styles.css';
309
- </style>
384
+ @import '../lib/dist/styles.css';
385
+ </style>