@zhangt58/svelte-vtable 0.1.4 → 0.3.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.
Files changed (36) hide show
  1. package/README.md +177 -44
  2. package/dist/components/DataTable.svelte +489 -0
  3. package/dist/components/DataTable.svelte.d.ts +31 -0
  4. package/dist/components/DataTableControls.svelte +576 -0
  5. package/dist/components/DataTableControls.svelte.d.ts +39 -0
  6. package/dist/components/DataTableFilters.svelte +215 -0
  7. package/dist/components/DataTableFilters.svelte.d.ts +37 -0
  8. package/dist/components/FiltersModal.svelte +65 -0
  9. package/dist/components/FiltersModal.svelte.d.ts +25 -0
  10. package/dist/components/PaginationBar.svelte +86 -0
  11. package/dist/components/PaginationBar.svelte.d.ts +15 -0
  12. package/dist/components/filters/FilterColumn.svelte +53 -0
  13. package/dist/components/filters/FilterColumn.svelte.d.ts +19 -0
  14. package/dist/components/filters/FilterDateRange.svelte +341 -0
  15. package/dist/components/filters/FilterDateRange.svelte.d.ts +19 -0
  16. package/dist/components/filters/FilterValueList.svelte +437 -0
  17. package/dist/components/filters/FilterValueList.svelte.d.ts +33 -0
  18. package/dist/components/filters/useFilterState.svelte.d.ts +25 -0
  19. package/dist/components/filters/useFilterState.svelte.js +132 -0
  20. package/dist/components/flowbite/DataTableControls.svelte +525 -0
  21. package/dist/components/flowbite/DataTableControls.svelte.d.ts +39 -0
  22. package/{src/components → dist/components/flowbite}/FiltersModal.svelte +5 -15
  23. package/dist/components/flowbite/FiltersModal.svelte.d.ts +25 -0
  24. package/dist/filterUtils.d.ts +76 -0
  25. package/{src/lib → dist}/filterUtils.js +48 -46
  26. package/dist/index.d.ts +60 -0
  27. package/dist/index.flowbite.d.ts +3 -0
  28. package/dist/index.flowbite.js +9 -0
  29. package/dist/index.js +49 -0
  30. package/{src/lib → dist}/styles.css +26 -3
  31. package/package.json +38 -17
  32. package/src/components/DataTable.svelte +0 -252
  33. package/src/components/DataTableControls.svelte +0 -500
  34. package/src/components/DataTableFilters.svelte +0 -1225
  35. package/src/lib/dist/styles.css +0 -273
  36. package/src/lib/index.js +0 -16
@@ -1,500 +0,0 @@
1
- <script>
2
- import { Pagination, Search, Badge, Select } from 'flowbite-svelte';
3
- import { FilterOutline } from 'flowbite-svelte-icons';
4
- import FiltersModal from './FiltersModal.svelte';
5
- // Inline SVGs are used instead of importing icons to avoid the dependency on flowbite-svelte-icons
6
- import { onMount, onDestroy } from 'svelte';
7
-
8
- // Props for search, pagination (perPage made bindable using Svelte 5 rune $bindable)
9
- let {
10
- search = '',
11
- currentPage = 1,
12
- perPage = $bindable(25),
13
- totalItems = 0,
14
- pagechange = () => {},
15
- searchchange = () => {},
16
- // control visibility of DataTableFilters above the controls
17
- filtersVisible = false,
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 = '',
28
- // new callback when perPage changes
29
- perpagechange = () => {},
30
- } = $props();
31
-
32
- const perPageOptions = [
33
- { value: 10, name: '10 rows' },
34
- { value: 25, name: '25 rows' },
35
- { value: 50, name: '50 rows' },
36
- { value: 100, name: '100 rows' },
37
- ];
38
-
39
- // count of active filters (sum of selected values per column)
40
- const activeFilterCount = $derived(() => {
41
- try {
42
- return Object.values(activeFilters || {}).reduce(
43
- (sum, v) => sum + (Array.isArray(v) ? v.length : 0),
44
- 0,
45
- );
46
- } catch (e) {
47
- return 0;
48
- }
49
- });
50
-
51
- // totalPages derived from totalItems and perPage
52
- const totalPages = $derived(() => Math.max(1, Math.ceil(totalItems / perPage)));
53
-
54
- // clamp currentPage into valid range whenever currentPage or totalPages change
55
- $effect(() => {
56
- currentPage = Math.min(Math.max(1, +currentPage || 1), totalPages());
57
- });
58
-
59
- function goTo(p) {
60
- const np = Math.min(Math.max(1, Math.floor(p)), totalPages());
61
- if (np !== currentPage) {
62
- currentPage = np;
63
- pagechange?.({ currentPage });
64
- }
65
- }
66
-
67
- // emit search changes for parent when search updates
68
- $effect(() => {
69
- if (typeof search !== 'undefined') searchchange?.({ search });
70
- });
71
-
72
- // call filterstoggle when filtersVisible changes (avoid on:change typing issues)
73
- let _prevFiltersVisible = undefined;
74
- $effect(() => {
75
- // initialize previous value on first run without emitting
76
- if (_prevFiltersVisible === undefined) {
77
- _prevFiltersVisible = filtersVisible;
78
- return;
79
- }
80
- if (filtersVisible !== _prevFiltersVisible) {
81
- try {
82
- filterstoggle?.({ filtersVisible });
83
- } catch (err) {}
84
- _prevFiltersVisible = filtersVisible;
85
- }
86
- });
87
-
88
- // Watch perPage changes: reset to first page and notify parent
89
- let _prevPerPage = undefined;
90
- $effect(() => {
91
- if (_prevPerPage === undefined) {
92
- _prevPerPage = perPage;
93
- return;
94
- }
95
- if (perPage !== _prevPerPage) {
96
- // coerce to number just in case
97
- perPage = +perPage || 25;
98
- _prevPerPage = perPage;
99
- // reset to page 1 (common UX) and notify parent
100
- currentPage = 1;
101
- try {
102
- perpagechange?.({ perPage });
103
- } catch (err) {}
104
- try {
105
- pagechange?.({ currentPage });
106
- } catch (err) {}
107
- }
108
- });
109
-
110
- // Calculate range for display
111
- const startItem = $derived(() => (totalItems === 0 ? 0 : (currentPage - 1) * perPage + 1));
112
- const endItem = $derived(() => Math.min(currentPage * perPage, totalItems));
113
-
114
- // visiblePages: number of middle numeric buttons to show (not counting first/last)
115
- const visiblePages = 5;
116
-
117
- // stable id to query the pagination DOM if needed (fallback)
118
- const paginationId = `pagination-${Math.random().toString(36).slice(2, 9)}`;
119
- const perPageSelectId = `dpc-perpage-${Math.random().toString(36).slice(2, 7)}`;
120
-
121
- // pages array for Pagination component (condensed with ellipses)
122
- const pages = $derived(() => {
123
- const total = totalPages();
124
- const current = Math.min(Math.max(1, Math.floor(currentPage)), total);
125
-
126
- // If small number of pages, show all
127
- if (total <= visiblePages + 2) {
128
- return Array.from({ length: total }, (_, i) => ({
129
- name: String(i + 1),
130
- active: i + 1 === current,
131
- }));
132
- }
133
-
134
- const pagesArr = [];
135
- // always show first
136
- pagesArr.push({ name: '1', active: current === 1 });
137
-
138
- const half = Math.floor(visiblePages / 2);
139
- let start = Math.max(2, current - half);
140
- let end = Math.min(total - 1, current + half);
141
-
142
- // adjust window when near the boundaries
143
- if (current - 1 <= half) {
144
- start = 2;
145
- end = 1 + visiblePages;
146
- }
147
- if (total - current <= half) {
148
- end = total - 1;
149
- start = total - visiblePages;
150
- }
151
-
152
- if (start > 2) {
153
- // compute left jump (midpoint of hidden range 2..start-1)
154
- const leftHiddenStart = 2;
155
- const leftHiddenEnd = start - 1;
156
- const leftJump = Math.max(leftHiddenStart, Math.floor((leftHiddenStart + leftHiddenEnd) / 2));
157
- pagesArr.push({ name: '…', active: false, ellipsis: 'left', jump: leftJump });
158
- }
159
-
160
- for (let i = start; i <= end; i++) pagesArr.push({ name: String(i), active: i === current });
161
-
162
- if (end < total - 1) {
163
- // compute right jump (midpoint of hidden range end+1..total-1)
164
- const rightHiddenStart = end + 1;
165
- const rightHiddenEnd = total - 1;
166
- const rightJump = Math.min(
167
- rightHiddenEnd,
168
- Math.ceil((rightHiddenStart + rightHiddenEnd) / 2),
169
- );
170
- pagesArr.push({ name: '…', active: false, ellipsis: 'right', jump: rightJump });
171
- }
172
-
173
- // always show last
174
- pagesArr.push({ name: String(total), active: current === total });
175
-
176
- return pagesArr;
177
- });
178
-
179
- // previous / next callbacks for Pagination
180
- function previous() {
181
- goTo(currentPage - 1);
182
- }
183
- function next() {
184
- goTo(currentPage + 1);
185
- }
186
-
187
- // DOM reference to the pagination container for decorating ellipsis buttons
188
- let paginationContainerEl = null;
189
-
190
- function decorateEllipsis() {
191
- if (!paginationContainerEl) return;
192
- const pageList = pages();
193
- // find the <ul> inside the pagination container
194
- let ul = null;
195
- if (paginationContainerEl && typeof paginationContainerEl.querySelector === 'function') {
196
- ul = paginationContainerEl.querySelector('ul');
197
- } else {
198
- // fallback: query by data attribute on the wrapper
199
- ul = document.querySelector(`[data-pagination-id="${paginationId}"] ul`);
200
- }
201
- if (!ul) return;
202
- // Ensure the <ul> has Tailwind utility classes for layout
203
- ul.classList.remove('flex', 'gap-0.5', 'p-0', 'm-0', 'list-none', 'items-center');
204
- ul.classList.add('flex', 'gap-0.5', 'p-0', 'm-0', 'list-none', 'items-center');
205
- const lis = Array.from(ul.children || []);
206
- // Build a list of page-button <li>s (skip prev/next controls) by checking their textContent
207
- const pageLis = [];
208
- for (const li of lis) {
209
- const btn = li.querySelector('button, a');
210
- if (!btn) continue;
211
- const text = (btn.textContent || '').trim();
212
- // consider numeric pages and ellipsis as page buttons
213
- if (/^\d+$/.test(text) || text === '…') pageLis.push({ li, btn, text });
214
- }
215
-
216
- // Now map pageLis to pageList entries in order
217
- pageLis.forEach((p, idx) => {
218
- const btn = p.btn;
219
- const pageObj = pageList[idx];
220
- if (!pageObj) return;
221
- // clear previous decorations
222
- btn.classList.remove('ellipsis-page');
223
- btn.removeAttribute('data-jump');
224
- btn.removeAttribute('data-ellipsis');
225
- btn.removeAttribute('title');
226
-
227
- // Apply Tailwind utility classes instead of inline styles
228
- // Remove any previously-applied utility classes we manage
229
- btn.classList.remove(
230
- 'px-2',
231
- 'py-1',
232
- 'text-sm',
233
- 'border',
234
- 'border-gray-300',
235
- 'bg-transparent',
236
- 'min-w-[2rem]',
237
- 'inline-flex',
238
- 'items-center',
239
- 'justify-center',
240
- 'transition-colors',
241
- 'hover:bg-gray-100',
242
- 'bg-green-100',
243
- 'text-green-600',
244
- 'border-transparent',
245
- 'opacity-60',
246
- 'cursor-default',
247
- 'pointer-events-none',
248
- 'tw-ellipsis',
249
- );
250
-
251
- // Base Tailwind classes for pagination buttons
252
- btn.classList.add(
253
- 'px-2',
254
- 'py-1',
255
- 'text-sm',
256
- 'border',
257
- 'border-gray-300',
258
- 'bg-transparent',
259
- 'min-w-[2rem]',
260
- 'inline-flex',
261
- 'items-center',
262
- 'justify-center',
263
- 'transition-colors',
264
- 'hover:bg-gray-100',
265
- );
266
-
267
- // active page styling
268
- if (pageObj.active) {
269
- btn.classList.add('bg-green-100', 'text-green-600', 'border-transparent');
270
- btn.setAttribute('aria-current', 'page');
271
- } else {
272
- btn.removeAttribute('aria-current');
273
- btn.classList.remove('bg-green-100', 'text-green-600', 'border-transparent');
274
- }
275
-
276
- // disabled styling
277
- if (btn.disabled || btn.getAttribute('aria-disabled') === 'true') {
278
- btn.classList.add('opacity-60', 'cursor-default', 'pointer-events-none');
279
- } else {
280
- btn.classList.remove('opacity-60', 'cursor-default', 'pointer-events-none');
281
- }
282
-
283
- if (pageObj.name === '…' && typeof pageObj['jump'] === 'number') {
284
- btn.setAttribute('data-jump', String(pageObj['jump']));
285
- btn.setAttribute('data-ellipsis', 'true');
286
- // restore native tooltip for compatibility (browser tooltip)
287
- btn.setAttribute('title', `Jump to page ${pageObj['jump']}`);
288
- // visually indicate ellipsis (smaller text) via Tailwind
289
- btn.classList.add('text-sm', 'opacity-90');
290
- }
291
- });
292
- }
293
-
294
- // run decoration whenever pages or currentPage change
295
- $effect(() => {
296
- pages();
297
- currentPage;
298
- // schedule decoration after the browser has painted the updated DOM
299
- requestAnimationFrame(() => requestAnimationFrame(() => decorateEllipsis()));
300
- });
301
-
302
- // Re-apply decorations whenever the pagination DOM mutates (childList changes)
303
- let _observer = null;
304
- onMount(() => {
305
- if (!paginationContainerEl) return;
306
- const run = () => requestAnimationFrame(() => requestAnimationFrame(() => decorateEllipsis()));
307
- _observer = new MutationObserver(run);
308
- const root =
309
- paginationContainerEl instanceof Element
310
- ? paginationContainerEl
311
- : document.querySelector(`[data-pagination-id="${paginationId}"]`);
312
- if (root) _observer.observe(root, { childList: true, subtree: true, attributes: true });
313
- // initial run
314
- run();
315
- });
316
-
317
- onDestroy(() => {
318
- _observer?.disconnect();
319
- _observer = null;
320
- });
321
-
322
- // handle clicks inside Pagination to detect page button clicks
323
- function handlePaginationClick(e) {
324
- const el = e.target instanceof Element ? e.target.closest('button, a') : null;
325
- if (!el) return;
326
- // find the parent li index so we can map to pages()
327
- const li = el.closest('li');
328
- if (!li) return;
329
- const ul = li.parentElement;
330
- if (!ul) return;
331
- const lis = Array.from(ul.children);
332
- // Build a list of page-button <li>s (skip prev/next controls) by checking their textContent
333
- const pageLis = [];
334
- for (const liItem of lis) {
335
- const btn = liItem.querySelector('button, a');
336
- if (!btn) continue;
337
- const text = (btn.textContent || '').trim();
338
- // consider numeric pages and ellipsis as page buttons
339
- if (/^\d+$/.test(text) || text === '…') pageLis.push({ li: liItem, btn, text });
340
- }
341
-
342
- // Map clicked li to decide what to do. If clicked is not a page button (i.e. prev/next),
343
- // do nothing here because the Pagination component already calls the `previous`/`next` callbacks.
344
- const clickedIsPage = pageLis.some((p) => p.li === li);
345
- if (!clickedIsPage) {
346
- return; // rely on Pagination's built-in previous/next handling to avoid double-invocation
347
- }
348
-
349
- const pageList = pages();
350
-
351
- // Map clicked li to page index
352
- const pageIdx = pageLis.findIndex((p) => p.li === li);
353
- if (pageIdx < 0 || pageIdx >= pageList.length) return;
354
- const pageObj = pageList[pageIdx];
355
- if (!pageObj) return;
356
- if (pageObj.name === '…' && typeof pageObj['jump'] === 'number') {
357
- goTo(pageObj['jump']);
358
- return;
359
- }
360
- const n = Number(pageObj.name);
361
- if (!Number.isNaN(n)) goTo(n);
362
- }
363
-
364
- // No external tooltip component in use; we rely on native title attribute for ellipses
365
- </script>
366
-
367
- <div class="w-full">
368
- <div class="flex items-center w-full gap-3 px-0 py-0">
369
- <!-- Search field on the left -->
370
- <div class="flex-1">
371
- <div class="flex items-center gap-2">
372
- <!-- Styled button to open/close filters modal -->
373
- <div class="flex items-center gap-1 relative">
374
- <button
375
- type="button"
376
- class={'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 ' +
377
- (filtersVisible
378
- ? 'bg-slate-100 dark:bg-slate-700 border-slate-300 dark:border-slate-600 text-slate-900 dark:text-slate-100'
379
- : 'bg-transparent border-transparent text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700')}
380
- aria-pressed={filtersVisible}
381
- aria-label="Toggle filters"
382
- title="Filters"
383
- onclick={() => {
384
- filtersVisible = !filtersVisible;
385
- }}
386
- >
387
- <!-- Funnel icon (Flowbite icon component) -->
388
- <FilterOutline class="h-4 w-4 shrink-0" />
389
- <span class="text-sm">Filters</span>
390
- </button>
391
-
392
- {#if activeFilterCount() > 0}
393
- <!-- positioned badge -->
394
- <span
395
- 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"
396
- >{activeFilterCount()}</span
397
- >
398
- {/if}
399
- </div>
400
-
401
- <Search
402
- size="sm"
403
- bind:value={search}
404
- placeholder="Search..."
405
- clearable
406
- clearableOnClick={() => {
407
- search = '';
408
- searchchange?.({ search });
409
- }}
410
- />
411
- </div>
412
- </div>
413
-
414
- <!-- Range count badge + per-page selector -->
415
- <div class="flex-2 flex items-center gap-2">
416
- <Badge rounded color="gray">
417
- Showing {startItem()} to {endItem()} of {totalItems}
418
- </Badge>
419
-
420
- <!-- Per-page selector -->
421
- <div class="flex items-center gap-2">
422
- <Select id={perPageSelectId} size="sm" items={perPageOptions} bind:value={perPage} />
423
- </div>
424
- </div>
425
-
426
- <!-- Pagination navigation: use Pagination with chevrons and page buttons -->
427
- <div
428
- bind:this={paginationContainerEl}
429
- data-pagination-id={paginationId}
430
- class="flex items-center gap-0.5"
431
- aria-label="Pagination"
432
- >
433
- <Pagination
434
- pages={pages()}
435
- {previous}
436
- {next}
437
- ariaLabel="Pagination"
438
- onclick={handlePaginationClick}
439
- >
440
- {#snippet prevContent()}
441
- <span class="sr-only">Previous</span>
442
- <!-- Left chevron SVG (replaces ChevronLeftOutline) -->
443
- <svg
444
- class="shrink-0 h-6 w-6"
445
- xmlns="http://www.w3.org/2000/svg"
446
- fill="none"
447
- viewBox="0 0 24 24"
448
- stroke="currentColor"
449
- aria-hidden="true"
450
- >
451
- <path
452
- stroke-linecap="round"
453
- stroke-linejoin="round"
454
- stroke-width="1"
455
- d="M15 19l-7-7 7-7"
456
- />
457
- </svg>
458
- {/snippet}
459
-
460
- {#snippet nextContent()}
461
- <span class="sr-only">Next</span>
462
- <!-- Right chevron SVG (replaces ChevronRightOutline) -->
463
- <svg
464
- class="shrink-0 h-6 w-6"
465
- xmlns="http://www.w3.org/2000/svg"
466
- fill="none"
467
- viewBox="0 0 24 24"
468
- stroke="currentColor"
469
- aria-hidden="true"
470
- >
471
- <path
472
- stroke-linecap="round"
473
- stroke-linejoin="round"
474
- stroke-width="1"
475
- d="M9 5l7 7-7 7"
476
- />
477
- </svg>
478
- {/snippet}
479
- </Pagination>
480
- </div>
481
- </div>
482
- </div>
483
-
484
- <FiltersModal
485
- bind:open={filtersVisible}
486
- {columnFilters}
487
- {activeFilters}
488
- filterChange={(...args) => {
489
- try {
490
- return filterChange(...args);
491
- } catch (e) {}
492
- }}
493
- {direction}
494
- {showCounts}
495
- {className}
496
- />
497
-
498
- <style>
499
- @import '../lib/dist/styles.css';
500
- </style>