@zhangt58/svelte-vtable 0.1.0 → 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.
@@ -1,20 +1,20 @@
1
1
  <script>
2
- import { Pagination, Search, Badge } from 'flowbite-svelte';
2
+ import { Pagination, Search, Badge, Select } from 'flowbite-svelte';
3
3
  import { FilterOutline } from 'flowbite-svelte-icons';
4
4
  import FiltersModal from './FiltersModal.svelte';
5
5
  // Inline SVGs are used instead of importing icons to avoid the dependency on flowbite-svelte-icons
6
6
  import { onMount, onDestroy } from 'svelte';
7
7
 
8
- // Props for search, pagination (but no per-page control)
8
+ // Props for search, pagination (perPage made bindable using Svelte 5 rune $bindable)
9
9
  let {
10
10
  search = '',
11
11
  currentPage = 1,
12
- perPage = 25, // Fixed value, not user-configurable
12
+ perPage = $bindable(25),
13
13
  totalItems = 0,
14
14
  pagechange = () => {},
15
15
  searchchange = () => {},
16
16
  // control visibility of DataTableFilters above the controls
17
- filtersVisible = true,
17
+ filtersVisible = false,
18
18
  // callback when toggle changes: filterstoggle({ filtersVisible })
19
19
  filterstoggle = () => {},
20
20
  // optional DataTableFilters inputs - when provided, this component will render the filters
@@ -24,13 +24,25 @@
24
24
  filterChange = (..._args) => {},
25
25
  direction = 'horizontal',
26
26
  showCounts = true,
27
- className = ''
27
+ className = '',
28
+ // new callback when perPage changes
29
+ perpagechange = () => {},
28
30
  } = $props();
29
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
+
30
39
  // count of active filters (sum of selected values per column)
31
40
  const activeFilterCount = $derived(() => {
32
41
  try {
33
- return Object.values(activeFilters || {}).reduce((sum, v) => sum + (Array.isArray(v) ? v.length : 0), 0);
42
+ return Object.values(activeFilters || {}).reduce(
43
+ (sum, v) => sum + (Array.isArray(v) ? v.length : 0),
44
+ 0,
45
+ );
34
46
  } catch (e) {
35
47
  return 0;
36
48
  }
@@ -66,20 +78,45 @@
66
78
  return;
67
79
  }
68
80
  if (filtersVisible !== _prevFiltersVisible) {
69
- try { filterstoggle?.({ filtersVisible }); } catch (err) {}
81
+ try {
82
+ filterstoggle?.({ filtersVisible });
83
+ } catch (err) {}
70
84
  _prevFiltersVisible = filtersVisible;
71
85
  }
72
86
  });
73
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
+
74
110
  // Calculate range for display
75
- const startItem = $derived(() => totalItems === 0 ? 0 : (currentPage - 1) * perPage + 1);
111
+ const startItem = $derived(() => (totalItems === 0 ? 0 : (currentPage - 1) * perPage + 1));
76
112
  const endItem = $derived(() => Math.min(currentPage * perPage, totalItems));
77
113
 
78
114
  // visiblePages: number of middle numeric buttons to show (not counting first/last)
79
115
  const visiblePages = 5;
80
116
 
81
117
  // stable id to query the pagination DOM if needed (fallback)
82
- const paginationId = `pagination-${Math.random().toString(36).slice(2,9)}`;
118
+ const paginationId = `pagination-${Math.random().toString(36).slice(2, 9)}`;
119
+ const perPageSelectId = `dpc-perpage-${Math.random().toString(36).slice(2, 7)}`;
83
120
 
84
121
  // pages array for Pagination component (condensed with ellipses)
85
122
  const pages = $derived(() => {
@@ -88,7 +125,10 @@
88
125
 
89
126
  // If small number of pages, show all
90
127
  if (total <= visiblePages + 2) {
91
- return Array.from({ length: total }, (_, i) => ({ name: String(i + 1), active: i + 1 === current }));
128
+ return Array.from({ length: total }, (_, i) => ({
129
+ name: String(i + 1),
130
+ active: i + 1 === current,
131
+ }));
92
132
  }
93
133
 
94
134
  const pagesArr = [];
@@ -123,7 +163,10 @@
123
163
  // compute right jump (midpoint of hidden range end+1..total-1)
124
164
  const rightHiddenStart = end + 1;
125
165
  const rightHiddenEnd = total - 1;
126
- const rightJump = Math.min(rightHiddenEnd, Math.ceil((rightHiddenStart + rightHiddenEnd) / 2));
166
+ const rightJump = Math.min(
167
+ rightHiddenEnd,
168
+ Math.ceil((rightHiddenStart + rightHiddenEnd) / 2),
169
+ );
127
170
  pagesArr.push({ name: '…', active: false, ellipsis: 'right', jump: rightJump });
128
171
  }
129
172
 
@@ -157,8 +200,8 @@
157
200
  }
158
201
  if (!ul) return;
159
202
  // Ensure the <ul> has Tailwind utility classes for layout
160
- ul.classList.remove('flex','gap-0.5','p-0','m-0','list-none','items-center');
161
- ul.classList.add('flex','gap-0.5','p-0','m-0','list-none','items-center');
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');
162
205
  const lis = Array.from(ul.children || []);
163
206
  // Build a list of page-button <li>s (skip prev/next controls) by checking their textContent
164
207
  const pageLis = [];
@@ -184,32 +227,57 @@
184
227
  // Apply Tailwind utility classes instead of inline styles
185
228
  // Remove any previously-applied utility classes we manage
186
229
  btn.classList.remove(
187
- 'px-2','py-1','text-sm','border','border-gray-300','bg-transparent','min-w-[2rem]',
188
- 'inline-flex','items-center','justify-center','transition-colors','hover:bg-gray-100',
189
- 'bg-green-100','text-green-600','border-transparent','opacity-60','cursor-default','pointer-events-none',
190
- 'tw-ellipsis'
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',
191
249
  );
192
250
 
193
251
  // Base Tailwind classes for pagination buttons
194
252
  btn.classList.add(
195
- 'px-2','py-1','text-sm','border','border-gray-300','bg-transparent','min-w-[2rem]',
196
- 'inline-flex','items-center','justify-center','transition-colors','hover:bg-gray-100'
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',
197
265
  );
198
266
 
199
267
  // active page styling
200
268
  if (pageObj.active) {
201
- btn.classList.add('bg-green-100','text-green-600','border-transparent');
269
+ btn.classList.add('bg-green-100', 'text-green-600', 'border-transparent');
202
270
  btn.setAttribute('aria-current', 'page');
203
271
  } else {
204
272
  btn.removeAttribute('aria-current');
205
- btn.classList.remove('bg-green-100','text-green-600','border-transparent');
273
+ btn.classList.remove('bg-green-100', 'text-green-600', 'border-transparent');
206
274
  }
207
275
 
208
276
  // disabled styling
209
277
  if (btn.disabled || btn.getAttribute('aria-disabled') === 'true') {
210
- btn.classList.add('opacity-60','cursor-default','pointer-events-none');
278
+ btn.classList.add('opacity-60', 'cursor-default', 'pointer-events-none');
211
279
  } else {
212
- btn.classList.remove('opacity-60','cursor-default','pointer-events-none');
280
+ btn.classList.remove('opacity-60', 'cursor-default', 'pointer-events-none');
213
281
  }
214
282
 
215
283
  if (pageObj.name === '…' && typeof pageObj['jump'] === 'number') {
@@ -218,7 +286,7 @@
218
286
  // restore native tooltip for compatibility (browser tooltip)
219
287
  btn.setAttribute('title', `Jump to page ${pageObj['jump']}`);
220
288
  // visually indicate ellipsis (smaller text) via Tailwind
221
- btn.classList.add('text-sm','opacity-90');
289
+ btn.classList.add('text-sm', 'opacity-90');
222
290
  }
223
291
  });
224
292
  }
@@ -237,7 +305,10 @@
237
305
  if (!paginationContainerEl) return;
238
306
  const run = () => requestAnimationFrame(() => requestAnimationFrame(() => decorateEllipsis()));
239
307
  _observer = new MutationObserver(run);
240
- const root = paginationContainerEl instanceof Element ? paginationContainerEl : document.querySelector(`[data-pagination-id="${paginationId}"]`);
308
+ const root =
309
+ paginationContainerEl instanceof Element
310
+ ? paginationContainerEl
311
+ : document.querySelector(`[data-pagination-id="${paginationId}"]`);
241
312
  if (root) _observer.observe(root, { childList: true, subtree: true, attributes: true });
242
313
  // initial run
243
314
  run();
@@ -258,33 +329,27 @@
258
329
  const ul = li.parentElement;
259
330
  if (!ul) return;
260
331
  const lis = Array.from(ul.children);
261
- // Find prev/next by detecting non-numeric/non-ellipsis buttons
262
- const pageList = pages();
263
- // Build ordered list of page-button lis (numeric and ellipsis)
332
+ // Build a list of page-button <li>s (skip prev/next controls) by checking their textContent
264
333
  const pageLis = [];
265
- for (const item of lis) {
266
- const btn = item.querySelector('button, a');
334
+ for (const liItem of lis) {
335
+ const btn = liItem.querySelector('button, a');
267
336
  if (!btn) continue;
268
337
  const text = (btn.textContent || '').trim();
269
- if (/^\d+$/.test(text) || text === '…') pageLis.push({ li: item, btn, text });
338
+ // consider numeric pages and ellipsis as page buttons
339
+ if (/^\d+$/.test(text) || text === '…') pageLis.push({ li: liItem, btn, text });
270
340
  }
271
341
 
272
- // If clicked on prev/next controls, detect by checking whether clicked li is not in pageLis
273
- const clickedIsPage = pageLis.some(p => p.li === li);
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);
274
345
  if (!clickedIsPage) {
275
- // determine if it was prev (first li) or next (last li)
276
- const firstLi = lis[0];
277
- const lastLi = lis[lis.length - 1];
278
- if (li === firstLi) {
279
- previous();
280
- } else if (li === lastLi) {
281
- next();
282
- }
283
- return;
346
+ return; // rely on Pagination's built-in previous/next handling to avoid double-invocation
284
347
  }
285
348
 
349
+ const pageList = pages();
350
+
286
351
  // Map clicked li to page index
287
- const pageIdx = pageLis.findIndex(p => p.li === li);
352
+ const pageIdx = pageLis.findIndex((p) => p.li === li);
288
353
  if (pageIdx < 0 || pageIdx >= pageList.length) return;
289
354
  const pageObj = pageList[pageIdx];
290
355
  if (!pageObj) return;
@@ -308,16 +373,16 @@
308
373
  <div class="flex items-center gap-1 relative">
309
374
  <button
310
375
  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 " +
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 ' +
313
377
  (filtersVisible
314
378
  ? '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
- }
379
+ : 'bg-transparent border-transparent text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700')}
317
380
  aria-pressed={filtersVisible}
318
381
  aria-label="Toggle filters"
319
382
  title="Filters"
320
- onclick={() => { filtersVisible = !filtersVisible; }}
383
+ onclick={() => {
384
+ filtersVisible = !filtersVisible;
385
+ }}
321
386
  >
322
387
  <!-- Funnel icon (Flowbite icon component) -->
323
388
  <FilterOutline class="h-4 w-4 shrink-0" />
@@ -326,24 +391,45 @@
326
391
 
327
392
  {#if activeFilterCount() > 0}
328
393
  <!-- 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>
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
+ >
330
398
  {/if}
331
399
  </div>
332
400
 
333
- <Search size="sm" bind:value={search} placeholder="Search..." clearable
334
- clearableOnClick={() => { search = ''; searchchange?.({ search }); }} />
401
+ <Search
402
+ size="sm"
403
+ bind:value={search}
404
+ placeholder="Search..."
405
+ clearable
406
+ clearableOnClick={() => {
407
+ search = '';
408
+ searchchange?.({ search });
409
+ }}
410
+ />
335
411
  </div>
336
412
  </div>
337
413
 
338
- <!-- Range count badge -->
339
- <div class="flex-2">
414
+ <!-- Range count badge + per-page selector -->
415
+ <div class="flex-2 flex items-center gap-2">
340
416
  <Badge rounded color="gray">
341
417
  Showing {startItem()} to {endItem()} of {totalItems}
342
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>
343
424
  </div>
344
425
 
345
426
  <!-- 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">
427
+ <div
428
+ bind:this={paginationContainerEl}
429
+ data-pagination-id={paginationId}
430
+ class="flex items-center gap-0.5"
431
+ aria-label="Pagination"
432
+ >
347
433
  <Pagination
348
434
  pages={pages()}
349
435
  {previous}
@@ -354,16 +440,40 @@
354
440
  {#snippet prevContent()}
355
441
  <span class="sr-only">Previous</span>
356
442
  <!-- 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" />
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
+ />
359
457
  </svg>
360
458
  {/snippet}
361
459
 
362
460
  {#snippet nextContent()}
363
461
  <span class="sr-only">Next</span>
364
462
  <!-- 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" />
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
+ />
367
477
  </svg>
368
478
  {/snippet}
369
479
  </Pagination>
@@ -371,15 +481,20 @@
371
481
  </div>
372
482
  </div>
373
483
 
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}
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}
381
496
  />
382
497
 
383
498
  <style>
384
- @import '../lib/dist/styles.css';
385
- </style>
499
+ @import '../lib/dist/styles.css';
500
+ </style>