@3mo/fetchable-data-grid
Version:
A fetchable variant of @3mo/data-grid
56 lines (55 loc) • 2.21 kB
JavaScript
import { FetcherController } from '@3mo/fetcher-controller';
import { DataGridSelectionBehaviorOnDataChange } from '@3mo/data-grid';
export class FetchableDataGridFetcherController extends FetcherController {
constructor(host) {
super(host, {
throttle: 500,
fetch: ([parameters]) => !parameters ? Promise.resolve(undefined) : this.host.fetch(parameters),
args: () => [{
...this.host.parameters ?? {},
...this.host.paginationParameters?.({ page: this.host.page, pageSize: this.host.pageSize }) ?? {},
...this.host.sortParameters?.() ?? {},
}]
});
this.host = host;
this.disabled = false;
this._silent = 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();
}
fetch(options) {
this.silent = options?.silent ?? (this.host.silentFetch
&& this.host.data.length > 0
&& !this.host.hasServerSidePagination
&& !this.host.hasServerSideSort);
return this.run();
}
async run(args) {
if (this.disabled) {
return;
}
await super.run(args);
const result = this.value || [];
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);
this.host.dataFetch.dispatch(result);
}
updateTimer() {
window.clearInterval(this.timerId);
if (this.host.autoRefetch) {
this.timerId = window.setInterval(() => {
if (!this.pending) {
this.fetch({ silent: true });
}
}, this.host.autoRefetch * 1000);
}
}
}