@zhangt58/svelte-vtable 0.1.4 → 0.2.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.
@@ -1,9 +1,8 @@
1
1
  <script>
2
- import { Pagination, Search, Badge, Select } from 'flowbite-svelte';
2
+ import { Search, Badge, Select } from 'flowbite-svelte';
3
3
  import { FilterOutline } from 'flowbite-svelte-icons';
4
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';
5
+ import PaginationBar from './PaginationBar.svelte';
7
6
 
8
7
  // Props for search, pagination (perPage made bindable using Svelte 5 rune $bindable)
9
8
  let {
@@ -11,22 +10,23 @@
11
10
  currentPage = 1,
12
11
  perPage = $bindable(25),
13
12
  totalItems = 0,
14
- pagechange = () => {},
15
- searchchange = () => {},
13
+ onpage = undefined,
14
+ onsearch = undefined,
16
15
  // control visibility of DataTableFilters above the controls
17
16
  filtersVisible = false,
18
- // callback when toggle changes: filterstoggle({ filtersVisible })
19
- filterstoggle = () => {},
17
+ // callback when toggle changes: onfilterstoggle({ visible })
18
+ onfilterstoggle = undefined,
20
19
  // optional DataTableFilters inputs - when provided, this component will render the filters
21
20
  columnFilters = [],
22
21
  activeFilters = {},
23
- /** @type {(..._args: any[]) => void} */
24
- filterChange = (..._args) => {},
22
+ // onfilter({ key, values, allFilters }) — passed through to DataTableFilters
23
+ /** @type {((..._args: any[]) => void) | undefined} */
24
+ onfilter = undefined,
25
25
  direction = 'horizontal',
26
26
  showCounts = true,
27
27
  className = '',
28
- // new callback when perPage changes
29
- perpagechange = () => {},
28
+ // callback when perPage changes: onperpage({ perPage })
29
+ onperpage = undefined,
30
30
  } = $props();
31
31
 
32
32
  const perPageOptions = [
@@ -37,7 +37,7 @@
37
37
  ];
38
38
 
39
39
  // count of active filters (sum of selected values per column)
40
- const activeFilterCount = $derived(() => {
40
+ const activeFilterCount = $derived.by(() => {
41
41
  try {
42
42
  return Object.values(activeFilters || {}).reduce(
43
43
  (sum, v) => sum + (Array.isArray(v) ? v.length : 0),
@@ -49,27 +49,33 @@
49
49
  });
50
50
 
51
51
  // totalPages derived from totalItems and perPage
52
- const totalPages = $derived(() => Math.max(1, Math.ceil(totalItems / perPage)));
52
+ const totalPages = $derived(Math.max(1, Math.ceil(totalItems / perPage)));
53
53
 
54
54
  // clamp currentPage into valid range whenever currentPage or totalPages change
55
55
  $effect(() => {
56
- currentPage = Math.min(Math.max(1, +currentPage || 1), totalPages());
56
+ currentPage = Math.min(Math.max(1, +currentPage || 1), totalPages);
57
57
  });
58
58
 
59
59
  function goTo(p) {
60
- const np = Math.min(Math.max(1, Math.floor(p)), totalPages());
60
+ const np = Math.min(Math.max(1, Math.floor(p)), totalPages);
61
61
  if (np !== currentPage) {
62
62
  currentPage = np;
63
- pagechange?.({ currentPage });
63
+ if (onpage !== undefined) {
64
+ onpage({ page: np });
65
+ }
64
66
  }
65
67
  }
66
68
 
67
69
  // emit search changes for parent when search updates
68
70
  $effect(() => {
69
- if (typeof search !== 'undefined') searchchange?.({ search });
71
+ if (typeof search !== 'undefined') {
72
+ if (onsearch !== undefined) {
73
+ onsearch({ search });
74
+ }
75
+ }
70
76
  });
71
77
 
72
- // call filterstoggle when filtersVisible changes (avoid on:change typing issues)
78
+ // call onfilterstoggle when filtersVisible changes (avoid on:change typing issues)
73
79
  let _prevFiltersVisible = undefined;
74
80
  $effect(() => {
75
81
  // initialize previous value on first run without emitting
@@ -78,9 +84,11 @@
78
84
  return;
79
85
  }
80
86
  if (filtersVisible !== _prevFiltersVisible) {
81
- try {
82
- filterstoggle?.({ filtersVisible });
83
- } catch (err) {}
87
+ if (onfilterstoggle !== undefined) {
88
+ try {
89
+ onfilterstoggle({ visible: filtersVisible });
90
+ } catch (err) {}
91
+ }
84
92
  _prevFiltersVisible = filtersVisible;
85
93
  }
86
94
  });
@@ -98,29 +106,31 @@
98
106
  _prevPerPage = perPage;
99
107
  // reset to page 1 (common UX) and notify parent
100
108
  currentPage = 1;
101
- try {
102
- perpagechange?.({ perPage });
103
- } catch (err) {}
104
- try {
105
- pagechange?.({ currentPage });
106
- } catch (err) {}
109
+ if (onperpage !== undefined) {
110
+ try {
111
+ onperpage({ perPage });
112
+ } catch (err) {}
113
+ }
114
+ if (onpage !== undefined) {
115
+ try {
116
+ onpage({ page: currentPage });
117
+ } catch (err) {}
118
+ }
107
119
  }
108
120
  });
109
121
 
110
122
  // Calculate range for display
111
- const startItem = $derived(() => (totalItems === 0 ? 0 : (currentPage - 1) * perPage + 1));
112
- const endItem = $derived(() => Math.min(currentPage * perPage, totalItems));
123
+ const startItem = $derived(totalItems === 0 ? 0 : (currentPage - 1) * perPage + 1);
124
+ const endItem = $derived(Math.min(currentPage * perPage, totalItems));
113
125
 
114
126
  // visiblePages: number of middle numeric buttons to show (not counting first/last)
115
127
  const visiblePages = 5;
116
128
 
117
- // stable id to query the pagination DOM if needed (fallback)
118
- const paginationId = `pagination-${Math.random().toString(36).slice(2, 9)}`;
119
129
  const perPageSelectId = `dpc-perpage-${Math.random().toString(36).slice(2, 7)}`;
120
130
 
121
131
  // pages array for Pagination component (condensed with ellipses)
122
- const pages = $derived(() => {
123
- const total = totalPages();
132
+ const pages = $derived.by(() => {
133
+ const total = totalPages;
124
134
  const current = Math.min(Math.max(1, Math.floor(currentPage)), total);
125
135
 
126
136
  // If small number of pages, show all
@@ -176,191 +186,6 @@
176
186
  return pagesArr;
177
187
  });
178
188
 
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
189
  // No external tooltip component in use; we rely on native title attribute for ellipses
365
190
  </script>
366
191
 
@@ -373,7 +198,7 @@
373
198
  <div class="flex items-center gap-1 relative">
374
199
  <button
375
200
  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 ' +
201
+ 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 ' +
377
202
  (filtersVisible
378
203
  ? 'bg-slate-100 dark:bg-slate-700 border-slate-300 dark:border-slate-600 text-slate-900 dark:text-slate-100'
379
204
  : 'bg-transparent border-transparent text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700')}
@@ -389,11 +214,11 @@
389
214
  <span class="text-sm">Filters</span>
390
215
  </button>
391
216
 
392
- {#if activeFilterCount() > 0}
217
+ {#if activeFilterCount > 0}
393
218
  <!-- positioned badge -->
394
219
  <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
220
+ 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 text-white text-xs font-medium"
221
+ style="background-color: var(--vtable-color-accent);">{activeFilterCount}</span
397
222
  >
398
223
  {/if}
399
224
  </div>
@@ -405,7 +230,9 @@
405
230
  clearable
406
231
  clearableOnClick={() => {
407
232
  search = '';
408
- searchchange?.({ search });
233
+ if (onsearch !== undefined) {
234
+ onsearch({ search: '' });
235
+ }
409
236
  }}
410
237
  />
411
238
  </div>
@@ -414,7 +241,7 @@
414
241
  <!-- Range count badge + per-page selector -->
415
242
  <div class="flex-2 flex items-center gap-2">
416
243
  <Badge rounded color="gray">
417
- Showing {startItem()} to {endItem()} of {totalItems}
244
+ Showing {startItem} to {endItem} of {totalItems}
418
245
  </Badge>
419
246
 
420
247
  <!-- Per-page selector -->
@@ -423,61 +250,8 @@
423
250
  </div>
424
251
  </div>
425
252
 
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>
253
+ <!-- Pagination navigation -->
254
+ <PaginationBar {pages} {currentPage} onpage={goTo} />
481
255
  </div>
482
256
  </div>
483
257
 
@@ -485,11 +259,7 @@
485
259
  bind:open={filtersVisible}
486
260
  {columnFilters}
487
261
  {activeFilters}
488
- filterChange={(...args) => {
489
- try {
490
- return filterChange(...args);
491
- } catch (e) {}
492
- }}
262
+ {onfilter}
493
263
  {direction}
494
264
  {showCounts}
495
265
  {className}