@zhangt58/svelte-vtable 0.1.1 → 0.1.2

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
@@ -44,24 +44,24 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
44
44
  currentPage: 1,
45
45
  perPage: 25,
46
46
  sortKey: null,
47
- sortDir: 'asc'
47
+ sortDir: 'asc',
48
48
  });
49
49
 
50
50
  const visibleKeys = ['name', 'email', 'dept'];
51
51
  const colWidths = { name: 1, email: 2, dept: 1 }; // stretch weights
52
-
52
+
53
53
  // For filtering
54
54
  let activeFilters = $state({});
55
55
  const columnFilters = [
56
- { key: 'dept', label: 'Department', uniqueValues: ['Engineering', 'Sales'] }
56
+ { key: 'dept', label: 'Department', uniqueValues: ['Engineering', 'Sales'] },
57
57
  ];
58
58
  </script>
59
59
 
60
60
  <!-- Multi-select filters -->
61
- <DataTableFilters
62
- {columnFilters}
61
+ <DataTableFilters
62
+ {columnFilters}
63
63
  {activeFilters}
64
- filterChange={({allFilters}) => activeFilters = allFilters}
64
+ filterChange={({ allFilters }) => (activeFilters = allFilters)}
65
65
  />
66
66
 
67
67
  <!-- Search and pagination controls -->
@@ -70,8 +70,8 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
70
70
  currentPage={ui.currentPage}
71
71
  perPage={ui.perPage}
72
72
  totalItems={items.length}
73
- pagechange={(e) => ui.currentPage = e.currentPage}
74
- searchchange={(e) => ui.searchQuery = e.search}
73
+ pagechange={(e) => (ui.currentPage = e.currentPage)}
74
+ searchchange={(e) => (ui.searchQuery = e.search)}
75
75
  />
76
76
 
77
77
  <!-- Virtualized table -->
@@ -80,11 +80,15 @@ npm install svelte@^5.0.0 tailwindcss@^4.0.0 flowbite-svelte@^1.0.0 flowbite-sve
80
80
  {visibleKeys}
81
81
  sortKey={ui.sortKey}
82
82
  sortDir={ui.sortDir}
83
- sortCallback={(key) => { /* handle sort */ }}
84
- selectCallback={(detail) => { /* handle selection */ }}
83
+ sortCallback={(key) => {
84
+ /* handle sort */
85
+ }}
86
+ selectCallback={(detail) => {
87
+ /* handle selection */
88
+ }}
85
89
  {colWidths}
86
90
  >
87
- {#snippet rowSnippet({item, index, select, selected})}
91
+ {#snippet rowSnippet({ item, index, select, selected })}
88
92
  <tr onclick={select}>
89
93
  <td>{item.name}</td>
90
94
  <td>{item.email}</td>
@@ -102,24 +106,25 @@ A virtualized table component for efficient rendering of large datasets. The com
102
106
 
103
107
  #### Props
104
108
 
105
- | Prop | Type | Default | Description |
106
- |------|------|---------|-------------|
107
- | `items` | `Array` | `[]` | Array of data items to display |
108
- | `visibleKeys` | `Array` | `[]` | Array of keys/titles to display as column headers |
109
- | `sortKey` | `string \| null` | `null` | Current sort key (column header) |
110
- | `sortDir` | `'asc' \| 'desc'` | `'asc'` | Sort direction |
111
- | `className` | `string` | `''` | Additional CSS classes |
112
- | `style` | `string` | `''` | Inline styles |
113
- | `emptyMessage` | `string` | `'No items to display.'` | Message when no items |
114
- | `colWidths` | `object \| Array` | `{}` | Column width configuration (stretch weights or pixel values) |
115
- | `selected` | `any` | `null` | Currently selected item |
116
- | `selectCallback` | `function` | `() => {}` | Callback when a row is selected: `({item, index}) => void` |
117
- | `sortCallback` | `function` | `defaultSort` | Callback when sorting: `(headerKey) => void` |
118
- | `rowSnippet` | `Snippet` | required | Svelte 5 snippet for rendering rows |
109
+ | Prop | Type | Default | Description |
110
+ | ---------------- | ----------------- | ------------------------ | ------------------------------------------------------------ |
111
+ | `items` | `Array` | `[]` | Array of data items to display |
112
+ | `visibleKeys` | `Array` | `[]` | Array of keys/titles to display as column headers |
113
+ | `sortKey` | `string \| null` | `null` | Current sort key (column header) |
114
+ | `sortDir` | `'asc' \| 'desc'` | `'asc'` | Sort direction |
115
+ | `className` | `string` | `''` | Additional CSS classes |
116
+ | `style` | `string` | `''` | Inline styles |
117
+ | `emptyMessage` | `string` | `'No items to display.'` | Message when no items |
118
+ | `colWidths` | `object \| Array` | `{}` | Column width configuration (stretch weights or pixel values) |
119
+ | `selected` | `any` | `null` | Currently selected item |
120
+ | `selectCallback` | `function` | `() => {}` | Callback when a row is selected: `({item, index}) => void` |
121
+ | `sortCallback` | `function` | `defaultSort` | Callback when sorting: `(headerKey) => void` |
122
+ | `rowSnippet` | `Snippet` | required | Svelte 5 snippet for rendering rows |
119
123
 
120
124
  #### Row Snippet Parameters
121
125
 
122
126
  The `rowSnippet` receives an object with:
127
+
123
128
  - `item` - The current row data
124
129
  - `index` - Row index in the current page
125
130
  - `select` - Function to call to select this row
@@ -137,15 +142,21 @@ Below is a minimal example showing how to wire the `filterCallback` prop on `Vir
137
142
  const rawItems = [
138
143
  { id: 1, name: 'Alice', email: 'alice@example.com' },
139
144
  { id: 2, name: 'Bob', email: 'bob@example.com' },
140
- { id: 3, name: 'Carol', email: 'carol@example.com' }
145
+ { id: 3, name: 'Carol', email: 'carol@example.com' },
141
146
  ];
142
147
 
143
148
  // per-column filter values
144
149
  let filters = {};
145
150
 
146
151
  // derived, reactive filtered list
147
- $: filteredItems = rawItems.filter(item =>
148
- Object.entries(filters).every(([k, v]) => !v || String(item[k] ?? '').toLowerCase().includes(v.toLowerCase()))
152
+ $: filteredItems = rawItems.filter((item) =>
153
+ Object.entries(filters).every(
154
+ ([k, v]) =>
155
+ !v ||
156
+ String(item[k] ?? '')
157
+ .toLowerCase()
158
+ .includes(v.toLowerCase()),
159
+ ),
149
160
  );
150
161
 
151
162
  // called when a ColumnHeader emits a filter event: { key, value }
@@ -154,12 +165,8 @@ Below is a minimal example showing how to wire the `filterCallback` prop on `Vir
154
165
  }
155
166
  </script>
156
167
 
157
- <DataTable
158
- items={filteredItems}
159
- visibleKeys={['name', 'email']}
160
- filterCallback={handleFilter}
161
- >
162
- {#snippet rowSnippet({item, index, select, selected})}
168
+ <DataTable items={filteredItems} visibleKeys={['name', 'email']} filterCallback={handleFilter}>
169
+ {#snippet rowSnippet({ item, index, select, selected })}
163
170
  <tr onclick={select}>
164
171
  <td>{item.name}</td>
165
172
  <td>{item.email}</td>
@@ -171,12 +178,14 @@ Below is a minimal example showing how to wire the `filterCallback` prop on `Vir
171
178
  #### Column Widths
172
179
 
173
180
  Column widths can be specified as:
181
+
174
182
  - **Stretch weights** (numbers): Distributed proportionally, e.g., `{ name: 1, description: 3 }`
175
183
  - **Pixel values** (strings): Fixed widths, e.g., `{ id: '80px', name: '200px' }`
176
184
 
177
185
  #### Row Snippet Parameters
178
186
 
179
187
  The `rowSnippet` receives an object with:
188
+
180
189
  - `item` - The current row data
181
190
  - `index` - Row index in the current page
182
191
  - `select` - Function to call to select this row
@@ -188,14 +197,14 @@ Controls component for search and pagination.
188
197
 
189
198
  #### Props
190
199
 
191
- | Prop | Type | Default | Description |
192
- |------|------|---------|-------------|
193
- | `search` | `string` | `''` | Current search query |
194
- | `currentPage` | `number` | `1` | Current page number |
195
- | `perPage` | `number` | `25` | Items per page |
196
- | `totalItems` | `number` | `0` | Total number of items |
197
- | `pagechange` | `function` | `() => {}` | Callback for page changes: `({currentPage}) => void` |
198
- | `searchchange` | `function` | `() => {}` | Callback for search changes: `({search}) => void` |
200
+ | Prop | Type | Default | Description |
201
+ | -------------- | ---------- | ---------- | ---------------------------------------------------- |
202
+ | `search` | `string` | `''` | Current search query |
203
+ | `currentPage` | `number` | `1` | Current page number |
204
+ | `perPage` | `number` | `25` | Items per page |
205
+ | `totalItems` | `number` | `0` | Total number of items |
206
+ | `pagechange` | `function` | `() => {}` | Callback for page changes: `({currentPage}) => void` |
207
+ | `searchchange` | `function` | `() => {}` | Callback for search changes: `({search}) => void` |
199
208
 
200
209
  ### DataTableFilters
201
210
 
@@ -203,18 +212,19 @@ Multi-select filter component with flexible layout options. Implements OR logic
203
212
 
204
213
  #### Props
205
214
 
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 |
215
+ | Prop | Type | Default | Description |
216
+ | --------------- | ---------------------------- | -------------- | -------------------------------------------------------- |
217
+ | `columnFilters` | `Array` | `[]` | Array of filter configurations (see below) |
218
+ | `direction` | `'horizontal' \| 'vertical'` | `'horizontal'` | Layout direction for filter grid |
219
+ | `activeFilters` | `Object` | `{}` | Current active filters `{ columnKey: [selectedValues] }` |
220
+ | `filterChange` | `function` | `() => {}` | Callback when filters change |
221
+ | `className` | `string` | `''` | Additional CSS classes |
222
+ | `showCounts` | `boolean` | `true` | Whether to show value counts |
214
223
 
215
224
  #### columnFilters Structure
216
225
 
217
226
  Each item in `columnFilters` should have:
227
+
218
228
  ```javascript
219
229
  {
220
230
  key: 'columnKey', // Column identifier
@@ -230,36 +240,37 @@ Each item in `columnFilters` should have:
230
240
  - **AND across columns**: All active column filters must match for a row to pass
231
241
 
232
242
  Example usage with data filtering:
243
+
233
244
  ```svelte
234
245
  <script>
235
246
  import { DataTableFilters } from '@zhangt58/svelte-vtable';
236
-
247
+
237
248
  const data = [
238
249
  { name: 'Alice', dept: 'Engineering', status: 'Active' },
239
250
  { name: 'Bob', dept: 'Sales', status: 'Active' },
240
251
  // ...
241
252
  ];
242
-
253
+
243
254
  let activeFilters = $state({});
244
-
255
+
245
256
  const columnFilters = [
246
- {
247
- key: 'dept',
248
- label: 'Department',
257
+ {
258
+ key: 'dept',
259
+ label: 'Department',
249
260
  uniqueValues: ['Engineering', 'Sales'],
250
- counts: { 'Engineering': 5, 'Sales': 3 }
261
+ counts: { Engineering: 5, Sales: 3 },
251
262
  },
252
- {
253
- key: 'status',
254
- label: 'Status',
263
+ {
264
+ key: 'status',
265
+ label: 'Status',
255
266
  uniqueValues: ['Active', 'Inactive'],
256
- counts: { 'Active': 7, 'Inactive': 1 }
257
- }
267
+ counts: { Active: 7, Inactive: 1 },
268
+ },
258
269
  ];
259
-
270
+
260
271
  // Apply filters
261
272
  const filteredData = $derived(() => {
262
- return data.filter(item => {
273
+ return data.filter((item) => {
263
274
  for (const [key, values] of Object.entries(activeFilters)) {
264
275
  if (values?.length > 0 && !values.includes(item[key])) {
265
276
  return false; // AND logic across columns
@@ -270,10 +281,10 @@ Example usage with data filtering:
270
281
  });
271
282
  </script>
272
283
 
273
- <DataTableFilters
274
- {columnFilters}
284
+ <DataTableFilters
285
+ {columnFilters}
275
286
  {activeFilters}
276
- filterChange={({allFilters}) => activeFilters = allFilters}
287
+ filterChange={({ allFilters }) => (activeFilters = allFilters)}
277
288
  direction="horizontal"
278
289
  showCounts={true}
279
290
  />
@@ -285,11 +296,13 @@ For complete examples, see [DATATABLEFILTERS_README.md](./DATATABLEFILTERS_READM
285
296
 
286
297
  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:
287
298
 
288
- 1) Source vs published CSS
299
+ 1. Source vs published CSS
300
+
289
301
  - The human-editable source is `src/lib/styles.css`. It is written using Svelte-style `:global(...)` wrappers so the selectors are clear and scoped intentionally when compiled inside Svelte components.
290
302
  - Bundlers and consumer projects do not process Svelte `:global(...)` tokens when they load plain `.css` files. For that reason the package publishes a compiled plain-CSS file at `src/lib/dist/styles.css`. This compiled file has the `:global(...)` wrappers removed so the selectors are normal CSS selectors and will match in any bundler.
291
303
 
292
- 2) How you should import the styles as a consumer
304
+ 2. How you should import the styles as a consumer
305
+
293
306
  - Recommended (installed from npm):
294
307
 
295
308
  ```js
@@ -308,11 +321,13 @@ Components inside this package import the compiled CSS via:
308
321
 
309
322
  Do not import the raw `src/lib/styles.css` from components or consumers — the `:global(...)` wrappers will remain and selectors won't behave as intended outside the Svelte compiler.
310
323
 
311
- 3) How :global works here and why we compile it
324
+ 3. How :global works here and why we compile it
325
+
312
326
  - `:global(.selector)` is a Svelte compiler token used when writing styles in Svelte components. It tells the Svelte compiler to treat the selector as global instead of scoping it to the component.
313
327
  - When shipping plain `.css` files to consumers, those tokens must be converted into regular selectors. The repository contains a tiny build script (`scripts/build-styles.cjs`) that strips `:global(...)` wrappers and emits a compiled `src/lib/dist/styles.css`. This is what gets published and what consumers should import.
314
328
 
315
- 4) Build scripts and publishing
329
+ 4. Build scripts and publishing
330
+
316
331
  - The project has a `build:styles` script that generates `src/lib/dist/styles.css` from `src/lib/styles.css`:
317
332
 
318
333
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhangt58/svelte-vtable",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
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",
@@ -18,7 +18,9 @@
18
18
  "check": "svelte-check --tsconfig ./jsconfig.json",
19
19
  "build:styles": "node ./scripts/build-styles.cjs",
20
20
  "prepare": "npm run build:styles",
21
- "prepublishOnly": "npm run build:styles && npm run check"
21
+ "prepublishOnly": "npm run build:styles",
22
+ "format": "prettier --write .",
23
+ "format:check": "prettier --check ."
22
24
  },
23
25
  "keywords": [
24
26
  "svelte",
@@ -51,8 +53,10 @@
51
53
  "@sveltejs/vite-plugin-svelte": "^6.2.1",
52
54
  "flowbite-svelte": "^1.28.1",
53
55
  "flowbite-svelte-icons": "^3.0.0",
56
+ "prettier": "^3.7.4",
57
+ "prettier-plugin-svelte": "^3.4.1",
54
58
  "svelte": "^5.0.0",
55
- "svelte-check": "^4.3.4",
59
+ "svelte-check": "^4.3.5",
56
60
  "svelte-virtuallists": "^1.4.2",
57
61
  "vite": "^7.2.2"
58
62
  },
@@ -5,6 +5,7 @@
5
5
  const DEFAULT_NOOP = (..._args) => {};
6
6
 
7
7
  // Default sort behavior: sort by the header string alphabetically, toggling asc/desc
8
+ // and actually sort the items array
8
9
  function defaultSort(key) {
9
10
  if (sortKey === key) {
10
11
  sortDir = sortDir === 'asc' ? 'desc' : 'asc';
@@ -12,6 +13,30 @@
12
13
  sortKey = key;
13
14
  sortDir = 'asc';
14
15
  }
16
+
17
+ // Actually sort the items array
18
+ items = [...items].sort((a, b) => {
19
+ const aVal = a[key];
20
+ const bVal = b[key];
21
+
22
+ // Handle null/undefined values
23
+ if (aVal == null && bVal == null) return 0;
24
+ if (aVal == null) return 1;
25
+ if (bVal == null) return -1;
26
+
27
+ // Convert to strings for comparison
28
+ const aStr = String(aVal);
29
+ const bStr = String(bVal);
30
+
31
+ // Alphabetical comparison
32
+ const comparison = aStr.localeCompare(bStr, undefined, {
33
+ numeric: true,
34
+ sensitivity: 'base',
35
+ });
36
+
37
+ // Apply sort direction
38
+ return sortDir === 'asc' ? comparison : -comparison;
39
+ });
15
40
  }
16
41
 
17
42
  // Runic props: accept props via $props() so the component matches the
@@ -37,21 +62,29 @@
37
62
  // by setting its `isDisabled` prop. Default: true (virtualization enabled).
38
63
  virtualize = true,
39
64
  // <slot> -> @render migration
40
- rowSnippet
65
+ rowSnippet,
41
66
  } = $props();
42
67
 
43
68
  // expose selection via the callback prop (if provided)
44
69
  function selectItem(item, index) {
45
70
  selected = item;
46
- try { callSelectCallback({ item, index }); } catch (err) { try { console.error('selectCallback threw:', err); } catch (e) {} }
71
+ try {
72
+ callSelectCallback({ item, index });
73
+ } catch (err) {
74
+ try {
75
+ console.error('selectCallback threw:', err);
76
+ } catch (e) {}
77
+ }
47
78
  }
48
79
 
49
80
  // Wrapper that casts the possibly-typed callback to any before invoking so callers may pass a payload
50
81
  function callSelectCallback(payload) {
51
82
  try {
52
- (/** @type {any} */ (selectCallback))(payload);
83
+ /** @type {any} */ (selectCallback)(payload);
53
84
  } catch (err) {
54
- try { console.error('selectCallback threw:', err); } catch (e) {}
85
+ try {
86
+ console.error('selectCallback threw:', err);
87
+ } catch (e) {}
55
88
  }
56
89
  }
57
90
 
@@ -59,7 +92,13 @@
59
92
  // using bind:sortKey / bind:sortDir receive updates (no event dispatching).
60
93
  function handleSort(key) {
61
94
  // Delegate sorting to the configured callback (by default `defaultSort` will run)
62
- try { sortCallback(key); } catch (err) { try { console.error('sortCallback threw:', err); } catch (e) {} }
95
+ try {
96
+ sortCallback(key);
97
+ } catch (err) {
98
+ try {
99
+ console.error('sortCallback threw:', err);
100
+ } catch (e) {}
101
+ }
63
102
  }
64
103
 
65
104
  // Normalize colWidths: handle object or array input, treat numeric as stretch weights.
@@ -101,9 +140,10 @@
101
140
  if (numeric.length > 0 && totalWeight > 0) {
102
141
  let acc = 0;
103
142
  numeric.forEach((n, idx) => {
104
- const pct = idx === numeric.length - 1
105
- ? Math.max(0, Math.round((availablePct - acc) * 100) / 100)
106
- : Math.round((n.w / totalWeight) * availablePct * 100) / 100;
143
+ const pct =
144
+ idx === numeric.length - 1
145
+ ? Math.max(0, Math.round((availablePct - acc) * 100) / 100)
146
+ : Math.round((n.w / totalWeight) * availablePct * 100) / 100;
107
147
  map[n.key] = `${pct}%`;
108
148
  acc += pct;
109
149
  });
@@ -153,16 +193,20 @@
153
193
  const pct = Math.floor(100 / n);
154
194
  return pct + '%';
155
195
  }
156
-
157
196
  </script>
158
197
 
159
- <section class="virtual-data-table {className}" style={style}>
198
+ <section class="virtual-data-table {className}" {style}>
160
199
  {#if items && items.length > 0}
161
200
  <!-- When `virtualize` is false we instruct VirtualList to render as a normal list/table
162
201
  by setting `isDisabled`. This ensures pagination based on item counts shows the
163
202
  exact number of rows expected (useful when rows have variable height). -->
164
- <VirtualList items={items} isTable isDisabled={!virtualize} class="datatable-table max-w-full max-h-full overflow-auto">
165
- <!-- colgroup enforces the column widths so table-layout: fixed distributes as intended -->
203
+ <VirtualList
204
+ {items}
205
+ isTable
206
+ isDisabled={!virtualize}
207
+ class="datatable-table max-w-full max-h-full overflow-auto"
208
+ >
209
+ <!-- colgroup enforces the column widths so table-layout: fixed distributes as intended -->
166
210
  {#snippet header()}
167
211
  <colgroup>
168
212
  {#each visibleKeys as key, i}
@@ -172,8 +216,16 @@
172
216
  <thead class="sticky-header">
173
217
  <tr>
174
218
  {#each visibleKeys as key, i}
175
- <th style="width: {calcColWidth(key, i)}" class="cursor-pointer select-none" onclick={() => handleSort(key)}
176
- aria-sort={sortKey === key ? (sortDir === 'asc' ? 'ascending' : 'descending') : 'none'}>
219
+ <th
220
+ style="width: {calcColWidth(key, i)}"
221
+ class="cursor-pointer select-none"
222
+ onclick={() => handleSort(key)}
223
+ aria-sort={sortKey === key
224
+ ? sortDir === 'asc'
225
+ ? 'ascending'
226
+ : 'descending'
227
+ : 'none'}
228
+ >
177
229
  <div class="inline-flex items-center gap-1">
178
230
  <span>{key}</span>
179
231
  {#if sortKey === key}
@@ -187,7 +239,7 @@
187
239
  {/snippet}
188
240
 
189
241
  {#snippet vl_slot({ index, item })}
190
- {@render rowSnippet({item, index, select: () => selectItem(item, index), selected})}
242
+ {@render rowSnippet({ item, index, select: () => selectItem(item, index), selected })}
191
243
  {/snippet}
192
244
  </VirtualList>
193
245
  {:else}
@@ -198,4 +250,3 @@
198
250
  <style>
199
251
  @import '../lib/dist/styles.css';
200
252
  </style>
201
-