UNPKG

@3mo/fetchable-data-grid

Version:

A fetchable variant of @3mo/data-grid

77 lines (76 loc) 2.91 kB
import { FetcherController } from '@3mo/fetcher-controller'; import { DataGridSelectionBehaviorOnDataChange } from '@3mo/data-grid'; export class FetchableDataGridFetcherController extends FetcherController { constructor(host) { super(host, { throttle: 500, fetch: async () => { if (!this.host.parameters) { return undefined; } const paginationParameters = this.host.paginationParameters?.({ page: this.host.page, pageSize: this.host.pageSize }) ?? {}; const sortParameters = this.host.sortParameters?.() ?? {}; const data = await this.host.fetch({ ...this.host.parameters, ...paginationParameters, ...sortParameters, }) ?? []; this.host.dataFetch.dispatch(data); return data; }, }); this.host = host; this._silent = false; this._preventFetch = false; } get hasNextPage() { return this._hasNextPage ?? false; } get dataLength() { return this._dataLength; } get silent() { return this._silent; } set silent(value) { this._silent = value; this.host.requestUpdate(); } async fetch(options) { if (this._preventFetch) { return; } this.silent = options?.silent ?? (this.host.silentFetch && this.host.data.length > 0 && !this.host.hasServerSidePagination && !this.host.hasServerSideSort); this._hasNextPage = undefined; this._dataLength = undefined; const result = await super.fetch() || []; if (!(result instanceof Array)) { this._dataLength = result.dataLength; this._hasNextPage = result.hasNextPage ?? (this.host.page < Math.ceil(result.dataLength / this.host.pageSize)); } this.host.setData(result instanceof Array ? result : result.data, this.silent ? DataGridSelectionBehaviorOnDataChange.Maintain : this.host.selectionBehaviorOnDataChange); return result; } async runPreventingFetch(action) { this._preventFetch = true; const result = action(); if (result instanceof Promise) { await result; } this._preventFetch = false; } get autoRefetch() { return this._autoRefetch; } set autoRefetch(value) { this._autoRefetch = value; this.host.requestUpdate(); this.updateTimer(); } updateTimer() { window.clearInterval(this.timerId); this.timerId = undefined; if (this.autoRefetch) { this.timerId = window.setInterval(() => { if (!this.isFetching) { this.fetch({ silent: true }); } }, this.autoRefetch * 1000); } } }