@optionfactory/fml 9.0.0-rc31 → 9.0.0-rc32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/fml.iife.js CHANGED
@@ -10875,6 +10875,10 @@ var fml = (function (exports) {
10875
10875
  * @typedef {{ data: any[], size: number }} TablePageResponse the rows of the
10876
10876
  * requested page and the total number of rows across every page
10877
10877
  */
10878
+ /**
10879
+ * @typedef {{ count: Element, appending: Element, failure: Element, error: Element }} TableStatus the pieces
10880
+ * of the status bar `paging="infinite"` and `paging="virtual"` show in place of the pager
10881
+ */
10878
10882
  /**
10879
10883
  * @typedef {{ load(pageRequest: TablePageRequest, sortRequest: TableSortRequest|null, filterRequest: Record<string, any>): Promise<TablePageResponse> }} TableRowLoader
10880
10884
  */
@@ -11347,6 +11351,21 @@ var fml = (function (exports) {
11347
11351
  * for it. Without it the table shows an initial panel until `load`,
11348
11352
  * `reload` or `resetWithFilter` is called.
11349
11353
  *
11354
+ * `paging="infinite"`, read once at the upgrade, replaces the pager with a
11355
+ * status bar saying how many rows of how many are shown, with a reload
11356
+ * button. A load still replaces the rows with one page, scrolling the rows
11357
+ * back to the top; from then on, whenever a row of the last half page
11358
+ * comes into view, the next page is asked with the same size, sort and
11359
+ * filters and appended (see `load`). `reload`, a sort, a filter submit and a
11360
+ * size change start over from the first page.
11361
+ *
11362
+ * `paging="virtual"` shows the same status bar, saying which rows of how many
11363
+ * are in view, and keeps in the page only the page in view and one on either
11364
+ * side of it, the others standing in as empty space sized on the height of
11365
+ * the rows. The rows must scroll inside the table, as `ful-fill` makes them:
11366
+ * a table whose rows the page scrolls appends as `paging="infinite"` does,
11367
+ * and warns. See `load` and `reload`.
11368
+ *
11350
11369
  * Inside the table, and not inside a `ful-table` nested in it, a
11351
11370
  * `page:requested` loads that page with the current size,
11352
11371
  * sort and filters; a `sort:requested` loads the current page with the new
@@ -11362,13 +11381,14 @@ var fml = (function (exports) {
11362
11381
  */
11363
11382
  class Table extends ParsedElement {
11364
11383
  /** Read once at the upgrade. */
11365
- static attributes = ['loader', 'autoload:presence'];
11384
+ static attributes = ['loader', 'autoload:presence', 'paging'];
11366
11385
  /** These stay live after the upgrade: see `pageSize`, `src` and `method`. */
11367
11386
  static observed = ['page-size:number', 'src', 'method'];
11368
11387
  static slots = true;
11369
11388
  static config = {
11370
11389
  searchIcon: 'search',
11371
11390
  emptyIcon: 'inbox',
11391
+ reloadIcon: 'arrow-clockwise',
11372
11392
  };
11373
11393
  static template = `
11374
11394
  <ful-form data-tpl-if="slots.filters">
@@ -11378,7 +11398,9 @@ var fml = (function (exports) {
11378
11398
  <table>
11379
11399
  <caption data-tpl-if="slots.caption">{{{{ slots.caption }}}}</caption>
11380
11400
  <thead></thead>
11401
+ <tbody data-tpl-if="virtual" data-ref="before" aria-hidden="true"><tr><td data-tpl-colspan="schema.length"></td></tr></tbody>
11381
11402
  <tbody></tbody>
11403
+ <tbody data-tpl-if="virtual" data-ref="after" aria-hidden="true"><tr><td data-tpl-colspan="schema.length"></td></tr></tbody>
11382
11404
  <tbody data-ref="initial">
11383
11405
  <tr>
11384
11406
  <td data-tpl-colspan="schema.length">
@@ -11422,7 +11444,16 @@ var fml = (function (exports) {
11422
11444
  </tfoot>
11423
11445
  </table>
11424
11446
  </ful-table-wrapper>
11425
- <ful-pagination current="0" total="1"></ful-pagination>
11447
+ <ful-pagination data-tpl-if="!scrolled" current="0" total="1"></ful-pagination>
11448
+ <ful-table-status data-tpl-if="scrolled">
11449
+ <span data-ref="count"></span>
11450
+ <ful-spinner data-ref="appending" role="status" hidden><span class="ful-sr-only">{{ #l10n:t('spinner.loading') }}</span></ful-spinner>
11451
+ <div data-ref="append-failure" role="alert" hidden>
11452
+ <span>{{ #l10n:t('table.error') }} <span data-ref="append-error"></span></span>
11453
+ <button type="button" data-ref="retry">{{ #l10n:t('table.retry') }}</button>
11454
+ </div>
11455
+ <button type="button" data-ref="reload" data-tpl-aria-label="#l10n:t('pagination.reload')"><ful-icon data-tpl-name="config.reloadIcon" aria-hidden="true"></ful-icon></button>
11456
+ </ful-table-status>
11426
11457
  `;
11427
11458
  static templates = {
11428
11459
  row: `
@@ -11440,6 +11471,31 @@ var fml = (function (exports) {
11440
11471
  #feedback;
11441
11472
  #paginator;
11442
11473
  #sorters;
11474
+ #wrapper;
11475
+ /** @type {TableStatus|null} null under the pager */
11476
+ #status = null;
11477
+ /** @type {IntersectionObserver|null} */
11478
+ #endWatch = null;
11479
+ /** @type {Element[]} the rows whose coming into view appends the next page, none while no append is awaited */
11480
+ #watched = [];
11481
+ /** the page the next append asks for, the rows shown, the total the last answer reported and the rows it carried */
11482
+ #appended = { next: 1, shown: 0, total: 0, last: 0 };
11483
+ /** whether the table keeps a window of pages, `paging="virtual"` over rows that scroll inside it */
11484
+ #virtual = false;
11485
+ /** @type {{ before: HTMLElement, after: HTMLElement } | null} the cells standing in for the rows above and below the window */
11486
+ #spacers = null;
11487
+ /** @type {{ first: number, last: number, pages: Map<number, Element[]> } | null} the pages in the page, in order, null while no rows show */
11488
+ #window = null;
11489
+ /** the total number of rows the last answer reported */
11490
+ #total = 0;
11491
+ /** the height of a row the spacers are sized on, measured on the first rows a load shows; 0 until measured */
11492
+ #rowHeight = 0;
11493
+ /** @type {{ readonly stale: boolean } | null} the claim of the window shift in flight */
11494
+ #shifting = null;
11495
+ /** whether the last window shift failed: scrolling asks for nothing more until a retry or a load */
11496
+ #windowFailed = false;
11497
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
11498
+ #jump = undefined;
11443
11499
  /** @type {{ pageRequest: { page: number, size: number }, sortRequest: any, filterRequest: any }} */
11444
11500
  #latestRequest = { pageRequest: { page: 0, size: 10 }, sortRequest: null, filterRequest: {} };
11445
11501
  /** whether a load has been asked for, by autoload or by a caller */
@@ -11567,6 +11623,7 @@ var fml = (function (exports) {
11567
11623
  }
11568
11624
  this.#buildLoader();
11569
11625
  this.#latestRequest = { ...this.#latestRequest, pageRequest: { ...this.#latestRequest.pageRequest, page: 0 } };
11626
+ this.#window = null;
11570
11627
  return true;
11571
11628
  }
11572
11629
  /**
@@ -11577,14 +11634,24 @@ var fml = (function (exports) {
11577
11634
  async render({ slots }) {
11578
11635
  const template = this.template();
11579
11636
  const schema = TableSchemaParser.parse(slots.schema, template);
11580
- const fragment = template.withOverlay({ slots, schema }).render();
11637
+ const paging = this.declared('paging');
11638
+ const fragment = template
11639
+ .withOverlay({
11640
+ slots,
11641
+ schema,
11642
+ scrolled: paging === 'infinite' || paging === 'virtual',
11643
+ virtual: paging === 'virtual',
11644
+ })
11645
+ .render();
11581
11646
  const tableWrapper = /** @type HTMLTableElement */ (Nodes.queryChildren(fragment, 'ful-table-wrapper'));
11582
11647
  const table = /** @type HTMLTableElement */ (tableWrapper.querySelector('table'));
11583
11648
  Attributes.forward('table-', this, table);
11584
11649
  this.#buildLoader();
11585
11650
 
11651
+ this.#wrapper = tableWrapper;
11652
+ const status = Nodes.queryChildren(fragment, 'ful-table-status');
11586
11653
  this.#schema = schema;
11587
- this.#body = table.querySelector(':scope > tbody');
11654
+ this.#body = table.querySelector(':scope > tbody:not([data-ref])');
11588
11655
  this.#loading = table.querySelector(':scope > tbody[data-ref=loading]');
11589
11656
  this.#noAutoload = table.querySelector(':scope > tbody[data-ref=initial]');
11590
11657
  this.#empty = table.querySelector(':scope > tbody[data-ref=empty]');
@@ -11594,6 +11661,56 @@ var fml = (function (exports) {
11594
11661
  this.#feedback = table.querySelector(':scope > tbody[data-ref=feedback]');
11595
11662
  this.#paginator = Nodes.queryChildren(fragment, 'ful-pagination');
11596
11663
  this.replaceChildren(fragment);
11664
+ if (paging === 'virtual') {
11665
+ const overflow = getComputedStyle(tableWrapper).overflowY;
11666
+ this.#virtual = overflow === 'auto' || overflow === 'scroll';
11667
+ if (!this.#virtual) {
11668
+ console.warn(
11669
+ 'ful-table: paging="virtual" needs rows that scroll inside the table, as ful-fill makes them; this one appends its pages as paging="infinite" does',
11670
+ );
11671
+ }
11672
+ }
11673
+ if (status) {
11674
+ const piece = (/** @type string */ ref) =>
11675
+ /** @type Element */ (status.querySelector(`[data-ref=${ref}]`));
11676
+ this.#status = {
11677
+ count: piece('count'),
11678
+ appending: piece('appending'),
11679
+ failure: piece('append-failure'),
11680
+ error: piece('append-error'),
11681
+ };
11682
+ piece('reload').addEventListener('click', () => this.reload());
11683
+ piece('retry').addEventListener('click', () => {
11684
+ if (!this.#virtual) {
11685
+ this.#appendNext();
11686
+ return;
11687
+ }
11688
+ this.#windowFailed = false;
11689
+ this.#reconcile(true);
11690
+ });
11691
+ }
11692
+ if (this.#virtual) {
11693
+ this.#spacers = {
11694
+ before: /** @type HTMLElement */ (table.querySelector(':scope > tbody[data-ref=before] td')),
11695
+ after: /** @type HTMLElement */ (table.querySelector(':scope > tbody[data-ref=after] td')),
11696
+ };
11697
+ // scroll fires once per frame at most, so it needs no throttle of its own
11698
+ tableWrapper.addEventListener(
11699
+ 'scroll',
11700
+ () => {
11701
+ this.#countInView();
11702
+ this.#reconcile(false);
11703
+ },
11704
+ { passive: true },
11705
+ );
11706
+ } else if (status) {
11707
+ this.#endWatch = new IntersectionObserver((entries) => {
11708
+ // an entry queued before the watch moved on to another row, or stopped, asks for nothing
11709
+ if (entries.some((e) => e.isIntersecting && this.#watched.includes(e.target))) {
11710
+ this.#appendNext();
11711
+ }
11712
+ });
11713
+ }
11597
11714
  const thead = /** @type HTMLTableSectionElement */ (this.querySelector('thead'));
11598
11715
  schema.headersTemplate.renderTo(thead);
11599
11716
  this.#sorters = thead.querySelectorAll('ful-sorter');
@@ -11650,6 +11767,14 @@ var fml = (function (exports) {
11650
11767
  * `submit` listeners as the later ones, and the load its `submit:success`
11651
11768
  * starts is the one awaited. A filter submit that is cancelled, fails or
11652
11769
  * is dropped for one in flight loads nothing, and the promise resolves.
11770
+ *
11771
+ * Under `paging="virtual"`, once rows show, it asks again for the pages in
11772
+ * the page, with the same size, sort and filters, and shows them where
11773
+ * they are, the scroll position and the widths of the columns kept; the
11774
+ * table is busy and settles, fails and dispatches as a load does, one
11775
+ * `load:success` per page. When the answers report fewer rows than the
11776
+ * window starts at, it loads the first page instead. A `src` or `method`
11777
+ * write still starts over from the first page.
11653
11778
  * @returns {Promise<void>} as `load`
11654
11779
  */
11655
11780
  async reload() {
@@ -11659,6 +11784,9 @@ var fml = (function (exports) {
11659
11784
  }
11660
11785
  return;
11661
11786
  }
11787
+ if (this.#window) {
11788
+ return await this.#reloadWindow();
11789
+ }
11662
11790
  return await this.load(
11663
11791
  this.#latestRequest.pageRequest,
11664
11792
  this.#latestRequest.sortRequest,
@@ -11697,6 +11825,40 @@ var fml = (function (exports) {
11697
11825
  * failure arrives it changes nothing, dispatches nothing and resolves;
11698
11826
  * superseded while its rows render, it leaves them to the newer load and
11699
11827
  * dispatches nothing.
11828
+ *
11829
+ * Under `paging="infinite"` the status bar takes the pager's place, and
11830
+ * once the load has dispatched `load:success` the next page is awaited:
11831
+ * when a row of the last half page comes into view, through
11832
+ * whatever scrolls it, the following page is asked for with the same
11833
+ * size, sort and filters and its rows are appended. An append runs
11834
+ * without `aria-busy`, a spinner in the status bar standing in, and
11835
+ * dispatches `load:success` or `load:failure` as a load does, its
11836
+ * `pageRequest` naming the appended page. A failed append keeps the
11837
+ * rows, shows the error in the status bar with a retry button and
11838
+ * rejects to nobody, nothing awaiting it. Appending stops once the rows
11839
+ * shown reach the total the last answer reported, or an answer carries
11840
+ * no rows. A load supersedes an append in flight; `reload` repeats this
11841
+ * load, not the pages appended to it.
11842
+ *
11843
+ * Under `paging="virtual"` the load shows its page as the window, scrolled
11844
+ * to where it sits among the total, and measures two things on its rows:
11845
+ * the height the empty space standing in for the other rows is sized on,
11846
+ * and the width of the columns, which then stay as they are, in
11847
+ * proportion, until the next load, so that the pages coming and going do
11848
+ * not move them. From then on the window follows the scroll: the page in
11849
+ * view and one on either side stay in the page and the others are dropped,
11850
+ * the page holding the focus kept while it is within two pages of them. A
11851
+ * page next to the window is asked for at once; a scroll landing farther
11852
+ * waits for the scroll to rest. Window pages are asked for without
11853
+ * `aria-busy`, a spinner in the status bar standing in, and dispatch
11854
+ * `load:success` or `load:failure` per page as appends do; a failure keeps
11855
+ * the rows and offers a retry. The row in view stays where it is as pages
11856
+ * come and go above it: the table measures it before and after and
11857
+ * corrects the scroll by whatever the browser's own scroll anchoring has
11858
+ * not kept, which is all of it where the browser anchors no table rows
11859
+ * (Firefox), has no scroll anchoring or the rows' container declares
11860
+ * `overflow-anchor: none`, and nothing where it has. The table carries
11861
+ * `aria-rowcount` and each row its `aria-rowindex`.
11700
11862
  * @param {TablePageRequest} pageRequest
11701
11863
  * @param {TableSortRequest|null} sortRequest
11702
11864
  * @param {Record<string, any>} filterRequest
@@ -11707,6 +11869,13 @@ var fml = (function (exports) {
11707
11869
  this.#loadRequested = true;
11708
11870
  this.#requestedFilters = filterRequest;
11709
11871
  const claim = this.#loads.take();
11872
+ this.#watched = [];
11873
+ this.#endWatch?.disconnect();
11874
+ clearTimeout(this.#jump);
11875
+ this.#shifting = null;
11876
+ this.#windowFailed = false;
11877
+ this.#status?.appending.setAttribute('hidden', '');
11878
+ this.#status?.failure.setAttribute('hidden', '');
11710
11879
  this.#loading.toggleAttribute('hidden', this.#body.childElementCount > 0);
11711
11880
  this.#feedback.setAttribute('hidden', '');
11712
11881
  this.#noAutoload.setAttribute('hidden', '');
@@ -11736,6 +11905,9 @@ var fml = (function (exports) {
11736
11905
  if (claim.stale) {
11737
11906
  return;
11738
11907
  }
11908
+ if (this.#virtual) {
11909
+ this.#settleWindow();
11910
+ }
11739
11911
  this.removeAttribute('aria-busy');
11740
11912
  this.dispatchEvent(
11741
11913
  new CustomEvent('load:success', {
@@ -11744,24 +11916,15 @@ var fml = (function (exports) {
11744
11916
  detail: { pageRequest, sortRequest, filterRequest, response: pageResponse },
11745
11917
  }),
11746
11918
  );
11919
+ this.#watchEnd(pageRequest.size);
11920
+ this.#reconcile(false);
11747
11921
  return;
11748
11922
  }
11749
11923
  } catch (/** @type any */ error) {
11750
11924
  if (claim.stale) {
11751
11925
  return;
11752
11926
  }
11753
- this.#loading.setAttribute('hidden', '');
11754
- this.#body.replaceChildren();
11755
- this.#feedback.removeAttribute('hidden');
11756
- this.#feedback.querySelector('[data-ref=feedback-error]').textContent = Localization.of().failure(error);
11757
- this.removeAttribute('aria-busy');
11758
- this.dispatchEvent(
11759
- new CustomEvent('load:failure', {
11760
- bubbles: true,
11761
- cancelable: false,
11762
- detail: { pageRequest, sortRequest, filterRequest, exception: error },
11763
- }),
11764
- );
11927
+ this.#fail(error, { pageRequest, sortRequest, filterRequest });
11765
11928
  throw error;
11766
11929
  }
11767
11930
  return await this.load({ page: lastPage, size: pageRequest.size }, sortRequest, filterRequest);
@@ -11792,19 +11955,471 @@ var fml = (function (exports) {
11792
11955
  filterRequest,
11793
11956
  );
11794
11957
  }
11795
- #update(pageRequest, sortRequest, filterRequest, pageResponse) {
11796
- const pages = Math.ceil(pageResponse.size / pageRequest.size);
11958
+ /**
11959
+ * Watches the last half page of rows, so that any of them coming into
11960
+ * view appends the next page, unless the rows shown already reach the
11961
+ * total or the last answer carried none. A single row would be missed by
11962
+ * a scroll jumping past it, to the end for instance.
11963
+ * @param {number} size the rows a page asks for
11964
+ */
11965
+ #watchEnd(size) {
11966
+ const { shown, total, last } = this.#appended;
11967
+ if (!this.#endWatch || !(shown < total) || last === 0) {
11968
+ return;
11969
+ }
11970
+ const rows = [...this.#body.children];
11971
+ this.#watched = rows.slice(Math.max(0, rows.length - Math.ceil(size / 2)));
11972
+ for (const row of this.#watched) {
11973
+ this.#endWatch.observe(row);
11974
+ }
11975
+ }
11976
+ async #appendNext() {
11977
+ const status = /** @type TableStatus */ (this.#status);
11978
+ this.#watched = [];
11979
+ this.#endWatch?.disconnect();
11980
+ const { sortRequest, filterRequest } = this.#latestRequest;
11981
+ const pageRequest = { page: this.#appended.next, size: this.#latestRequest.pageRequest.size };
11982
+ const claim = this.#loads.take();
11983
+ status.failure.setAttribute('hidden', '');
11984
+ status.appending.removeAttribute('hidden');
11985
+ try {
11986
+ const pageResponse = await this.#loader.load(pageRequest, sortRequest, filterRequest);
11987
+ if (claim.stale) {
11988
+ return;
11989
+ }
11990
+ this.#body.append(
11991
+ this.template('row')
11992
+ .withOverlay({ schema: this.#schema, pageRequest, filterRequest, pageResponse })
11993
+ .render(),
11994
+ );
11995
+ this.#appended = {
11996
+ next: pageRequest.page + 1,
11997
+ shown: this.#appended.shown + pageResponse.data.length,
11998
+ total: pageResponse.size,
11999
+ last: pageResponse.data.length,
12000
+ };
12001
+ status.count.textContent = Localization.of().t('table.loaded', {
12002
+ loaded: this.#appended.shown,
12003
+ total: this.#appended.total,
12004
+ });
12005
+ await Rendering.waitForChildren(this.#body).catch(() => undefined);
12006
+ if (claim.stale) {
12007
+ return;
12008
+ }
12009
+ status.appending.setAttribute('hidden', '');
12010
+ this.dispatchEvent(
12011
+ new CustomEvent('load:success', {
12012
+ bubbles: true,
12013
+ cancelable: false,
12014
+ detail: { pageRequest, sortRequest, filterRequest, response: pageResponse },
12015
+ }),
12016
+ );
12017
+ this.#watchEnd(pageRequest.size);
12018
+ } catch (/** @type any */ error) {
12019
+ if (claim.stale) {
12020
+ return;
12021
+ }
12022
+ status.appending.setAttribute('hidden', '');
12023
+ status.error.textContent = Localization.of().failure(error);
12024
+ status.failure.removeAttribute('hidden');
12025
+ this.dispatchEvent(
12026
+ new CustomEvent('load:failure', {
12027
+ bubbles: true,
12028
+ cancelable: false,
12029
+ detail: { pageRequest, sortRequest, filterRequest, exception: error },
12030
+ }),
12031
+ );
12032
+ }
12033
+ }
12034
+ /**
12035
+ * Renders the rows of a page, numbering them with `aria-rowindex` under
12036
+ * `paging="virtual"`, the header row being the first.
12037
+ * @param {TablePageRequest} pageRequest
12038
+ * @param {Record<string, any>} filterRequest
12039
+ * @param {TablePageResponse} pageResponse
12040
+ * @returns {Element[]}
12041
+ */
12042
+ #pageRows(pageRequest, filterRequest, pageResponse) {
12043
+ const rows = [
12044
+ ...this.template('row')
12045
+ .withOverlay({ schema: this.#schema, pageRequest, filterRequest, pageResponse })
12046
+ .render().children,
12047
+ ];
12048
+ if (this.#virtual) {
12049
+ rows.forEach((row, i) => {
12050
+ row.setAttribute('aria-rowindex', String(pageRequest.page * pageRequest.size + i + 2));
12051
+ });
12052
+ }
12053
+ return rows;
12054
+ }
12055
+ /**
12056
+ * Shows a failed load: the rows go, the error panel shows and
12057
+ * `load:failure` is dispatched.
12058
+ * @param {any} error
12059
+ * @param {{ pageRequest: TablePageRequest, sortRequest: TableSortRequest|null, filterRequest: Record<string, any> }} request
12060
+ */
12061
+ #fail(error, request) {
11797
12062
  this.#loading.setAttribute('hidden', '');
11798
- this.#body.replaceChildren(
11799
- this.template('row')
11800
- .withOverlay({
11801
- schema: this.#schema,
11802
- pageRequest,
11803
- filterRequest,
11804
- pageResponse,
11805
- })
11806
- .render(),
12063
+ this.#body.replaceChildren();
12064
+ this.#window = null;
12065
+ this.#fitSpacers();
12066
+ this.#status?.count.replaceChildren();
12067
+ this.#feedback.removeAttribute('hidden');
12068
+ this.#feedback.querySelector('[data-ref=feedback-error]').textContent = Localization.of().failure(error);
12069
+ this.removeAttribute('aria-busy');
12070
+ this.dispatchEvent(
12071
+ new CustomEvent('load:failure', {
12072
+ bubbles: true,
12073
+ cancelable: false,
12074
+ detail: { ...request, exception: error },
12075
+ }),
11807
12076
  );
12077
+ }
12078
+ /** Counts the rows of a load just shown and moves the window where its page sits. */
12079
+ #settleWindow() {
12080
+ const table = /** @type HTMLTableElement */ (this.#body.parentElement);
12081
+ table.setAttribute('aria-rowcount', String(this.#total + 1));
12082
+ table.tHead?.rows[0]?.setAttribute('aria-rowindex', '1');
12083
+ const status = /** @type TableStatus */ (this.#status);
12084
+ const window = this.#window;
12085
+ if (!window) {
12086
+ this.#fitSpacers();
12087
+ status.count.textContent = Localization.of().t('table.loaded', { loaded: 0, total: this.#total });
12088
+ return;
12089
+ }
12090
+ const size = this.#latestRequest.pageRequest.size;
12091
+ const from = window.first * size;
12092
+ status.count.textContent = Localization.of().t('table.range', {
12093
+ from: from + 1,
12094
+ to: from + /** @type Element[] */ (window.pages.get(window.first)).length,
12095
+ total: this.#total,
12096
+ });
12097
+ if (this.#measureRows()) {
12098
+ this.#wrapper.scrollTop = from * this.#rowHeight;
12099
+ }
12100
+ }
12101
+ /**
12102
+ * Measures the height of a row and locks the widths of the columns, once
12103
+ * per load, on the rows it shows, then sizes the spacers. A table that is not laid out, inside a
12104
+ * closed disclosure for instance, measures nothing and is measured when
12105
+ * its rows next scroll.
12106
+ * @returns {boolean} whether the rows are measured
12107
+ */
12108
+ #measureRows() {
12109
+ if (this.#rowHeight > 0) {
12110
+ return true;
12111
+ }
12112
+ const count = this.#body.childElementCount;
12113
+ const height = this.#body.getBoundingClientRect().height;
12114
+ if (count === 0 || height === 0) {
12115
+ return false;
12116
+ }
12117
+ this.#rowHeight = height / count;
12118
+ this.#lockColumns();
12119
+ this.#fitSpacers();
12120
+ return true;
12121
+ }
12122
+ /**
12123
+ * Fixes the widths of the columns, in proportion to the table, at those
12124
+ * the rows in the page give them.
12125
+ */
12126
+ #lockColumns() {
12127
+ const table = /** @type HTMLTableElement */ (this.#body.parentElement);
12128
+ const widths = [...(table.tHead?.rows[0]?.cells ?? [])].map((cell) => cell.getBoundingClientRect().width);
12129
+ const sum = widths.reduce((a, b) => a + b, 0);
12130
+ const columns = document.createElement('colgroup');
12131
+ columns.setAttribute('data-ref', 'widths');
12132
+ for (const width of widths) {
12133
+ const column = document.createElement('col');
12134
+ column.style.width = `${(width / sum) * 100}%`;
12135
+ columns.append(column);
12136
+ }
12137
+ table.insertBefore(columns, table.tHead);
12138
+ }
12139
+ #unlockColumns() {
12140
+ this.#body.parentElement?.querySelector(':scope > colgroup[data-ref=widths]')?.remove();
12141
+ }
12142
+ /** Sizes the space standing in for the rows above and below the window. */
12143
+ #fitSpacers() {
12144
+ if (!this.#spacers) {
12145
+ return;
12146
+ }
12147
+ const window = this.#window;
12148
+ const size = this.#latestRequest.pageRequest.size;
12149
+ const above = window ? window.first * size : 0;
12150
+ const below = window ? Math.max(0, this.#total - (window.last + 1) * size) : 0;
12151
+ this.#spacers.before.style.height = `${above * this.#rowHeight}px`;
12152
+ this.#spacers.after.style.height = `${below * this.#rowHeight}px`;
12153
+ }
12154
+ /** Says in the status bar which rows are in view; nothing changes while none is. */
12155
+ #countInView() {
12156
+ const status = /** @type TableStatus */ (this.#status);
12157
+ const size = this.#latestRequest.pageRequest.size;
12158
+ const view = this.#wrapper.getBoundingClientRect();
12159
+ const top = view.top + (this.#body.parentElement?.querySelector(':scope > thead')?.getBoundingClientRect().height ?? 0);
12160
+ let from = 0;
12161
+ let to = 0;
12162
+ for (const [page, rows] of this.#window?.pages ?? []) {
12163
+ rows.forEach((row, i) => {
12164
+ const rect = row.getBoundingClientRect();
12165
+ if (rect.bottom > top && rect.top < view.bottom) {
12166
+ from ||= page * size + i + 1;
12167
+ to = page * size + i + 1;
12168
+ }
12169
+ });
12170
+ }
12171
+ if (from > 0) {
12172
+ status.count.textContent = Localization.of().t('table.range', { from, to, total: this.#total });
12173
+ }
12174
+ }
12175
+ /**
12176
+ * The page at the middle of the view: found among the rows in the page,
12177
+ * or estimated on the height of a row when the middle falls in the space
12178
+ * standing in for others.
12179
+ * @param {{ first: number, last: number, pages: Map<number, Element[]> }} window
12180
+ * @returns {number}
12181
+ */
12182
+ #pageInView(window) {
12183
+ const pageHeight = this.#latestRequest.pageRequest.size * this.#rowHeight;
12184
+ const view = this.#wrapper.getBoundingClientRect();
12185
+ const middle = view.top + view.height / 2;
12186
+ const rows = this.#body.getBoundingClientRect();
12187
+ if (middle < rows.top) {
12188
+ return Math.max(0, window.first - Math.ceil((rows.top - middle) / pageHeight));
12189
+ }
12190
+ if (middle >= rows.bottom) {
12191
+ return window.last + 1 + Math.floor((middle - rows.bottom) / pageHeight);
12192
+ }
12193
+ let found = window.first;
12194
+ for (const [page, pageRows] of window.pages) {
12195
+ if (pageRows.length > 0 && pageRows[0].getBoundingClientRect().top <= middle) {
12196
+ found = page;
12197
+ }
12198
+ }
12199
+ return found;
12200
+ }
12201
+ /**
12202
+ * Moves the window to the page in view and its neighbours. A window next
12203
+ * to the current one moves at once; one farther away waits for the scroll
12204
+ * to rest, unless `settled` says it has.
12205
+ * @param {boolean} settled
12206
+ */
12207
+ #reconcile(settled) {
12208
+ const window = this.#window;
12209
+ const pageCount = Math.ceil(this.#total / this.#latestRequest.pageRequest.size);
12210
+ if (
12211
+ !window ||
12212
+ this.#shifting ||
12213
+ this.#windowFailed ||
12214
+ this.hasAttribute('aria-busy') ||
12215
+ !this.#wrapper.isConnected ||
12216
+ !(pageCount > 0) ||
12217
+ !this.#measureRows()
12218
+ ) {
12219
+ return;
12220
+ }
12221
+ const target = Math.min(pageCount - 1, this.#pageInView(window));
12222
+ let first = Math.max(0, target - 1);
12223
+ let last = Math.min(pageCount - 1, target + 1);
12224
+ const focused = this.#body.contains(document.activeElement)
12225
+ ? /** @type Element */ (document.activeElement).closest('tr')
12226
+ : null;
12227
+ const focusedPage = [...window.pages].find(([, rows]) => focused && rows.includes(focused))?.[0];
12228
+ if (focusedPage !== undefined && Math.max(last, focusedPage) - Math.min(first, focusedPage) <= 4) {
12229
+ first = Math.min(first, focusedPage);
12230
+ last = Math.max(last, focusedPage);
12231
+ }
12232
+ if (first === window.first && last === window.last) {
12233
+ return;
12234
+ }
12235
+ clearTimeout(this.#jump);
12236
+ if (!settled && (last < window.first - 1 || first > window.last + 1)) {
12237
+ this.#jump = setTimeout(() => this.#reconcile(true), 150);
12238
+ return;
12239
+ }
12240
+ this.#shiftWindow(window, first, last);
12241
+ }
12242
+ /**
12243
+ * Asks for the pages of the new window that are not in the page, drops
12244
+ * the ones outside it and keeps the row in view where it is.
12245
+ * @param {{ first: number, last: number, pages: Map<number, Element[]> }} window
12246
+ * @param {number} first
12247
+ * @param {number} last
12248
+ */
12249
+ async #shiftWindow(window, first, last) {
12250
+ const status = /** @type TableStatus */ (this.#status);
12251
+ const claim = this.#loads.hold();
12252
+ this.#shifting = claim;
12253
+ const { sortRequest, filterRequest } = this.#latestRequest;
12254
+ const size = this.#latestRequest.pageRequest.size;
12255
+ const wanted = Array.from({ length: last - first + 1 }, (_, i) => first + i);
12256
+ const missing = wanted.filter((page) => !window.pages.has(page));
12257
+ status.failure.setAttribute('hidden', '');
12258
+ status.appending.removeAttribute('hidden');
12259
+ try {
12260
+ const answers = await Promise.all(
12261
+ missing.map(async (page) => {
12262
+ const pageRequest = { page, size };
12263
+ return { pageRequest, response: await this.#loader.load(pageRequest, sortRequest, filterRequest) };
12264
+ }),
12265
+ );
12266
+ if (claim.stale) {
12267
+ return;
12268
+ }
12269
+ const kept = wanted.filter((page) => window.pages.has(page));
12270
+ const top = this.#wrapper.getBoundingClientRect().top;
12271
+ const anchor = kept
12272
+ .flatMap((page) => window.pages.get(page) ?? [])
12273
+ .find((row) => row.getBoundingClientRect().bottom > top);
12274
+ const anchorTop = anchor?.getBoundingClientRect().top ?? 0;
12275
+ for (const [page, rows] of window.pages) {
12276
+ if (page < first || page > last) {
12277
+ for (const row of rows) {
12278
+ row.remove();
12279
+ }
12280
+ }
12281
+ }
12282
+ /** @type {Map<number, Element[]>} */
12283
+ const pages = new Map();
12284
+ for (const page of wanted) {
12285
+ const answer = answers.find((a) => a.pageRequest.page === page);
12286
+ pages.set(
12287
+ page,
12288
+ window.pages.get(page) ??
12289
+ (answer ? this.#pageRows(answer.pageRequest, filterRequest, answer.response) : []),
12290
+ );
12291
+ }
12292
+ if (kept.length === 0) {
12293
+ this.#body.replaceChildren(...[...pages.values()].flat());
12294
+ } else {
12295
+ this.#body.prepend(...wanted.filter((page) => page < kept[0]).flatMap((page) => pages.get(page) ?? []));
12296
+ this.#body.append(
12297
+ ...wanted.filter((page) => page > /** @type number */ (kept.at(-1))).flatMap((page) => pages.get(page) ?? []),
12298
+ );
12299
+ }
12300
+ this.#window = { first, last, pages };
12301
+ this.#total = answers.at(-1)?.response.size ?? this.#total;
12302
+ this.#body.parentElement?.setAttribute('aria-rowcount', String(this.#total + 1));
12303
+ this.#fitSpacers();
12304
+ if (anchor) {
12305
+ this.#wrapper.scrollTop += anchor.getBoundingClientRect().top - anchorTop;
12306
+ }
12307
+ await Rendering.waitForChildren(this.#body).catch(() => undefined);
12308
+ if (claim.stale) {
12309
+ return;
12310
+ }
12311
+ if (anchor) {
12312
+ // the elements in the new rows have rendered since, which can change their height
12313
+ this.#wrapper.scrollTop += anchor.getBoundingClientRect().top - anchorTop;
12314
+ }
12315
+ status.appending.setAttribute('hidden', '');
12316
+ this.#countInView();
12317
+ for (const { pageRequest, response } of answers) {
12318
+ this.dispatchEvent(
12319
+ new CustomEvent('load:success', {
12320
+ bubbles: true,
12321
+ cancelable: false,
12322
+ detail: { pageRequest, sortRequest, filterRequest, response },
12323
+ }),
12324
+ );
12325
+ }
12326
+ } catch (/** @type any */ error) {
12327
+ if (claim.stale) {
12328
+ return;
12329
+ }
12330
+ this.#windowFailed = true;
12331
+ status.appending.setAttribute('hidden', '');
12332
+ status.error.textContent = Localization.of().failure(error);
12333
+ status.failure.removeAttribute('hidden');
12334
+ this.dispatchEvent(
12335
+ new CustomEvent('load:failure', {
12336
+ bubbles: true,
12337
+ cancelable: false,
12338
+ detail: { pageRequest: { page: missing[0], size }, sortRequest, filterRequest, exception: error },
12339
+ }),
12340
+ );
12341
+ return;
12342
+ } finally {
12343
+ if (this.#shifting === claim) {
12344
+ this.#shifting = null;
12345
+ }
12346
+ }
12347
+ this.#reconcile(false);
12348
+ }
12349
+ /**
12350
+ * Asks again for the pages of the window and shows them where they are.
12351
+ * @returns {Promise<void>}
12352
+ */
12353
+ async #reloadWindow() {
12354
+ const window = /** @type {{ first: number, last: number, pages: Map<number, Element[]> }} */ (this.#window);
12355
+ const status = /** @type TableStatus */ (this.#status);
12356
+ const { sortRequest, filterRequest } = this.#latestRequest;
12357
+ const size = this.#latestRequest.pageRequest.size;
12358
+ this.#requestedFilters = filterRequest;
12359
+ const claim = this.#loads.take();
12360
+ clearTimeout(this.#jump);
12361
+ this.#shifting = null;
12362
+ this.#windowFailed = false;
12363
+ status.appending.setAttribute('hidden', '');
12364
+ status.failure.setAttribute('hidden', '');
12365
+ this.setAttribute('aria-busy', 'true');
12366
+ const wanted = Array.from({ length: window.last - window.first + 1 }, (_, i) => window.first + i);
12367
+ try {
12368
+ const answers = await Promise.all(
12369
+ wanted.map(async (page) => {
12370
+ const pageRequest = { page, size };
12371
+ return { pageRequest, response: await this.#loader.load(pageRequest, sortRequest, filterRequest) };
12372
+ }),
12373
+ );
12374
+ if (claim.stale) {
12375
+ return;
12376
+ }
12377
+ const total = /** @type {{ response: TablePageResponse }} */ (answers.at(-1)).response.size;
12378
+ const pageCount = Math.ceil(total / size);
12379
+ if (!(window.first < pageCount)) {
12380
+ return await this.load({ page: 0, size }, sortRequest, filterRequest);
12381
+ }
12382
+ const shown = answers.filter((a) => a.pageRequest.page < pageCount);
12383
+ const pages = new Map(
12384
+ shown.map((a) => [a.pageRequest.page, this.#pageRows(a.pageRequest, filterRequest, a.response)]),
12385
+ );
12386
+ this.#body.replaceChildren(...[...pages.values()].flat());
12387
+ this.#window = { first: window.first, last: Math.min(window.last, pageCount - 1), pages };
12388
+ this.#total = total;
12389
+ this.#body.parentElement?.setAttribute('aria-rowcount', String(total + 1));
12390
+ this.#fitSpacers();
12391
+ await Rendering.waitForChildren(this.#body).catch(() => undefined);
12392
+ if (claim.stale) {
12393
+ return;
12394
+ }
12395
+ this.removeAttribute('aria-busy');
12396
+ this.#countInView();
12397
+ for (const { pageRequest, response } of shown) {
12398
+ this.dispatchEvent(
12399
+ new CustomEvent('load:success', {
12400
+ bubbles: true,
12401
+ cancelable: false,
12402
+ detail: { pageRequest, sortRequest, filterRequest, response },
12403
+ }),
12404
+ );
12405
+ }
12406
+ this.#reconcile(false);
12407
+ } catch (/** @type any */ error) {
12408
+ if (claim.stale) {
12409
+ return;
12410
+ }
12411
+ this.#fail(error, { pageRequest: { page: window.first, size }, sortRequest, filterRequest });
12412
+ throw error;
12413
+ }
12414
+ }
12415
+ #update(pageRequest, sortRequest, filterRequest, pageResponse) {
12416
+ this.#loading.setAttribute('hidden', '');
12417
+ if (this.#virtual) {
12418
+ this.#rowHeight = 0;
12419
+ this.#unlockColumns();
12420
+ }
12421
+ const rows = this.#pageRows(pageRequest, filterRequest, pageResponse);
12422
+ this.#body.replaceChildren(...rows);
11808
12423
  this.#empty.toggleAttribute('hidden', pageResponse.data.length !== 0);
11809
12424
  if (this.#emptyTemplate && pageResponse.data.length === 0) {
11810
12425
  this.#emptyAuthors.replaceChildren(
@@ -11813,7 +12428,28 @@ var fml = (function (exports) {
11813
12428
  .render(),
11814
12429
  );
11815
12430
  }
11816
- this.#paginator.update({ current: pageRequest.page, total: pages });
12431
+ if (this.#virtual) {
12432
+ this.#wrapper.scrollTop = 0;
12433
+ this.#total = pageResponse.size;
12434
+ this.#window =
12435
+ rows.length > 0 ? { first: pageRequest.page, last: pageRequest.page, pages: new Map([[pageRequest.page, rows]]) } : null;
12436
+ return;
12437
+ }
12438
+ if (this.#status) {
12439
+ this.#wrapper.scrollTop = 0;
12440
+ this.#appended = {
12441
+ next: pageRequest.page + 1,
12442
+ shown: pageResponse.data.length,
12443
+ total: pageResponse.size,
12444
+ last: pageResponse.data.length,
12445
+ };
12446
+ this.#status.count.textContent = Localization.of().t('table.loaded', {
12447
+ loaded: this.#appended.shown,
12448
+ total: this.#appended.total,
12449
+ });
12450
+ return;
12451
+ }
12452
+ this.#paginator.update({ current: pageRequest.page, total: Math.ceil(pageResponse.size / pageRequest.size) });
11817
12453
  }
11818
12454
  }
11819
12455
 
@@ -14780,6 +15416,9 @@ var fml = (function (exports) {
14780
15416
  'table.initial': 'Start searching to see results.',
14781
15417
  'table.error': 'Error while loading data:',
14782
15418
  'table.no-data': 'No elements found.',
15419
+ 'table.loaded': 'Showing {loaded} of {total}',
15420
+ 'table.range': 'Rows {from}-{to} of {total}',
15421
+ 'table.retry': 'Retry',
14783
15422
  'dropdown.empty': 'No results',
14784
15423
  'select.remove': 'Remove',
14785
15424
  'files.dropzone-label': 'Click or drop your files here',
@@ -14831,6 +15470,9 @@ var fml = (function (exports) {
14831
15470
  'table.initial': 'Avvia la ricerca per visualizzare i risultati.',
14832
15471
  'table.error': 'Errore nel caricamento dei dati:',
14833
15472
  'table.no-data': 'Nessun elemento trovato.',
15473
+ 'table.loaded': 'Mostrati {loaded} di {total}',
15474
+ 'table.range': 'Righe {from}-{to} di {total}',
15475
+ 'table.retry': 'Riprova',
14834
15476
  'dropdown.empty': 'Nessun risultato',
14835
15477
  'select.remove': 'Rimuovi',
14836
15478
  'files.dropzone-label': 'Clicca o trascina i file qui',
@@ -14882,6 +15524,9 @@ var fml = (function (exports) {
14882
15524
  'table.initial': 'Inicia la búsqueda para ver los resultados.',
14883
15525
  'table.error': 'Error al cargar los datos:',
14884
15526
  'table.no-data': 'No se encontraron elementos.',
15527
+ 'table.loaded': 'Mostrando {loaded} de {total}',
15528
+ 'table.range': 'Filas {from}-{to} de {total}',
15529
+ 'table.retry': 'Reintentar',
14885
15530
  'dropdown.empty': 'Sin resultados',
14886
15531
  'select.remove': 'Eliminar',
14887
15532
  'files.dropzone-label': 'Haz clic o arrastra tus archivos aquí',
@@ -14936,6 +15581,9 @@ var fml = (function (exports) {
14936
15581
  'table.initial': 'Lancez la recherche pour voir les résultats.',
14937
15582
  'table.error': 'Erreur lors du chargement des données :',
14938
15583
  'table.no-data': 'Aucun élément trouvé.',
15584
+ 'table.loaded': 'Affichage de {loaded} sur {total}',
15585
+ 'table.range': 'Lignes {from} à {to} sur {total}',
15586
+ 'table.retry': 'Réessayer',
14939
15587
  'dropdown.empty': 'Aucun résultat',
14940
15588
  'select.remove': 'Retirer',
14941
15589
  'files.dropzone-label': 'Cliquez ou déposez vos fichiers ici',