@mintplayer/web-components 1.6.0 → 2.0.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.
@@ -1,9 +1,9 @@
1
- import { unsafeCSS as C, LitElement as S, nothing as c, html as h } from "lit";
2
- import { repeat as $ } from "lit/directives/repeat.js";
3
- import { styleMap as f } from "lit/directives/style-map.js";
1
+ import { unsafeCSS as x, LitElement as C, nothing as c, html as d } from "lit";
2
+ import { repeat as S } from "lit/directives/repeat.js";
3
+ import { styleMap as m } from "lit/directives/style-map.js";
4
4
  import "./mp-pagination-BGxsawFL.mjs";
5
5
  import "./mp-checkbox-BokLL7BS.mjs";
6
- const I = C(`@charset "UTF-8";
6
+ const R = x(`@charset "UTF-8";
7
7
  :host {
8
8
  display: block;
9
9
  width: 100%;
@@ -249,12 +249,12 @@ tbody tr[data-placeholder=true] {
249
249
  transition: none !important;
250
250
  }
251
251
  }`);
252
- function R(l, e, t) {
252
+ function I(l, e, t) {
253
253
  if (t) {
254
- const r = l.findIndex((i) => i.property === e);
255
- return r === -1 ? [...l, { property: e, direction: "ascending" }] : l[r].direction === "ascending" ? l.map(
256
- (i, a) => a === r ? { ...i, direction: "descending" } : i
257
- ) : l.filter((i, a) => a !== r);
254
+ const i = l.findIndex((a) => a.property === e);
255
+ return i === -1 ? [...l, { property: e, direction: "ascending" }] : l[i].direction === "ascending" ? l.map(
256
+ (a, r) => r === i ? { ...a, direction: "descending" } : a
257
+ ) : l.filter((a, r) => r !== i);
258
258
  }
259
259
  const s = l.length === 1 && l[0].property === e;
260
260
  return [
@@ -266,28 +266,28 @@ function R(l, e, t) {
266
266
  }
267
267
  function b(l, e) {
268
268
  return e.length === 0 ? l.slice() : l.map((t, s) => ({ row: t, index: s })).sort((t, s) => {
269
- for (const r of e) {
270
- const i = w(t.row, r.property), a = w(s.row, r.property), o = E(i, a);
269
+ for (const i of e) {
270
+ const a = y(t.row, i.property), r = y(s.row, i.property), o = $(a, r);
271
271
  if (o !== 0)
272
- return r.direction === "ascending" ? o : -o;
272
+ return i.direction === "ascending" ? o : -o;
273
273
  }
274
274
  return t.index - s.index;
275
275
  }).map(({ row: t }) => t);
276
276
  }
277
- function w(l, e) {
277
+ function y(l, e) {
278
278
  if (!(l == null || typeof l != "object"))
279
279
  return l[e];
280
280
  }
281
- function E(l, e) {
281
+ function $(l, e) {
282
282
  return l === e ? 0 : l == null ? 1 : e == null ? -1 : typeof l == "number" && typeof e == "number" ? l - e : l instanceof Date && e instanceof Date ? l.getTime() - e.getTime() : String(l).localeCompare(String(e));
283
283
  }
284
- let z = 0;
285
- class M extends S {
284
+ let P = 0;
285
+ class E extends C {
286
286
  constructor() {
287
- super(...arguments), this.instanceId = `mp-datatable-${++z}`, this._columns = [], this._data = [], this._sortColumns = [], this._selectionMode = "none", this._selectedIds = /* @__PURE__ */ new Set(), this._cutIds = /* @__PURE__ */ new Set(), this._focusedRowKey = null, this._rowKey = (e, t) => {
287
+ super(...arguments), this.instanceId = `mp-datatable-${++P}`, this._columns = [], this._data = [], this._sortColumns = [], this._selectionMode = "none", this._selectedIds = /* @__PURE__ */ new Set(), this._cutIds = /* @__PURE__ */ new Set(), this._focusedRowKey = null, this._rowKey = (e, t) => {
288
288
  const s = e;
289
289
  return s && s.id != null ? String(s.id) : `row-${t}`;
290
- }, this._columnWidths = /* @__PURE__ */ new Map(), this._hasMeasuredInitial = !1, this._loading = !1, this._emptyMessage = "No data", this._pagination = !1, this._page = 1, this._perPage = 20, this._perPageOptions = [10, 20, 50], this._autoSort = !0, this._totalRecords = null, this._virtualScroll = !1, this._itemSize = 40, this._virtualBuffer = 10, this._virtualRange = { startIndex: 0, endIndex: 0 }, this._scrollElement = null, this._resizeObserver = null, this._scrollListener = null, this._viewportHeight = 0, this._tree = !1, this._idKey = null, this._childCountKey = null, this._treeIndent = 1.25, this._expandedIds = /* @__PURE__ */ new Set(), this._selectionStrategy = "flat", this._childCache = /* @__PURE__ */ new Map(), this._childTotals = /* @__PURE__ */ new Map(), this._pendingFetches = /* @__PURE__ */ new Set(), this._cachedFlatList = null, this._cachedIndeterminateKeys = null, this._resizableColumns = !0, this.resizeState = null, this.onColumnResizeMove = (e) => {
290
+ }, this._columnWidths = /* @__PURE__ */ new Map(), this._hasMeasuredInitial = !1, this._loading = !1, this._emptyMessage = "No data", this._pagination = !1, this._page = 1, this._perPage = 20, this._perPageOptions = [10, 20, 50], this._autoSort = !0, this._totalRecords = null, this._virtualScroll = !1, this._itemSize = 40, this._virtualBuffer = 10, this._virtualRange = { startIndex: 0, endIndex: 0 }, this._scrollElement = null, this._resizeObserver = null, this._scrollListener = null, this._viewportHeight = 0, this._tree = !1, this._idKey = null, this._childCountKey = null, this._treeIndent = 1.25, this._expandedIds = /* @__PURE__ */ new Set(), this._selectionStrategy = "flat", this._childCache = /* @__PURE__ */ new Map(), this._childTotals = /* @__PURE__ */ new Map(), this._pendingFetches = /* @__PURE__ */ new Set(), this._pageCache = /* @__PURE__ */ new Map(), this._pendingPageFetches = /* @__PURE__ */ new Set(), this._fetch = null, this._fetchGeneration = 0, this._initialFetchDone = !1, this._reloadScheduled = !1, this._lastReloadKey = null, this._cachedFlatList = null, this._cachedIndeterminateKeys = null, this._resizableColumns = !0, this.resizeState = null, this.onColumnResizeMove = (e) => {
291
291
  if (!this.resizeState) return;
292
292
  const t = e.clientX - this.resizeState.startX, s = Math.max(40, this.resizeState.startWidth + t);
293
293
  this._columnWidths = new Map(this._columnWidths), this._columnWidths.set(this.resizeState.columnName, s), this.requestUpdate();
@@ -303,7 +303,7 @@ class M extends S {
303
303
  };
304
304
  }
305
305
  static {
306
- this.styles = [I];
306
+ this.styles = [R];
307
307
  }
308
308
  static get observedAttributes() {
309
309
  return [
@@ -374,11 +374,23 @@ class M extends S {
374
374
  set data(e) {
375
375
  this._data = Array.isArray(e) ? e : [], this.requestUpdate();
376
376
  }
377
+ /**
378
+ * High-level fetch callback. When set, the WC owns the entire server-paged
379
+ * loop and the consumer provides nothing else — no page-1 seeding via `data`,
380
+ * no separate `totalRecords`, no event bridge. Works with any framework or
381
+ * none (`el.fetch = fn`). Setting it kicks off the initial page-1 load.
382
+ */
383
+ get fetch() {
384
+ return this._fetch;
385
+ }
386
+ set fetch(e) {
387
+ this._fetch = typeof e == "function" ? e : null, this._fetch && (this._autoSort = !1, this._initialFetchDone = !1, this._lastReloadKey = null, this.scheduleFetchReload());
388
+ }
377
389
  get sortColumns() {
378
390
  return [...this._sortColumns];
379
391
  }
380
392
  set sortColumns(e) {
381
- this._sortColumns = Array.isArray(e) ? [...e] : [], this.requestUpdate();
393
+ this._sortColumns = Array.isArray(e) ? [...e] : [], this.requestUpdate(), this.scheduleFetchReload();
382
394
  }
383
395
  get selectionMode() {
384
396
  return this._selectionMode;
@@ -485,14 +497,14 @@ class M extends S {
485
497
  }
486
498
  set page(e) {
487
499
  const t = Math.max(1, Math.floor(e || 1));
488
- this._page !== t && (this._page = t, this.requestUpdate());
500
+ this._page !== t && (this._page = t, this.requestUpdate(), this.scheduleFetchReload());
489
501
  }
490
502
  get perPage() {
491
503
  return this._perPage;
492
504
  }
493
505
  set perPage(e) {
494
506
  const t = Math.max(1, Math.floor(e || 1));
495
- this._perPage !== t && (this._perPage = t, this._page = 1, this.requestUpdate());
507
+ this._perPage !== t && (this._perPage = t, this._page = 1, this.requestUpdate(), this.scheduleFetchReload());
496
508
  }
497
509
  get perPageOptions() {
498
510
  return [...this._perPageOptions];
@@ -501,25 +513,32 @@ class M extends S {
501
513
  this._perPageOptions = Array.isArray(e) && e.length > 0 ? [...e] : [10, 20, 50], this.requestUpdate();
502
514
  }
503
515
  /**
504
- * Caller-supplied total record count for external paging. Set this when
505
- * `[fetch]` returns one page at a time so the pagination footer can show
506
- * the correct total. Leave as `null` (default) to use `_data.length`.
516
+ * Read-only grand total. Derived by the WC from the `fetch` response (server
517
+ * paging) or `_data.length` (static data) — consumers never set it. Exposed
518
+ * so a consumer can render "row X of N" if it wants.
507
519
  */
508
520
  get totalRecords() {
509
521
  return this._totalRecords;
510
522
  }
511
- set totalRecords(e) {
512
- const t = e == null ? null : Math.max(0, Math.floor(e));
513
- this._totalRecords !== t && (this._totalRecords = t, this.requestUpdate());
514
- }
515
523
  /** True when the consumer is paging externally (totalRecords exceeds the in-memory rows). */
516
524
  isExternallyPaged() {
517
525
  return this._totalRecords != null && this._totalRecords > this._data.length;
518
526
  }
527
+ /**
528
+ * True when virtual scrolling is driving lazy windowed fetches at the **root**
529
+ * level: the consumer pages externally and the WC pulls root pages ≥ 2 on
530
+ * demand. Applies to BOTH flat mode (the rows are the roots) and tree mode
531
+ * (the top-level rows; their children are windowed separately, keyed by
532
+ * parentId). When false (single page or no virtual scroll) the WC falls back
533
+ * to the trivial mapping of `_data`.
534
+ */
535
+ isRootWindowed() {
536
+ return this._virtualScroll && this.isExternallyPaged();
537
+ }
519
538
  attributeChangedCallback(e, t, s) {
520
539
  if (super.attributeChangedCallback(e, t, s), e === "selection-mode") {
521
- const r = s;
522
- (r === "none" || r === "single" || r === "multiple") && (this.selectionMode = r);
540
+ const i = s;
541
+ (i === "none" || i === "single" || i === "multiple") && (this.selectionMode = i);
523
542
  } else if (e === "pagination")
524
543
  this.pagination = s !== null;
525
544
  else if (e === "resizable-columns")
@@ -531,13 +550,13 @@ class M extends S {
531
550
  else if (e === "virtual-scroll")
532
551
  this.virtualScroll = s !== null;
533
552
  else if (e === "item-size") {
534
- const r = Number(s);
535
- Number.isFinite(r) && (this.itemSize = r);
553
+ const i = Number(s);
554
+ Number.isFinite(i) && (this.itemSize = i);
536
555
  } else if (e === "tree")
537
556
  this.tree = s !== null;
538
557
  else if (e === "tree-indent") {
539
- const r = Number(s);
540
- Number.isFinite(r) && (this.treeIndent = r);
558
+ const i = Number(s);
559
+ Number.isFinite(i) && (this.treeIndent = i);
541
560
  } else e === "selection-strategy" && (this.selectionStrategy = s === "cascading" ? "cascading" : "flat");
542
561
  }
543
562
  get resizableColumns() {
@@ -571,14 +590,14 @@ class M extends S {
571
590
  if (this._hasMeasuredInitial || this._columns.length === 0 || this._data.length === 0 || !this.shadowRoot || this.shadowRoot.querySelectorAll('tbody tr[data-row-key]:not([data-placeholder="true"])').length === 0) return;
572
591
  const t = new Map(this._columnWidths);
573
592
  let s = !1;
574
- for (const r of this._columns) {
575
- if (t.has(r.name)) continue;
576
- if (typeof r.width == "number") {
577
- t.set(r.name, r.width), s = !0;
593
+ for (const i of this._columns) {
594
+ if (t.has(i.name)) continue;
595
+ if (typeof i.width == "number") {
596
+ t.set(i.name, i.width), s = !0;
578
597
  continue;
579
598
  }
580
- const i = this.measureColumnWidth(r.name);
581
- i != null && (t.set(r.name, i), s = !0);
599
+ const a = this.measureColumnWidth(i.name);
600
+ a != null && (t.set(i.name, a), s = !0);
582
601
  }
583
602
  s && (this._columnWidths = t, this._hasMeasuredInitial = !0, this.requestUpdate());
584
603
  }
@@ -596,24 +615,39 @@ class M extends S {
596
615
  if (!this._virtualScroll || !this._scrollElement) return;
597
616
  const e = this._scrollElement.scrollTop, t = this._scrollElement.clientHeight;
598
617
  this._viewportHeight = t;
599
- const s = this.getEffectiveData().length, r = this._itemSize, i = Math.max(0, Math.floor(e / r) - this._virtualBuffer), a = Math.ceil(t / r), o = Math.min(s, i + a + this._virtualBuffer * 2);
600
- (i !== this._virtualRange.startIndex || o !== this._virtualRange.endIndex) && (this._virtualRange = { startIndex: i, endIndex: o }, this.requestUpdate()), this._tree && this.maybeFetchPlaceholdersInViewport();
618
+ const s = this.getEffectiveData().length, i = this._itemSize, a = Math.max(0, Math.floor(e / i) - this._virtualBuffer), r = Math.ceil(t / i), o = Math.min(s, a + r + this._virtualBuffer * 2);
619
+ (a !== this._virtualRange.startIndex || o !== this._virtualRange.endIndex) && (this._virtualRange = { startIndex: a, endIndex: o }, this.requestUpdate()), this._tree && this.maybeFetchPlaceholdersInViewport(), this.isRootWindowed() && this.maybeFetchPagesInViewport();
601
620
  }
602
621
  /**
603
622
  * Walk the visible viewport for placeholder rows whose parent isn't cached
604
623
  * and isn't already in-flight. Emit a fetch-request per such parent.
605
624
  */
606
625
  maybeFetchPlaceholdersInViewport() {
607
- const e = this.getFlatList(), { startIndex: t, endIndex: s } = this._virtualRange, r = this._virtualScroll ? t : 0, i = this._virtualScroll ? s : e.length, a = /* @__PURE__ */ new Set();
608
- for (let o = r; o < i; o++) {
626
+ const e = this.getFlatList(), { startIndex: t, endIndex: s } = this._virtualRange, i = this._virtualScroll ? t : 0, a = this._virtualScroll ? s : e.length, r = /* @__PURE__ */ new Set();
627
+ for (let o = i; o < a; o++) {
628
+ const n = e[o];
629
+ !n.isPlaceholder || n.parentId == null || this._childCache.has(n.parentId) || this._pendingFetches.has(n.parentId) || r.add(n.parentId);
630
+ }
631
+ for (const o of r) this.fetchChildren(o);
632
+ }
633
+ /**
634
+ * Flat-window counterpart of `maybeFetchPlaceholdersInViewport`: scan the
635
+ * visible range for flat placeholder rows, collect the distinct pages they
636
+ * belong to that aren't cached or already in-flight, and request each once.
637
+ * Page 1 is never requested here — it lives in `_data` (seeded by the
638
+ * wrapper's first-page fetch).
639
+ */
640
+ maybeFetchPagesInViewport() {
641
+ const e = this.getFlatList(), { startIndex: t, endIndex: s } = this._virtualRange, i = this._virtualScroll ? t : 0, a = this._virtualScroll ? s : e.length, r = /* @__PURE__ */ new Set();
642
+ for (let o = i; o < a; o++) {
609
643
  const n = e[o];
610
- !n.isPlaceholder || n.parentId == null || this._childCache.has(n.parentId) || this._pendingFetches.has(n.parentId) || a.add(n.parentId);
644
+ !n.isPlaceholder || n.page == null || n.page <= 1 || this._pageCache.has(n.page) || this._pendingPageFetches.has(n.page) || r.add(n.page);
611
645
  }
612
- for (const o of a) this.requestChildrenFetch(o);
646
+ for (const o of r) this.fetchWindowPage(o);
613
647
  }
614
648
  render() {
615
- const e = this.computeVisibleRows(), t = this._totalRecords ?? this._data.length, s = this.pagination && !this._tree ? Math.max(1, Math.ceil(t / this._perPage)) : 1, r = this._selectionMode === "multiple", i = this._columns.length + (r ? 1 : 0) + (this._tree ? 1 : 0), a = this.getVirtualSpacerHeights(), o = (this._tree ? this.getFlatList().length : this._data.length) + 1;
616
- return h`
649
+ const e = this.computeVisibleRows(), t = this._totalRecords ?? this._data.length, s = this.pagination && !this._tree ? Math.max(1, Math.ceil(t / this._perPage)) : 1, i = this._selectionMode === "multiple", a = this._columns.length + (i ? 1 : 0) + (this._tree ? 1 : 0), r = this.getVirtualSpacerHeights(), o = (this._tree || this.isRootWindowed() ? this.getFlatList().length : this._data.length) + 1;
650
+ return d`
617
651
  <div class="datatable-shell">
618
652
  <div class="datatable-scroll ${this._virtualScroll ? "datatable-virtual" : ""}" role="presentation">
619
653
  <table
@@ -623,29 +657,29 @@ class M extends S {
623
657
  >
624
658
  <thead>
625
659
  <tr role="row" aria-rowindex="1">
626
- ${this._tree ? h`<th class="tree-chevron-cell" scope="col" aria-label="Expand or collapse"></th>` : c}
627
- ${r ? h`<th class="checkbox-cell" scope="col">
660
+ ${this._tree ? d`<th class="tree-chevron-cell" scope="col" aria-label="Expand or collapse"></th>` : c}
661
+ ${i ? d`<th class="checkbox-cell" scope="col">
628
662
  <mp-checkbox
629
663
  aria-label="Deselect all"
630
664
  aria-hidden=${this._selectedIds.size === 0 ? "true" : c}
631
- style=${f({ visibility: this._selectedIds.size > 0 ? "visible" : "hidden" })}
665
+ style=${m({ visibility: this._selectedIds.size > 0 ? "visible" : "hidden" })}
632
666
  .checked=${!1}
633
667
  .indeterminate=${this._selectedIds.size > 0}
634
668
  @change=${this.onDeselectAll}
635
669
  ></mp-checkbox>
636
670
  </th>` : c}
637
- ${this._columns.map((n, d) => this.renderHeader(n, d))}
671
+ ${this._columns.map((n, h) => this.renderHeader(n, h))}
638
672
  </tr>
639
673
  </thead>
640
674
  <tbody>
641
- ${this._loading ? h`<tr><td colspan=${i} class="loading-state">Loading…</td></tr>` : e.length === 0 ? h`<tr><td colspan=${i} class="empty-state">${this._emptyMessage}</td></tr>` : h`
642
- ${a.top > 0 ? h`<tr class="virtual-spacer" aria-hidden="true"><td colspan=${i} style=${f({ height: `${a.top}px`, padding: "0", border: "0" })}></td></tr>` : c}
643
- ${$(
675
+ ${this._loading ? d`<tr><td colspan=${a} class="loading-state">Loading…</td></tr>` : e.length === 0 ? d`<tr><td colspan=${a} class="empty-state">${this._emptyMessage}</td></tr>` : d`
676
+ ${r.top > 0 ? d`<tr class="virtual-spacer" aria-hidden="true"><td colspan=${a} style=${m({ height: `${r.top}px`, padding: "0", border: "0" })}></td></tr>` : c}
677
+ ${S(
644
678
  e,
645
679
  ({ key: n }) => n,
646
- ({ key: n, rowIndex: d, flat: g }) => this.renderRow(g, n, d, r)
680
+ ({ key: n, rowIndex: h, flat: _ }) => this.renderRow(_, n, h, i)
647
681
  )}
648
- ${a.bottom > 0 ? h`<tr class="virtual-spacer" aria-hidden="true"><td colspan=${i} style=${f({ height: `${a.bottom}px`, padding: "0", border: "0" })}></td></tr>` : c}
682
+ ${r.bottom > 0 ? d`<tr class="virtual-spacer" aria-hidden="true"><td colspan=${a} style=${m({ height: `${r.bottom}px`, padding: "0", border: "0" })}></td></tr>` : c}
649
683
  `}
650
684
  </tbody>
651
685
  </table>
@@ -663,92 +697,92 @@ class M extends S {
663
697
  };
664
698
  }
665
699
  renderHeader(e, t) {
666
- const s = e.sortable ?? !0, r = this._sortColumns.findIndex((d) => d.property === e.name), i = r >= 0 ? this._sortColumns[r].direction : null, a = this._columnWidths.get(e.name) ?? e.width, o = e.headerRenderer ? e.headerRenderer(e) : e.label ?? e.name, n = {};
667
- return typeof a == "number" && (n.width = `${a}px`, n.minWidth = `${a}px`), h`
700
+ const s = e.sortable ?? !0, i = this._sortColumns.findIndex((h) => h.property === e.name), a = i >= 0 ? this._sortColumns[i].direction : null, r = this._columnWidths.get(e.name) ?? e.width, o = e.headerRenderer ? e.headerRenderer(e) : e.label ?? e.name, n = {};
701
+ return typeof r == "number" && (n.width = `${r}px`, n.minWidth = `${r}px`), d`
668
702
  <th
669
703
  scope="col"
670
704
  data-column=${e.name}
671
705
  data-sortable=${s ? "true" : "false"}
672
- aria-sort=${i ? i === "ascending" ? "ascending" : "descending" : "none"}
673
- style=${f(n)}
674
- @click=${(d) => this.onHeaderClick(e, d)}
706
+ aria-sort=${a ? a === "ascending" ? "ascending" : "descending" : "none"}
707
+ style=${m(n)}
708
+ @click=${(h) => this.onHeaderClick(e, h)}
675
709
  >
676
710
  <span class="header-cell">
677
- <span>${x(o)}</span>
678
- ${r >= 0 && this._sortColumns.length > 1 ? h`<span class="sort-index">${r + 1}</span>` : c}
711
+ <span>${w(o)}</span>
712
+ ${i >= 0 && this._sortColumns.length > 1 ? d`<span class="sort-index">${i + 1}</span>` : c}
679
713
  </span>
680
- ${this._resizableColumns ? h`<span
714
+ ${this._resizableColumns ? d`<span
681
715
  class="resize-handle"
682
716
  role="separator"
683
717
  aria-orientation="vertical"
684
718
  aria-label="Resize column ${e.label ?? e.name}"
685
- @pointerdown=${(d) => this.startColumnResize(e, d)}
719
+ @pointerdown=${(h) => this.startColumnResize(e, h)}
686
720
  ></span>` : c}
687
721
  </th>
688
722
  `;
689
723
  }
690
- renderRow(e, t, s, r) {
691
- const { row: i, depth: a, isExpanded: o, isPlaceholder: n } = e, d = !n && this._selectedIds.has(t), g = !n && this._cutIds.has(t), _ = !n && this._focusedRowKey === t, p = n ? 0 : this.extractChildCount(i), m = this._tree && !n && p > 0, y = !n && i != null && this.isParentIndeterminate(i);
692
- return h`
724
+ renderRow(e, t, s, i) {
725
+ const { row: a, depth: r, isExpanded: o, isPlaceholder: n } = e, h = !n && this._selectedIds.has(t), _ = !n && this._cutIds.has(t), p = !n && this._focusedRowKey === t, g = n ? 0 : this.extractChildCount(a), f = this._tree && !n && g > 0, v = !n && a != null && this.isParentIndeterminate(a);
726
+ return d`
693
727
  <tr
694
728
  role="row"
695
729
  aria-rowindex=${s + 2}
696
- aria-level=${this._tree ? a + 1 : c}
697
- aria-expanded=${this._tree && p > 0 ? o ? "true" : "false" : c}
730
+ aria-level=${this._tree ? r + 1 : c}
731
+ aria-expanded=${this._tree && g > 0 ? o ? "true" : "false" : c}
698
732
  aria-busy=${n ? "true" : c}
699
- aria-selected=${!n && this._selectionMode !== "none" ? d ? "true" : "false" : c}
733
+ aria-selected=${!n && this._selectionMode !== "none" ? h ? "true" : "false" : c}
700
734
  data-row-key=${t}
701
- data-selected=${d ? "true" : "false"}
702
- data-cut=${g ? "true" : "false"}
703
- data-focused=${_ ? "true" : "false"}
735
+ data-selected=${h ? "true" : "false"}
736
+ data-cut=${_ ? "true" : "false"}
737
+ data-focused=${p ? "true" : "false"}
704
738
  data-placeholder=${n ? "true" : "false"}
705
- data-depth=${this._tree ? String(a) : c}
739
+ data-depth=${this._tree ? String(r) : c}
706
740
  data-clickable=${!n && (this._selectionMode !== "none" || this.hasRowClickListeners()) ? "true" : "false"}
707
- @click=${n ? null : (u) => this.onRowClick(i, t, s, u)}
708
- @dblclick=${n ? null : (u) => this.onRowDblClick(i, t, s, u)}
709
- @contextmenu=${n ? null : (u) => this.onRowContextMenu(i, t, s, u)}
710
- @keydown=${this._tree && !n ? (u) => this.onRowKeydown(i, e.parentId, a, o, p, u) : null}
741
+ @click=${n ? null : (u) => this.onRowClick(a, t, s, u)}
742
+ @dblclick=${n ? null : (u) => this.onRowDblClick(a, t, s, u)}
743
+ @contextmenu=${n ? null : (u) => this.onRowContextMenu(a, t, s, u)}
744
+ @keydown=${this._tree && !n ? (u) => this.onRowKeydown(a, e.parentId, r, o, g, u) : null}
711
745
  >
712
- ${this._tree ? h`<td class="tree-chevron-cell" style=${f({ paddingInlineStart: `${a * this._treeIndent}rem` })}>
713
- ${m ? h`<button
746
+ ${this._tree ? d`<td class="tree-chevron-cell" style=${m({ paddingInlineStart: `${r * this._treeIndent}rem` })}>
747
+ ${f ? d`<button
714
748
  type="button"
715
749
  class="tree-chevron"
716
750
  aria-label=${o ? "Collapse row" : "Expand row"}
717
751
  aria-expanded=${o ? "true" : "false"}
718
752
  data-expanded=${o ? "true" : "false"}
719
- @click=${(u) => this.toggleExpand(i, e.parentId, a, u)}
753
+ @click=${(u) => this.toggleExpand(a, e.parentId, r, u)}
720
754
  >${o ? "▾" : "▸"}</button>` : c}
721
755
  </td>` : c}
722
- ${r ? h`<td class="checkbox-cell" @click=${(u) => u.stopPropagation()}>
723
- ${n ? c : h`<mp-checkbox
756
+ ${i ? d`<td class="checkbox-cell" @click=${(u) => u.stopPropagation()}>
757
+ ${n ? c : d`<mp-checkbox
724
758
  aria-label=${`Select row ${s + 1}`}
725
- .checked=${d}
726
- .indeterminate=${y}
727
- @change=${(u) => this.onRowCheckboxToggle(i, t, s, u)}
759
+ .checked=${h}
760
+ .indeterminate=${v}
761
+ @change=${(u) => this.onRowCheckboxToggle(a, t, s, u)}
728
762
  ></mp-checkbox>`}
729
763
  </td>` : c}
730
- ${this._rowRenderer ? this.renderRowFromRenderer(i, s, { depth: a, isExpanded: o, isPlaceholder: n }) : n ? h`<td colspan=${this._columns.length} class="tree-placeholder-cell" aria-label="Loading">…</td>` : this._columns.map((u) => this.renderCell(i, u, s))}
764
+ ${this._rowRenderer ? this.renderRowFromRenderer(a, s, { depth: r, isExpanded: o, isPlaceholder: n }) : n ? d`<td colspan=${this._columns.length} class="tree-placeholder-cell" aria-label="Loading">…</td>` : this._columns.map((u) => this.renderCell(a, u, s))}
731
765
  </tr>
732
766
  `;
733
767
  }
734
768
  renderRowFromRenderer(e, t, s) {
735
- const r = this._rowRenderer(e, t, s);
736
- if (r == null)
737
- return s.isPlaceholder ? h`<td colspan=${this._columns.length} class="tree-placeholder-cell" aria-label="Loading">…</td>` : this._columns.map((i) => this.renderCell(e, i, t));
738
- if (Array.isArray(r) || P(r)) {
739
- const i = [];
740
- for (const a of r) i.push(a);
741
- return i;
769
+ const i = this._rowRenderer(e, t, s);
770
+ if (i == null)
771
+ return s.isPlaceholder ? d`<td colspan=${this._columns.length} class="tree-placeholder-cell" aria-label="Loading">…</td>` : this._columns.map((a) => this.renderCell(e, a, t));
772
+ if (Array.isArray(i) || z(i)) {
773
+ const a = [];
774
+ for (const r of i) a.push(r);
775
+ return a;
742
776
  }
743
- return r;
777
+ return i;
744
778
  }
745
779
  renderCell(e, t, s) {
746
- const r = t.cellRenderer ? t.cellRenderer(e, t, s) : K(e, t);
747
- return h`<td class=${t.cellClass ?? ""} data-column=${t.name}>${x(r)}</td>`;
780
+ const i = t.cellRenderer ? t.cellRenderer(e, t, s) : M(e, t);
781
+ return d`<td class=${t.cellClass ?? ""} data-column=${t.name}>${w(i)}</td>`;
748
782
  }
749
783
  renderFooter(e) {
750
- const t = Array.from({ length: e }, (s, r) => r + 1);
751
- return h`
784
+ const t = Array.from({ length: e }, (s, i) => i + 1);
785
+ return d`
752
786
  <div class="datatable-footer">
753
787
  <mp-pagination
754
788
  class="datatable-per-page"
@@ -771,7 +805,7 @@ class M extends S {
771
805
  }
772
806
  setPerPage(e) {
773
807
  const t = Math.max(1, Math.floor(e || 1));
774
- this._perPage !== t && (this._perPage = t, this._page = 1, this.requestUpdate(), this.dispatchEvent(
808
+ this._perPage !== t && (this._perPage = t, this._page = 1, this.requestUpdate(), this.scheduleFetchReload(), this.dispatchEvent(
775
809
  new CustomEvent("mp-datatable-per-page-change", {
776
810
  detail: { perPage: t },
777
811
  bubbles: !0,
@@ -786,7 +820,7 @@ class M extends S {
786
820
  ));
787
821
  }
788
822
  getEffectiveData() {
789
- if (this._tree)
823
+ if (this._tree || this.isRootWindowed())
790
824
  return this.getFlatList().map((t) => t.row);
791
825
  let e = this._data;
792
826
  if (this._autoSort && this._sortColumns.length > 0 && (e = b(e, this._sortColumns)), this._pagination && !this.isExternallyPaged()) {
@@ -807,65 +841,66 @@ class M extends S {
807
841
  getFlatList() {
808
842
  if (this._cachedFlatList !== null) return this._cachedFlatList;
809
843
  if (!this._tree) {
810
- const r = (() => {
811
- let i = this._data;
812
- if (this._autoSort && this._sortColumns.length > 0 && (i = b(i, this._sortColumns)), this._pagination && !this.isExternallyPaged()) {
813
- const a = (this._page - 1) * this._perPage;
814
- i = i.slice(a, a + this._perPage);
844
+ if (this.isRootWindowed()) {
845
+ const r = this._totalRecords ?? this._data.length, o = Math.max(1, this._perPage), n = new Array(r);
846
+ for (let h = 0; h < r; h++) {
847
+ const _ = Math.floor(h / o) + 1, p = h % o, g = _ === 1 ? this._data[p] : this._pageCache.get(_)?.[p];
848
+ n[h] = g !== void 0 ? { row: g, key: this._rowKey(g, h), depth: 0, parentId: null, isExpanded: !1, isPlaceholder: !1 } : { row: void 0, key: `__placeholder-flat-${h}`, depth: 0, parentId: null, page: _, isExpanded: !1, isPlaceholder: !0 };
815
849
  }
816
- return i;
850
+ return this._cachedFlatList = n;
851
+ }
852
+ const a = (() => {
853
+ let r = this._data;
854
+ if (this._autoSort && this._sortColumns.length > 0 && (r = b(r, this._sortColumns)), this._pagination && !this.isExternallyPaged()) {
855
+ const o = (this._page - 1) * this._perPage;
856
+ r = r.slice(o, o + this._perPage);
857
+ }
858
+ return r;
817
859
  })();
818
- return this._cachedFlatList = r.map((i, a) => ({
819
- row: i,
820
- key: this._rowKey(i, a),
860
+ return this._cachedFlatList = a.map((r, o) => ({
861
+ row: r,
862
+ key: this._rowKey(r, o),
821
863
  depth: 0,
822
864
  parentId: null,
823
865
  isExpanded: !1,
824
866
  isPlaceholder: !1
825
867
  }));
826
868
  }
827
- const e = [], t = this._autoSort && this._sortColumns.length > 0 ? b(this._data, this._sortColumns) : this._data, s = (r, i, a) => {
828
- for (const o of r) {
829
- const n = this.extractId(o), d = n != null && this._expandedIds.has(n), g = this.extractChildCount(o), _ = this._rowKey(o, e.length);
830
- if (e.push({ row: o, key: _, depth: i, parentId: a, isExpanded: d, isPlaceholder: !1 }), !d || g === 0 || n == null) continue;
831
- const p = this._childCache.get(n);
832
- if (p && p.length > 0) {
833
- const m = this._autoSort && this._sortColumns.length > 0 ? b(p, this._sortColumns) : p;
834
- s(m, i + 1, n);
835
- const y = this._childTotals.get(n) ?? p.length, u = Math.max(0, y - p.length);
836
- for (let v = 0; v < u; v++)
837
- e.push({
838
- row: void 0,
839
- key: `__placeholder-${String(n)}-${p.length + v}`,
840
- depth: i + 1,
841
- parentId: n,
842
- isExpanded: !1,
843
- isPlaceholder: !0
844
- });
845
- } else
846
- for (let m = 0; m < g; m++)
847
- e.push({
848
- row: void 0,
849
- key: `__placeholder-${String(n)}-${m}`,
850
- depth: i + 1,
851
- parentId: n,
852
- isExpanded: !1,
853
- isPlaceholder: !0
854
- });
855
- }
869
+ const e = [], t = Math.max(1, this._perPage), s = (a) => this._autoSort && this._sortColumns.length > 0 ? b(a, this._sortColumns) : a, i = (a, r, o) => {
870
+ const n = this.extractId(a), h = n != null && this._expandedIds.has(n), _ = this.extractChildCount(a);
871
+ if (e.push({ row: a, key: this._rowKey(a, e.length), depth: r, parentId: o, isExpanded: h, isPlaceholder: !1 }), !h || _ === 0 || n == null) return;
872
+ const p = this._childCache.get(n);
873
+ if (p && p.length > 0) {
874
+ for (const f of s(p)) i(f, r + 1, n);
875
+ const g = this._childTotals.get(n) ?? p.length;
876
+ for (let f = 0; f < Math.max(0, g - p.length); f++)
877
+ e.push({ row: void 0, key: `__placeholder-${String(n)}-${p.length + f}`, depth: r + 1, parentId: n, isExpanded: !1, isPlaceholder: !0 });
878
+ } else
879
+ for (let g = 0; g < _; g++)
880
+ e.push({ row: void 0, key: `__placeholder-${String(n)}-${g}`, depth: r + 1, parentId: n, isExpanded: !1, isPlaceholder: !0 });
856
881
  };
857
- return s(t, 0, null), this._cachedFlatList = e;
882
+ if (this.isRootWindowed()) {
883
+ const a = this._totalRecords ?? this._data.length;
884
+ for (let r = 0; r < a; r++) {
885
+ const o = Math.floor(r / t) + 1, n = r % t, h = o === 1 ? this._data[n] : this._pageCache.get(o)?.[n];
886
+ h === void 0 ? e.push({ row: void 0, key: `__placeholder-root-${r}`, depth: 0, parentId: null, page: o, isExpanded: !1, isPlaceholder: !0 }) : i(h, 0, null);
887
+ }
888
+ } else {
889
+ const a = this._autoSort && this._sortColumns.length > 0 ? b(this._data, this._sortColumns) : this._data;
890
+ for (const r of a) i(r, 0, null);
891
+ }
892
+ return this._cachedFlatList = e;
858
893
  }
859
894
  computeVisibleRows() {
860
895
  const e = this.getFlatList(), t = this._tree ? 0 : this._pagination ? (this._page - 1) * this._perPage : 0;
861
- let s = e, r = 0;
896
+ let s = e, i = 0;
862
897
  if (this._virtualScroll) {
863
- const { startIndex: i, endIndex: a } = this._virtualRange;
864
- s = e.slice(i, a), r = i;
898
+ const { startIndex: a, endIndex: r } = this._virtualRange;
899
+ s = e.slice(a, r), i = a;
865
900
  }
866
- return s.map((i, a) => {
867
- const o = t + r + a;
868
- return { row: i.row, rowIndex: o, key: i.key, flat: i };
901
+ return s.map((a, r) => {
902
+ const o = t + i + r;
903
+ return { row: a.row, rowIndex: o, key: a.key, flat: a };
869
904
  });
870
905
  }
871
906
  // ─── Tree-mode helpers ───────────────────────────────────────────────────
@@ -881,13 +916,13 @@ class M extends S {
881
916
  collectDescendantKeys(e) {
882
917
  const t = this.extractId(e), s = t != null ? this._childCache.get(t) : void 0;
883
918
  if (!s) return [];
884
- const r = [];
885
- for (const i of s) {
886
- r.push(this._rowKey(i, -1));
887
- const a = this.collectDescendantKeys(i);
888
- for (const o of a) r.push(o);
919
+ const i = [];
920
+ for (const a of s) {
921
+ i.push(this._rowKey(a, -1));
922
+ const r = this.collectDescendantKeys(a);
923
+ for (const o of r) i.push(o);
889
924
  }
890
- return r;
925
+ return i;
891
926
  }
892
927
  /** Some-but-not-all loaded descendants selected → indeterminate parent checkbox. */
893
928
  isParentIndeterminate(e) {
@@ -906,16 +941,16 @@ class M extends S {
906
941
  if (this._selectionStrategy !== "cascading" || !this._tree)
907
942
  return this._cachedIndeterminateKeys = e;
908
943
  const t = (s) => {
909
- const r = this.extractId(s);
910
- if (r == null) return { selected: 0, total: 0 };
911
- const i = this._childCache.get(r);
912
- if (!i || i.length === 0) return { selected: 0, total: 0 };
913
- let a = 0, o = 0;
914
- for (const n of i) {
915
- const d = this._rowKey(n, -1), g = this._selectedIds.has(d) ? 1 : 0, _ = t(n);
916
- a += g + _.selected, o += 1 + _.total;
944
+ const i = this.extractId(s);
945
+ if (i == null) return { selected: 0, total: 0 };
946
+ const a = this._childCache.get(i);
947
+ if (!a || a.length === 0) return { selected: 0, total: 0 };
948
+ let r = 0, o = 0;
949
+ for (const n of a) {
950
+ const h = this._rowKey(n, -1), _ = this._selectedIds.has(h) ? 1 : 0, p = t(n);
951
+ r += _ + p.selected, o += 1 + p.total;
917
952
  }
918
- return o > 0 && a > 0 && a < o && e.add(this._rowKey(s, -1)), { selected: a, total: o };
953
+ return o > 0 && r > 0 && r < o && e.add(this._rowKey(s, -1)), { selected: r, total: o };
919
954
  };
920
955
  for (const s of this._data) t(s);
921
956
  return this._cachedIndeterminateKeys = e;
@@ -925,19 +960,19 @@ class M extends S {
925
960
  * children aren't cached yet so the wrapper can bridge to the consumer's
926
961
  * `[fetch]` callback. Always fires `expanded-ids-change`.
927
962
  */
928
- toggleExpand(e, t, s, r) {
929
- r.stopPropagation(), r.preventDefault();
930
- const i = this.extractId(e);
931
- if (i == null) return;
932
- const a = new Set(this._expandedIds);
963
+ toggleExpand(e, t, s, i) {
964
+ i.stopPropagation(), i.preventDefault();
965
+ const a = this.extractId(e);
966
+ if (a == null) return;
967
+ const r = new Set(this._expandedIds);
933
968
  let o;
934
- a.has(i) ? (a.delete(i), o = !1) : (a.add(i), o = !0), this._expandedIds = a, o ? (this.dispatchEvent(
969
+ r.has(a) ? (r.delete(a), o = !1) : (r.add(a), o = !0), this._expandedIds = r, o ? (this.dispatchEvent(
935
970
  new CustomEvent("mp-datatable-row-expand", {
936
971
  detail: { row: e, depth: s, parentId: t },
937
972
  bubbles: !0,
938
973
  composed: !0
939
974
  })
940
- ), this.extractChildCount(e) > 0 && !this._childCache.has(i) && !this._pendingFetches.has(i) && this.requestChildrenFetch(i)) : this.dispatchEvent(
975
+ ), this.extractChildCount(e) > 0 && !this._childCache.has(a) && !this._pendingFetches.has(a) && this.fetchChildren(a)) : this.dispatchEvent(
941
976
  new CustomEvent("mp-datatable-row-collapse", {
942
977
  detail: { row: e, depth: s, parentId: t },
943
978
  bubbles: !0,
@@ -954,93 +989,140 @@ class M extends S {
954
989
  })
955
990
  );
956
991
  }
957
- /** Emit a fetch-request event the wrapper will bridge to the consumer's `[fetch]`. */
958
- requestChildrenFetch(e) {
959
- e != null && this._pendingFetches.add(e), this.dispatchEvent(
960
- new CustomEvent("mp-datatable-fetch-request", {
961
- detail: {
962
- parentId: e,
963
- page: 1,
964
- perPage: this._perPage,
965
- sortColumns: [...this._sortColumns]
966
- },
967
- bubbles: !0,
968
- composed: !0
969
- })
970
- );
992
+ // ─── Fetch-callback driver (the WC owns the whole server-paged loop) ─────
993
+ /**
994
+ * Fetch a windowed root page (≥ 2) into the page cache. Called when a root
995
+ * placeholder scrolls into view. Keyed on the requested page, so a server
996
+ * that echoes a different page number can't deadlock the window.
997
+ * Generation-guarded against responses that land after an invalidation.
998
+ */
999
+ async fetchWindowPage(e) {
1000
+ if (!this._fetch || e <= 1) return;
1001
+ this._pendingPageFetches.add(e);
1002
+ const t = this._fetchGeneration;
1003
+ try {
1004
+ const s = await this._fetch({ parentId: null, page: e, perPage: this._perPage, sortColumns: [...this._sortColumns] });
1005
+ if (t !== this._fetchGeneration || !this._fetch) return;
1006
+ this._pendingPageFetches.delete(e), this._pageCache.set(e, [...s?.data ?? []]);
1007
+ const i = s?.totalRecords == null ? null : Math.max(0, Math.floor(s.totalRecords));
1008
+ i != null && (this._totalRecords = i), this.requestUpdate();
1009
+ } catch (s) {
1010
+ this._pendingPageFetches.delete(e), console.error("[mp-datatable] fetch failed for root page", e, s);
1011
+ }
1012
+ }
1013
+ /**
1014
+ * Fetch a node's children into the child cache. Called on expand or when a
1015
+ * child placeholder scrolls into view. Generation-guarded.
1016
+ */
1017
+ async fetchChildren(e) {
1018
+ if (!this._fetch || e == null) return;
1019
+ this._pendingFetches.add(e);
1020
+ const t = this._fetchGeneration;
1021
+ try {
1022
+ const s = await this._fetch({ parentId: e, page: 1, perPage: this._perPage, sortColumns: [...this._sortColumns] });
1023
+ if (t !== this._fetchGeneration || !this._fetch) return;
1024
+ this._pendingFetches.delete(e), this._childCache.set(e, [...s?.data ?? []]), this._childTotals.set(e, s?.totalRecords ?? s?.data?.length ?? 0), this.requestUpdate();
1025
+ } catch (s) {
1026
+ this._pendingFetches.delete(e), console.error("[mp-datatable] fetch failed for children of", e, s);
1027
+ }
971
1028
  }
972
1029
  /**
973
- * Public method called by the framework wrapper after the consumer's
974
- * `[fetch]` callback resolves. Populates the cache + total for the parent,
975
- * clears the pending flag, and rerenders so placeholders disappear.
1030
+ * Fetch a single page of roots and make it the page-1 data (initial load and
1031
+ * non-virtual pagination). The grand total is read from the response —
1032
+ * consumers never set `totalRecords`. Generation-guarded against stale loads.
976
1033
  */
977
- setFetchResponse(e, t) {
978
- e != null && (this._pendingFetches.delete(e), this._childCache.set(e, [...t.data]), this._childTotals.set(e, t.totalRecords), this.requestUpdate());
1034
+ async loadPage(e) {
1035
+ if (!this._fetch) return;
1036
+ const t = this._fetchGeneration;
1037
+ let s;
1038
+ try {
1039
+ s = await this._fetch({ parentId: null, page: e, perPage: this._perPage, sortColumns: [...this._sortColumns] });
1040
+ } catch (a) {
1041
+ console.error("[mp-datatable] fetch failed for page", e, a);
1042
+ return;
1043
+ }
1044
+ if (t !== this._fetchGeneration || !this._fetch) return;
1045
+ this._data = [...s?.data ?? []];
1046
+ const i = s?.totalRecords == null ? null : Math.max(0, Math.floor(s.totalRecords));
1047
+ this._totalRecords = i, this._initialFetchDone = !0, this.requestUpdate();
979
1048
  }
980
- /** Drop cached children for one parent (or all). Used on sort change / refresh. */
981
- invalidateChildren(e) {
982
- e === void 0 ? (this._childCache.clear(), this._childTotals.clear(), this._pendingFetches.clear()) : (this._childCache.delete(e), this._childTotals.delete(e), this._pendingFetches.delete(e)), this.requestUpdate();
1049
+ /**
1050
+ * Coalesce sort/perPage/page changes (which arrive both as user actions and
1051
+ * as echoed property pushes) into a single reload. A microtask debounces the
1052
+ * burst; a `{sort,perPage,page}` change-key skips echoes that didn't actually
1053
+ * change anything.
1054
+ */
1055
+ scheduleFetchReload() {
1056
+ !this._fetch || this._reloadScheduled || (this._reloadScheduled = !0, queueMicrotask(() => {
1057
+ if (this._reloadScheduled = !1, !this._fetch) return;
1058
+ const e = JSON.stringify({
1059
+ s: this._sortColumns,
1060
+ pp: this._perPage,
1061
+ p: this._virtualScroll ? 1 : this._page
1062
+ });
1063
+ this._initialFetchDone && e === this._lastReloadKey || (this._lastReloadKey = e, this._fetchGeneration++, this._pageCache.clear(), this._pendingPageFetches.clear(), this._childCache.clear(), this._childTotals.clear(), this._pendingFetches.clear(), this.loadPage(this._virtualScroll ? 1 : this._page));
1064
+ }));
983
1065
  }
984
1066
  /** Keyboard handling on a tree-mode row. Arrow keys + Enter/Space toggle expansion. */
985
- onRowKeydown(e, t, s, r, i, a) {
986
- a.key === "ArrowRight" && i > 0 && !r ? this.toggleExpand(e, t, s, a) : a.key === "ArrowLeft" && r ? this.toggleExpand(e, t, s, a) : (a.key === "Enter" || a.key === " ") && i > 0 && this.toggleExpand(e, t, s, a);
1067
+ onRowKeydown(e, t, s, i, a, r) {
1068
+ r.key === "ArrowRight" && a > 0 && !i ? this.toggleExpand(e, t, s, r) : r.key === "ArrowLeft" && i ? this.toggleExpand(e, t, s, r) : (r.key === "Enter" || r.key === " ") && a > 0 && this.toggleExpand(e, t, s, r);
987
1069
  }
988
1070
  hasRowClickListeners() {
989
1071
  return !0;
990
1072
  }
991
1073
  onHeaderClick(e, t) {
992
1074
  if (!(e.sortable ?? !0) || t.target.closest(".resize-handle")) return;
993
- const i = R(this._sortColumns, e.name, t.shiftKey);
994
- this._sortColumns = i, this.requestUpdate(), this.dispatchEvent(
1075
+ const a = I(this._sortColumns, e.name, t.shiftKey);
1076
+ this._sortColumns = a, this._page = 1, this.requestUpdate(), this.scheduleFetchReload(), this.dispatchEvent(
995
1077
  new CustomEvent("mp-datatable-sort-change", {
996
- detail: { sortColumns: i },
1078
+ detail: { sortColumns: a },
997
1079
  bubbles: !0,
998
1080
  composed: !0
999
1081
  })
1000
1082
  );
1001
1083
  }
1002
- onRowClick(e, t, s, r) {
1003
- r.target.closest('input[type="checkbox"]') || (this._focusedRowKey = t, this.handleSelectionOnClick(t, r), this.requestUpdate(), this.dispatchEvent(
1084
+ onRowClick(e, t, s, i) {
1085
+ i.target.closest('input[type="checkbox"]') || (this._focusedRowKey = t, this.handleSelectionOnClick(t, i), this.requestUpdate(), this.dispatchEvent(
1004
1086
  new CustomEvent("mp-datatable-row-click", {
1005
- detail: { row: e, rowIndex: s, rowKey: t, originalEvent: r },
1087
+ detail: { row: e, rowIndex: s, rowKey: t, originalEvent: i },
1006
1088
  bubbles: !0,
1007
1089
  composed: !0
1008
1090
  })
1009
1091
  ));
1010
1092
  }
1011
- onRowDblClick(e, t, s, r) {
1093
+ onRowDblClick(e, t, s, i) {
1012
1094
  this.dispatchEvent(
1013
1095
  new CustomEvent("mp-datatable-row-dblclick", {
1014
- detail: { row: e, rowIndex: s, rowKey: t, originalEvent: r },
1096
+ detail: { row: e, rowIndex: s, rowKey: t, originalEvent: i },
1015
1097
  bubbles: !0,
1016
1098
  composed: !0
1017
1099
  })
1018
1100
  );
1019
1101
  }
1020
- onRowContextMenu(e, t, s, r) {
1102
+ onRowContextMenu(e, t, s, i) {
1021
1103
  this._selectionMode !== "none" && !this._selectedIds.has(t) && (this._selectedIds = /* @__PURE__ */ new Set([t]), this._focusedRowKey = t, this.emitSelectionChange(), this.requestUpdate()), this.dispatchEvent(
1022
1104
  new CustomEvent("mp-datatable-row-contextmenu", {
1023
- detail: { row: e, rowIndex: s, rowKey: t, originalEvent: r },
1105
+ detail: { row: e, rowIndex: s, rowKey: t, originalEvent: i },
1024
1106
  bubbles: !0,
1025
1107
  composed: !0,
1026
1108
  cancelable: !0
1027
1109
  })
1028
1110
  );
1029
1111
  }
1030
- onRowCheckboxToggle(e, t, s, r) {
1112
+ onRowCheckboxToggle(e, t, s, i) {
1031
1113
  if (this._selectionMode !== "none") {
1032
1114
  if (this._selectionMode === "single")
1033
1115
  this._selectedIds = /* @__PURE__ */ new Set([t]);
1034
1116
  else {
1035
- const i = new Set(this._selectedIds), a = !i.has(t);
1036
- if (a ? i.add(t) : i.delete(t), this._tree && this._selectionStrategy === "cascading" && e != null) {
1117
+ const a = new Set(this._selectedIds), r = !a.has(t);
1118
+ if (r ? a.add(t) : a.delete(t), this._tree && this._selectionStrategy === "cascading" && e != null) {
1037
1119
  const o = this.collectDescendantKeys(e);
1038
- if (a)
1039
- for (const n of o) i.add(n);
1120
+ if (r)
1121
+ for (const n of o) a.add(n);
1040
1122
  else
1041
- for (const n of o) i.delete(n);
1123
+ for (const n of o) a.delete(n);
1042
1124
  }
1043
- this._selectedIds = i;
1125
+ this._selectedIds = a;
1044
1126
  }
1045
1127
  this.emitSelectionChange(), this.requestUpdate();
1046
1128
  }
@@ -1062,9 +1144,9 @@ class M extends S {
1062
1144
  return;
1063
1145
  }
1064
1146
  if (t.shiftKey && this._focusedRowKey && this._focusedRowKey !== e) {
1065
- const s = this.computeVisibleRows(), r = s.findIndex((a) => a.key === this._focusedRowKey), i = s.findIndex((a) => a.key === e);
1066
- if (r >= 0 && i >= 0) {
1067
- const [a, o] = r < i ? [r, i] : [i, r], n = s.slice(a, o + 1).map((d) => d.key);
1147
+ const s = this.computeVisibleRows(), i = s.findIndex((r) => r.key === this._focusedRowKey), a = s.findIndex((r) => r.key === e);
1148
+ if (i >= 0 && a >= 0) {
1149
+ const [r, o] = i < a ? [i, a] : [a, i], n = s.slice(r, o + 1).map((h) => h.key);
1068
1150
  this._selectedIds = /* @__PURE__ */ new Set([...this._selectedIds, ...n]), this.emitSelectionChange();
1069
1151
  return;
1070
1152
  }
@@ -1078,17 +1160,33 @@ class M extends S {
1078
1160
  }
1079
1161
  }
1080
1162
  emitSelectionChange() {
1163
+ const e = [...this._selectedIds];
1081
1164
  this.dispatchEvent(
1082
1165
  new CustomEvent("mp-datatable-selection-change", {
1083
- detail: { selectedIds: [...this._selectedIds] },
1166
+ detail: { selectedIds: e, selectedRows: this.resolveRows(e) },
1084
1167
  bubbles: !0,
1085
1168
  composed: !0
1086
1169
  })
1087
1170
  );
1088
1171
  }
1172
+ /**
1173
+ * Resolve row keys → row objects across every loaded source (page-1 `_data`,
1174
+ * fetched windows in `_pageCache`, tree children in `_childCache`). One pass
1175
+ * builds a key→row index; unresolvable ids are skipped.
1176
+ */
1177
+ resolveRows(e) {
1178
+ if (e.length === 0) return [];
1179
+ const t = /* @__PURE__ */ new Map(), s = (i) => {
1180
+ for (const a of i) t.set(this._rowKey(a, -1), a);
1181
+ };
1182
+ s(this._data);
1183
+ for (const i of this._pageCache.values()) s(i);
1184
+ for (const i of this._childCache.values()) s(i);
1185
+ return e.map((i) => t.get(i)).filter((i) => i !== void 0);
1186
+ }
1089
1187
  gotoPage(e) {
1090
1188
  const t = this._totalRecords ?? this._data.length, s = Math.max(1, Math.ceil(t / this._perPage));
1091
- this._page = Math.max(1, Math.min(s, e)), this.requestUpdate(), this.dispatchEvent(
1189
+ this._page = Math.max(1, Math.min(s, e)), this.requestUpdate(), this.scheduleFetchReload(), this.dispatchEvent(
1092
1190
  new CustomEvent("mp-datatable-page-change", {
1093
1191
  detail: { page: this._page },
1094
1192
  bubbles: !0,
@@ -1099,27 +1197,27 @@ class M extends S {
1099
1197
  startColumnResize(e, t) {
1100
1198
  if (!this._resizableColumns) return;
1101
1199
  t.preventDefault(), t.stopPropagation();
1102
- const s = t.currentTarget, r = s.closest("th");
1103
- if (!r) return;
1104
- const i = r.getBoundingClientRect().width;
1105
- this.resizeState = { columnName: e.name, startX: t.clientX, startWidth: i, handle: s }, s.classList.add("active"), s.setPointerCapture(t.pointerId), s.addEventListener("pointermove", this.onColumnResizeMove), s.addEventListener("pointerup", this.onColumnResizeEnd), s.addEventListener("pointercancel", this.onColumnResizeEnd);
1200
+ const s = t.currentTarget, i = s.closest("th");
1201
+ if (!i) return;
1202
+ const a = i.getBoundingClientRect().width;
1203
+ this.resizeState = { columnName: e.name, startX: t.clientX, startWidth: a, handle: s }, s.classList.add("active"), s.setPointerCapture(t.pointerId), s.addEventListener("pointermove", this.onColumnResizeMove), s.addEventListener("pointerup", this.onColumnResizeEnd), s.addEventListener("pointercancel", this.onColumnResizeEnd);
1106
1204
  }
1107
1205
  }
1108
- function K(l, e) {
1206
+ function M(l, e) {
1109
1207
  if (l == null || typeof l != "object") return "";
1110
1208
  const t = l[e.name];
1111
1209
  return t == null ? "" : String(t);
1112
1210
  }
1113
- function P(l) {
1211
+ function z(l) {
1114
1212
  return l != null && typeof l != "string" && typeof l[Symbol.iterator] == "function";
1115
1213
  }
1116
- function x(l) {
1214
+ function w(l) {
1117
1215
  return l == null || l === !1 ? c : (l instanceof Node || typeof l == "object" && "_$litType$" in l, l);
1118
1216
  }
1119
- typeof customElements < "u" && !customElements.get("mp-datatable") && customElements.define("mp-datatable", M);
1217
+ typeof customElements < "u" && !customElements.get("mp-datatable") && customElements.define("mp-datatable", E);
1120
1218
  export {
1121
- M,
1122
- R as c,
1123
- I as d,
1219
+ E as M,
1220
+ I as c,
1221
+ R as d,
1124
1222
  b as s
1125
1223
  };
@@ -1,4 +1,4 @@
1
- import { M as s, c as e, d as o, s as r } from "../chunks/mp-datatable-Con0yQue.mjs";
1
+ import { M as s, c as e, d as o, s as r } from "../chunks/mp-datatable-mZ6EkXmp.mjs";
2
2
  export {
3
3
  s as MpDatatable,
4
4
  e as computeNextSort,
@@ -1,6 +1,6 @@
1
1
  import { LitElement, TemplateResult } from 'lit';
2
2
  import { SortColumn } from '../sort';
3
- import { DatatableColumnDef, RowKey, RowRenderer, TreeFetchResponse, TreeIdKey, TreeSelectionStrategy } from '../types';
3
+ import { DatatableColumnDef, RowKey, RowRenderer, DatatableFetch, TreeIdKey, TreeSelectionStrategy } from '../types';
4
4
  export type DatatableSelectionMode = 'none' | 'single' | 'multiple';
5
5
  export interface RowEventDetail<T = unknown> {
6
6
  row: T;
@@ -11,8 +11,16 @@ export interface RowEventDetail<T = unknown> {
11
11
  export interface SortChangeEventDetail {
12
12
  sortColumns: SortColumn[];
13
13
  }
14
- export interface SelectionChangeEventDetail {
14
+ export interface SelectionChangeEventDetail<T = unknown> {
15
15
  selectedIds: string[];
16
+ /**
17
+ * The selected row objects, resolved from the WC's loaded data (page 1 +
18
+ * fetched windows + tree children). Since the WC owns the data when fetching,
19
+ * consumers can't resolve ids → rows themselves — this is how a consumer gets
20
+ * the actual selected records. An id whose row isn't currently loaded is
21
+ * omitted (shouldn't happen: you can only select a row you can see).
22
+ */
23
+ selectedRows: T[];
16
24
  }
17
25
  /**
18
26
  * `<mp-datatable>` — property-driven data grid.
@@ -72,6 +80,19 @@ export declare class MpDatatable extends LitElement {
72
80
  private _childTotals;
73
81
  /** Parents with an in-flight fetch; suppresses re-requests. */
74
82
  private _pendingFetches;
83
+ /** Loaded rows per 1-based page (pages ≥ 2; page 1 is `_data`). */
84
+ private _pageCache;
85
+ /** Pages with an in-flight fetch; suppresses re-requests. */
86
+ private _pendingPageFetches;
87
+ private _fetch;
88
+ /** Bumped on invalidation; in-flight responses from an older generation are dropped. */
89
+ private _fetchGeneration;
90
+ /** Guards the one-time initial page-1 load. Reset by `invalidateData`. */
91
+ private _initialFetchDone;
92
+ /** Coalesces multiple setter calls in one flush into a single reload. */
93
+ private _reloadScheduled;
94
+ /** Last loaded {sort,perPage,page} signature — echoes with the same key skip. */
95
+ private _lastReloadKey;
75
96
  /** Per-render memo of `getFlatList()`. Invalidated in `willUpdate`. */
76
97
  private _cachedFlatList;
77
98
  /** Per-render memo of the set of row keys whose loaded subtree is partially selected. */
@@ -99,6 +120,14 @@ export declare class MpDatatable extends LitElement {
99
120
  set columns(value: DatatableColumnDef[]);
100
121
  get data(): unknown[];
101
122
  set data(value: unknown[]);
123
+ /**
124
+ * High-level fetch callback. When set, the WC owns the entire server-paged
125
+ * loop and the consumer provides nothing else — no page-1 seeding via `data`,
126
+ * no separate `totalRecords`, no event bridge. Works with any framework or
127
+ * none (`el.fetch = fn`). Setting it kicks off the initial page-1 load.
128
+ */
129
+ get fetch(): DatatableFetch | null;
130
+ set fetch(value: DatatableFetch | null);
102
131
  get sortColumns(): SortColumn[];
103
132
  set sortColumns(value: SortColumn[]);
104
133
  get selectionMode(): DatatableSelectionMode;
@@ -149,14 +178,22 @@ export declare class MpDatatable extends LitElement {
149
178
  get perPageOptions(): number[];
150
179
  set perPageOptions(value: number[]);
151
180
  /**
152
- * Caller-supplied total record count for external paging. Set this when
153
- * `[fetch]` returns one page at a time so the pagination footer can show
154
- * the correct total. Leave as `null` (default) to use `_data.length`.
181
+ * Read-only grand total. Derived by the WC from the `fetch` response (server
182
+ * paging) or `_data.length` (static data) — consumers never set it. Exposed
183
+ * so a consumer can render "row X of N" if it wants.
155
184
  */
156
185
  get totalRecords(): number | null;
157
- set totalRecords(value: number | null);
158
186
  /** True when the consumer is paging externally (totalRecords exceeds the in-memory rows). */
159
187
  private isExternallyPaged;
188
+ /**
189
+ * True when virtual scrolling is driving lazy windowed fetches at the **root**
190
+ * level: the consumer pages externally and the WC pulls root pages ≥ 2 on
191
+ * demand. Applies to BOTH flat mode (the rows are the roots) and tree mode
192
+ * (the top-level rows; their children are windowed separately, keyed by
193
+ * parentId). When false (single page or no virtual scroll) the WC falls back
194
+ * to the trivial mapping of `_data`.
195
+ */
196
+ private isRootWindowed;
160
197
  attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
161
198
  private _resizableColumns;
162
199
  get resizableColumns(): boolean;
@@ -183,6 +220,14 @@ export declare class MpDatatable extends LitElement {
183
220
  * and isn't already in-flight. Emit a fetch-request per such parent.
184
221
  */
185
222
  private maybeFetchPlaceholdersInViewport;
223
+ /**
224
+ * Flat-window counterpart of `maybeFetchPlaceholdersInViewport`: scan the
225
+ * visible range for flat placeholder rows, collect the distinct pages they
226
+ * belong to that aren't cached or already in-flight, and request each once.
227
+ * Page 1 is never requested here — it lives in `_data` (seeded by the
228
+ * wrapper's first-page fetch).
229
+ */
230
+ private maybeFetchPagesInViewport;
186
231
  render(): TemplateResult;
187
232
  private getVirtualSpacerHeights;
188
233
  private renderHeader;
@@ -224,16 +269,31 @@ export declare class MpDatatable extends LitElement {
224
269
  */
225
270
  private toggleExpand;
226
271
  private emitExpandedIdsChange;
227
- /** Emit a fetch-request event the wrapper will bridge to the consumer's `[fetch]`. */
228
- private requestChildrenFetch;
229
272
  /**
230
- * Public method called by the framework wrapper after the consumer's
231
- * `[fetch]` callback resolves. Populates the cache + total for the parent,
232
- * clears the pending flag, and rerenders so placeholders disappear.
273
+ * Fetch a windowed root page (≥ 2) into the page cache. Called when a root
274
+ * placeholder scrolls into view. Keyed on the requested page, so a server
275
+ * that echoes a different page number can't deadlock the window.
276
+ * Generation-guarded against responses that land after an invalidation.
233
277
  */
234
- setFetchResponse(parentId: unknown | null, response: TreeFetchResponse): void;
235
- /** Drop cached children for one parent (or all). Used on sort change / refresh. */
236
- invalidateChildren(parentId?: unknown): void;
278
+ private fetchWindowPage;
279
+ /**
280
+ * Fetch a node's children into the child cache. Called on expand or when a
281
+ * child placeholder scrolls into view. Generation-guarded.
282
+ */
283
+ private fetchChildren;
284
+ /**
285
+ * Fetch a single page of roots and make it the page-1 data (initial load and
286
+ * non-virtual pagination). The grand total is read from the response —
287
+ * consumers never set `totalRecords`. Generation-guarded against stale loads.
288
+ */
289
+ private loadPage;
290
+ /**
291
+ * Coalesce sort/perPage/page changes (which arrive both as user actions and
292
+ * as echoed property pushes) into a single reload. A microtask debounces the
293
+ * burst; a `{sort,perPage,page}` change-key skips echoes that didn't actually
294
+ * change anything.
295
+ */
296
+ private scheduleFetchReload;
237
297
  /** Keyboard handling on a tree-mode row. Arrow keys + Enter/Space toggle expansion. */
238
298
  private onRowKeydown;
239
299
  private hasRowClickListeners;
@@ -252,6 +312,12 @@ export declare class MpDatatable extends LitElement {
252
312
  private onDeselectAll;
253
313
  private handleSelectionOnClick;
254
314
  private emitSelectionChange;
315
+ /**
316
+ * Resolve row keys → row objects across every loaded source (page-1 `_data`,
317
+ * fetched windows in `_pageCache`, tree children in `_childCache`). One pass
318
+ * builds a key→row index; unresolvable ids are skipped.
319
+ */
320
+ private resolveRows;
255
321
  private gotoPage;
256
322
  private resizeState;
257
323
  private startColumnResize;
@@ -1,6 +1,6 @@
1
1
  export { MpDatatable } from './components';
2
2
  export type { DatatableSelectionMode, RowEventDetail, SortChangeEventDetail, SelectionChangeEventDetail, } from './components';
3
- export type { DatatableColumnDef, CellContent, CellRenderer, HeaderRenderer, RowKey, RowRenderer, RowRenderContext, TreeIdKey, TreeSelectionStrategy, TreeFetchRequestDetail, TreeFetchResponse, TreeRowExpandDetail, TreeExpandedIdsChangeDetail, } from './types';
3
+ export type { DatatableColumnDef, CellContent, CellRenderer, HeaderRenderer, RowKey, RowRenderer, RowRenderContext, TreeIdKey, TreeSelectionStrategy, DatatableFetchRequest, DatatableFetchResponse, DatatableFetch, TreeRowExpandDetail, TreeExpandedIdsChangeDetail, } from './types';
4
4
  export type { SortColumn, SortDirection } from './sort';
5
5
  export { computeNextSort, sortRows } from './sort';
6
6
  export { datatableStyles } from './styles';
@@ -1,2 +1,2 @@
1
1
  export type { DatatableColumnDef, CellContent, CellRenderer, HeaderRenderer, RowKey, RowRenderer, RowRenderContext, } from './column-def';
2
- export type { TreeFetchRequestDetail, TreeFetchResponse, TreeRowExpandDetail, TreeExpandedIdsChangeDetail, TreeIdKey, TreeSelectionStrategy, } from './tree';
2
+ export type { DatatableFetchRequest, DatatableFetchResponse, DatatableFetch, TreeRowExpandDetail, TreeExpandedIdsChangeDetail, TreeIdKey, TreeSelectionStrategy, } from './tree';
@@ -14,24 +14,34 @@ export type TreeIdKey<T = unknown> = keyof T | string | ((row: T) => unknown);
14
14
  */
15
15
  export type TreeSelectionStrategy = 'flat' | 'cascading';
16
16
  /**
17
- * Detail of `mp-datatable-fetch-request` — emitted by the WC when it needs
18
- * data for a parent (tree mode, lazy children). The wrapper bridges this to
19
- * the consumer's `[fetch]` callback and calls `setFetchResponse()` with the
20
- * result. `parentId === null` means roots.
17
+ * Request passed to the `fetch` callback. `parentId === null` is a root window
18
+ * (flat rows, or the tree's top level — pages ≥ 2 are windowed lazily); a
19
+ * non-null `parentId` is a tree node's children.
21
20
  */
22
- export interface TreeFetchRequestDetail {
21
+ export interface DatatableFetchRequest {
23
22
  parentId: unknown | null;
24
23
  page: number;
25
24
  perPage: number;
26
25
  sortColumns: SortColumn[];
27
26
  }
28
- /** Response shape consumed by `setFetchResponse()`. */
29
- export interface TreeFetchResponse<T = unknown> {
27
+ /**
28
+ * Response returned from the `fetch` callback. Only `data` + `totalRecords` are
29
+ * required — the WC already knows the page/perPage it asked for, and derives
30
+ * the grand total from `totalRecords`, so consumers never set a separate
31
+ * `totalRecords` property.
32
+ */
33
+ export interface DatatableFetchResponse<T = unknown> {
30
34
  data: T[];
31
35
  totalRecords: number;
32
- page: number;
33
- perPage: number;
34
36
  }
37
+ /**
38
+ * High-level fetch callback — the ONLY server-paging API. Set `el.fetch` and
39
+ * the web component owns the whole loop: initial page, on-demand windows, tree
40
+ * children, pagination, and sort/perPage reloads, deriving `totalRecords` from
41
+ * the response. Works standalone (no framework) — `el.fetch = fn` is all a
42
+ * plain web-components consumer needs.
43
+ */
44
+ export type DatatableFetch<T = unknown> = (req: DatatableFetchRequest) => Promise<DatatableFetchResponse<T>>;
35
45
  export interface TreeRowExpandDetail<T = unknown> {
36
46
  row: T;
37
47
  depth: number;
@@ -5,7 +5,7 @@ import { createRef as v, ref as w } from "lit/directives/ref.js";
5
5
  import { styleMap as y } from "lit/directives/style-map.js";
6
6
  import "../chunks/mp-splitter-C8cGCmac.mjs";
7
7
  import "../chunks/mp-treeview-C48F63xb.mjs";
8
- import "../chunks/mp-datatable-Con0yQue.mjs";
8
+ import "../chunks/mp-datatable-mZ6EkXmp.mjs";
9
9
  const $ = b(`:host {
10
10
  display: flex;
11
11
  flex-direction: column;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mintplayer/web-components",
3
- "version": "1.6.0",
3
+ "version": "2.0.1",
4
4
  "description": "Framework-agnostic Lit web components for the @mintplayer/bootstrap design system. Consumed by @mintplayer/ng-bootstrap, @mintplayer/react-bootstrap, and @mintplayer/vue-bootstrap.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -516,7 +516,7 @@ class g extends u {
516
516
  );
517
517
  }
518
518
  syncTreeviewSelection() {
519
- const e = this.renderRoot.querySelector("mp-treeview");
519
+ const e = this.renderRoot?.querySelector("mp-treeview");
520
520
  e && (e.selectedIds = [...this._selected.keys()]);
521
521
  }
522
522
  get nodeRenderer() {