primeng
Version:
PrimeNG is a premium UI library for Angular featuring a rich set of 90+ components, a theme designer, various theme alternatives such as Material, Bootstrap, Tailwind, premium templates and professional support. In addition, it integrates with PrimeBlock,
1,073 lines (1,064 loc) • 64.2 kB
JavaScript
export * from 'primeng/types/scroller';
import { isPlatformBrowser, NgTemplateOutlet } from '@angular/common';
import * as i0 from '@angular/core';
import { Injectable, InjectionToken, inject, input, computed, output, viewChild, signal, contentChild, effect, untracked, ViewEncapsulation, ChangeDetectionStrategy, Component, NgModule } from '@angular/core';
import { isVisible, getWidth, getHeight, findSingle, isTouchDevice } from '@primeuix/utils';
import { BaseComponent, PARENT_INSTANCE } from 'primeng/basecomponent';
import * as i1 from 'primeng/bind';
import { Bind } from 'primeng/bind';
import { Spinner } from '@primeicons/angular/spinner';
import { BaseStyle } from 'primeng/base';
const css = /*css*/ `
.p-virtualscroller {
position: relative;
overflow: auto;
contain: strict;
transform: translateZ(0);
will-change: scroll-position;
outline: 0 none;
}
.p-virtualscroller-content {
position: absolute;
top: 0;
left: 0;
min-height: 100%;
min-width: 100%;
will-change: transform;
}
.p-virtualscroller-spacer {
position: absolute;
top: 0;
left: 0;
height: 1px;
width: 1px;
transform-origin: 0 0;
pointer-events: none;
}
.p-virtualscroller-loader {
position: sticky;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: dt('virtualscroller.loader.mask.background');
color: dt('virtualscroller.loader.mask.color');
}
.p-virtualscroller-loader-mask {
display: flex;
align-items: center;
justify-content: center;
}
.p-virtualscroller-loading-icon {
font-size: dt('virtualscroller.loader.icon.size');
width: dt('virtualscroller.loader.icon.size');
height: dt('virtualscroller.loader.icon.size');
}
.p-virtualscroller-horizontal > .p-virtualscroller-content {
display: flex;
}
.p-virtualscroller-inline .p-virtualscroller-content {
position: static;
}
`;
const classes = {
root: ({ instance }) => [
'p-virtualscroller',
{
'p-virtualscroller-inline': instance.inline(),
'p-virtualscroller-both p-both-scroll': instance.both(),
'p-virtualscroller-horizontal p-horizontal-scroll': instance.horizontal()
}
],
content: 'p-virtualscroller-content',
spacer: 'p-virtualscroller-spacer',
loader: ({ instance }) => [
'p-virtualscroller-loader',
{
'p-virtualscroller-loader-mask': !instance.loaderTemplate()
}
],
loadingIcon: 'p-virtualscroller-loading-icon'
};
class ScrollerStyle extends BaseStyle {
name = 'virtualscroller';
css = css;
classes = classes;
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: ScrollerStyle, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: ScrollerStyle });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: ScrollerStyle, decorators: [{
type: Injectable
}] });
/**
*
* VirtualScroller is a performant approach to handle huge data efficiently.
*
* [Live Demo](https://www.primeng.org/scroller/)
*
* @module scrollerstyle
*
*/
var ScrollerClasses;
(function (ScrollerClasses) {
/**
* Class name of the root element
*/
ScrollerClasses["root"] = "p-virtualscroller";
/**
* Class name of the content element
*/
ScrollerClasses["content"] = "p-virtualscroller-content";
/**
* Class name of the spacer element
*/
ScrollerClasses["spacer"] = "p-virtualscroller-spacer";
/**
* Class name of the loader element
*/
ScrollerClasses["loader"] = "p-virtualscroller-loader";
/**
* Class name of the loading icon element
*/
ScrollerClasses["loadingIcon"] = "p-virtualscroller-loading-icon";
})(ScrollerClasses || (ScrollerClasses = {}));
const SCROLLER_INSTANCE = new InjectionToken('SCROLLER_INSTANCE');
/**
* Scroller is a performance-approach to handle huge data efficiently.
* @group Components
*/
class Scroller extends BaseComponent {
componentName = 'VirtualScroller';
bindDirectiveInstance = inject(Bind, { self: true });
$pcScroller = inject(SCROLLER_INSTANCE, { optional: true, skipSelf: true }) ?? undefined;
hostName = input('', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "hostName" }] : /* istanbul ignore next */ []));
/**
* Unique identifier of the element.
* @group Props
*/
id = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "id" }] : /* istanbul ignore next */ []));
/**
* Inline style of the component.
* @group Props
*/
style = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "style" }] : /* istanbul ignore next */ []));
/**
* Style class of the element.
* @group Props
*/
styleClass = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "styleClass" }] : /* istanbul ignore next */ []));
/**
* Index of the element in tabbing order.
* @group Props
*/
tabindex = input(0, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "tabindex" }] : /* istanbul ignore next */ []));
/**
* An array of objects to display.
* @group Props
*/
items = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "items" }] : /* istanbul ignore next */ []));
/**
* The height/width of item according to orientation.
* @group Props
*/
itemSize = input(0, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "itemSize" }] : /* istanbul ignore next */ []));
/**
* Height of the scroll viewport.
* @group Props
*/
scrollHeight = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "scrollHeight" }] : /* istanbul ignore next */ []));
/**
* Width of the scroll viewport.
* @group Props
*/
scrollWidth = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "scrollWidth" }] : /* istanbul ignore next */ []));
/**
* The orientation of scrollbar.
* @group Props
*/
orientation = input('vertical', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
/**
* Used to specify how many items to load in each load method in lazy mode.
* @group Props
*/
step = input(0, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "step" }] : /* istanbul ignore next */ []));
/**
* Delay in scroll before new data is loaded.
* @group Props
*/
delay = input(0, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "delay" }] : /* istanbul ignore next */ []));
/**
* Delay after window's resize finishes.
* @group Props
*/
resizeDelay = input(10, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "resizeDelay" }] : /* istanbul ignore next */ []));
/**
* Used to append each loaded item to top without removing any items from the DOM. Using very large data may cause the browser to crash.
* @group Props
*/
appendOnly = input(false, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "appendOnly" }] : /* istanbul ignore next */ []));
/**
* Specifies whether the scroller should be displayed inline or not.
* @group Props
*/
inline = input(false, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "inline" }] : /* istanbul ignore next */ []));
/**
* Defines if data is loaded and interacted with in lazy manner.
* @group Props
*/
lazy = input(false, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "lazy" }] : /* istanbul ignore next */ []));
/**
* If disabled, the scroller feature is eliminated and the content is displayed directly.
* @group Props
*/
disabled = input(false, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
/**
* Used to implement a custom loader instead of using the loader feature in the scroller.
* @group Props
*/
loaderDisabled = input(false, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "loaderDisabled" }] : /* istanbul ignore next */ []));
/**
* Columns to display.
* @group Props
*/
columns = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "columns" }] : /* istanbul ignore next */ []));
/**
* Used to implement a custom spacer instead of using the spacer feature in the scroller.
* @group Props
*/
showSpacer = input(true, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "showSpacer" }] : /* istanbul ignore next */ []));
/**
* Defines whether to show loader.
* @group Props
*/
showLoader = input(false, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "showLoader" }] : /* istanbul ignore next */ []));
/**
* Determines how many additional elements to add to the DOM outside of the view. According to the scrolls made up and down, extra items are added in a certain algorithm in the form of multiples of this number. Default value is half the number of items shown in the view.
* @group Props
*/
numToleratedItems = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "numToleratedItems" }] : /* istanbul ignore next */ []));
/**
* Defines whether the data is loaded.
* @group Props
*/
loading = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "loading" }] : /* istanbul ignore next */ []));
/**
* Defines whether to dynamically change the height or width of scrollable container.
* @group Props
*/
autoSize = input(false, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "autoSize" }] : /* istanbul ignore next */ []));
/**
* Function to optimize the dom operations by delegating to ngForTrackBy, default algoritm checks for object identity.
* @group Props
*/
trackBy = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "trackBy" }] : /* istanbul ignore next */ []));
/**
* Defines whether to use the scroller feature. The properties of scroller component can be used like an object in it.
* @group Props
*/
options = input(/* @ts-ignore */
...(ngDevMode ? [undefined, { debugName: "options" }] : /* istanbul ignore next */ []));
// Computed: Options merge with individual inputs
_id = computed(() => this.options()?.id ?? this.id(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_id" }] : /* istanbul ignore next */ []));
_style = computed(() => this.options()?.style ?? this.style(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_style" }] : /* istanbul ignore next */ []));
_styleClass = computed(() => this.options()?.styleClass ?? this.styleClass(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_styleClass" }] : /* istanbul ignore next */ []));
_tabindex = computed(() => this.options()?.tabindex ?? this.tabindex(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_tabindex" }] : /* istanbul ignore next */ []));
_items = computed(() => this.options()?.items ?? this.items(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_items" }] : /* istanbul ignore next */ []));
_itemSize = computed(() => this.options()?.itemSize ?? this.itemSize(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_itemSize" }] : /* istanbul ignore next */ []));
_scrollHeight = computed(() => this.options()?.scrollHeight ?? this.scrollHeight(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_scrollHeight" }] : /* istanbul ignore next */ []));
_scrollWidth = computed(() => this.options()?.scrollWidth ?? this.scrollWidth(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_scrollWidth" }] : /* istanbul ignore next */ []));
_orientation = computed(() => this.options()?.orientation ?? this.orientation(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_orientation" }] : /* istanbul ignore next */ []));
_step = computed(() => this.options()?.step ?? this.step(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_step" }] : /* istanbul ignore next */ []));
_delay = computed(() => this.options()?.delay ?? this.delay(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_delay" }] : /* istanbul ignore next */ []));
_resizeDelay = computed(() => this.options()?.resizeDelay ?? this.resizeDelay(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_resizeDelay" }] : /* istanbul ignore next */ []));
_appendOnly = computed(() => this.options()?.appendOnly ?? this.appendOnly(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_appendOnly" }] : /* istanbul ignore next */ []));
_inline = computed(() => this.options()?.inline ?? this.inline(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_inline" }] : /* istanbul ignore next */ []));
_lazy = computed(() => this.options()?.lazy ?? this.lazy(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_lazy" }] : /* istanbul ignore next */ []));
_disabled = computed(() => this.options()?.disabled ?? this.disabled(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_disabled" }] : /* istanbul ignore next */ []));
_loaderDisabled = computed(() => this.options()?.loaderDisabled ?? this.loaderDisabled(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_loaderDisabled" }] : /* istanbul ignore next */ []));
_columns = computed(() => this.options()?.columns ?? this.columns(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_columns" }] : /* istanbul ignore next */ []));
_showSpacer = computed(() => this.options()?.showSpacer ?? this.showSpacer(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_showSpacer" }] : /* istanbul ignore next */ []));
_showLoader = computed(() => this.options()?.showLoader ?? this.showLoader(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_showLoader" }] : /* istanbul ignore next */ []));
_numToleratedItems = computed(() => this.options()?.numToleratedItems ?? this.numToleratedItems(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_numToleratedItems" }] : /* istanbul ignore next */ []));
_loading = computed(() => this.options()?.loading ?? this.loading(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_loading" }] : /* istanbul ignore next */ []));
_autoSize = computed(() => this.options()?.autoSize ?? this.autoSize(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_autoSize" }] : /* istanbul ignore next */ []));
_trackBy = computed(() => this.options()?.trackBy ?? this.trackBy(), /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_trackBy" }] : /* istanbul ignore next */ []));
contentStyleClass = computed(() => this.options()?.contentStyleClass, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "contentStyleClass" }] : /* istanbul ignore next */ []));
/**
* Callback to invoke in lazy mode to load new data.
* @param {ScrollerLazyLoadEvent} event - Custom lazy load event.
* @group Emits
*/
onLazyLoad = output();
/**
* Callback to invoke when scroll position changes.
* @param {ScrollerScrollEvent} event - Custom scroll event.
* @group Emits
*/
onScroll = output();
/**
* Callback to invoke when scroll position and item's range in view changes.
* @param {ScrollerScrollEvent} event - Custom scroll index change event.
* @group Emits
*/
onScrollIndexChange = output();
elementViewChild = viewChild('element', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "elementViewChild" }] : /* istanbul ignore next */ []));
contentViewChild = viewChild('content', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "contentViewChild" }] : /* istanbul ignore next */ []));
hostHeight = signal(undefined, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "hostHeight" }] : /* istanbul ignore next */ []));
/**
* Content template of the component.
* @param {ScrollerContentTemplateContext} context - content context.
* @see {@link ScrollerContentTemplateContext}
* @group Templates
*/
contentTemplate = contentChild('content', { ...(ngDevMode ? { debugName: "contentTemplate" } : /* istanbul ignore next */ {}), descendants: false });
/**
* Item template of the component.
* @param {ScrollerItemTemplateContext} context - item context.
* @see {@link ScrollerItemTemplateContext}
* @group Templates
*/
itemTemplate = contentChild('item', { ...(ngDevMode ? { debugName: "itemTemplate" } : /* istanbul ignore next */ {}), descendants: false });
/**
* Loader template of the component.
* @param {ScrollerLoaderTemplateContext} context - loader context.
* @see {@link ScrollerLoaderTemplateContext}
* @group Templates
*/
loaderTemplate = contentChild('loader', { ...(ngDevMode ? { debugName: "loaderTemplate" } : /* istanbul ignore next */ {}), descendants: false });
/**
* Loader icon template of the component.
* @param {ScrollerLoaderIconTemplateContext} context - loader icon context.
* @see {@link ScrollerLoaderIconTemplateContext}
* @group Templates
*/
loaderIconTemplate = contentChild('loadericon', { ...(ngDevMode ? { debugName: "loaderIconTemplate" } : /* istanbul ignore next */ {}), descendants: false });
d_loading = false;
d_numToleratedItems;
contentEl;
vertical = computed(() => this._orientation() === 'vertical', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "vertical" }] : /* istanbul ignore next */ []));
horizontal = computed(() => this._orientation() === 'horizontal', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "horizontal" }] : /* istanbul ignore next */ []));
both = computed(() => this._orientation() === 'both', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "both" }] : /* istanbul ignore next */ []));
get loadedItems() {
const items = this._items();
if (items && !this.d_loading) {
if (this.both()) {
return items.slice(this._appendOnly() ? 0 : this.first.rows, this.last.rows).map((item) => {
if (this._columns()) {
return item;
}
else if (Array.isArray(item)) {
return item.slice(this._appendOnly() ? 0 : this.first.cols, this.last.cols);
}
else {
return item;
}
});
}
else if (this.horizontal() && this._columns())
return items;
else
return items.slice(this._appendOnly() ? 0 : this.first, this.last);
}
return [];
}
get loadedRows() {
return this.d_loading ? (this._loaderDisabled() ? this.loaderArr : []) : this.loadedItems;
}
get loadedColumns() {
const columns = this._columns();
if (columns && (this.both() || this.horizontal())) {
return this.d_loading && this._loaderDisabled() ? (this.both() ? this.loaderArr[0] : this.loaderArr) : columns.slice(this.both() ? this.first.cols : this.first, this.both() ? this.last.cols : this.last);
}
return columns;
}
first = 0;
last = 0;
page = 0;
isRangeChanged = false;
numItemsInViewport = 0;
lastScrollPos = 0;
lazyLoadState = {};
loaderArr = [];
spacerStyle;
contentStyle;
scrollTimeout;
resizeTimeout;
_destroyed = false;
initialized = false;
windowResizeListener;
defaultWidth;
defaultHeight;
defaultContentWidth;
defaultContentHeight;
_componentStyle = inject(ScrollerStyle);
constructor() {
super();
// hostHeight
effect(() => {
if (this._scrollHeight() === '100%') {
this.hostHeight.set('100%');
}
});
// loading sync
effect(() => {
const loading = this._loading();
untracked(() => {
if (this._lazy() && loading !== undefined && loading !== this.d_loading) {
this.d_loading = loading;
}
});
});
// orientation reset
effect(() => {
this._orientation();
untracked(() => {
this.lastScrollPos = this.both() ? { top: 0, left: 0 } : 0;
});
});
// numToleratedItems sync
effect(() => {
const numT = this._numToleratedItems();
untracked(() => {
if (numT !== undefined && numT !== this.d_numToleratedItems) {
this.d_numToleratedItems = numT;
}
});
});
// reinit on size/scroll changes
effect(() => {
this._itemSize();
this._scrollHeight();
this._scrollWidth();
untracked(() => {
if (this.initialized) {
this.init();
this.calculateAutoSize();
}
});
});
// items change
effect(() => {
this._items();
untracked(() => {
if (this.initialized && !this._lazy()) {
this.init();
}
});
});
// contentStyle sync from options
effect(() => {
const opts = this.options();
untracked(() => {
if (opts?.contentStyle !== undefined) {
this.contentStyle = opts.contentStyle;
}
});
});
}
onInit() {
this.setInitialState();
}
onAfterViewInit() {
Promise.resolve().then(() => {
this.viewInit();
});
}
onAfterViewChecked() {
this.bindDirectiveInstance.setAttrs(this.ptm('host'));
if (!this.initialized) {
this.viewInit();
}
}
onDestroy() {
this._destroyed = true;
this.unbindResizeListener();
// Cancel pending scroll/resize debounce timers so handleEvents can't emit after destroy.
if (this.scrollTimeout) {
clearTimeout(this.scrollTimeout);
}
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
}
this.contentEl = null;
this.initialized = false;
}
viewInit() {
if (isPlatformBrowser(this.platformId) && !this.initialized) {
if (isVisible(this.elementViewChild()?.nativeElement)) {
this.setInitialState();
this.setContentEl(this.contentEl);
this.init();
this.defaultWidth = getWidth(this.elementViewChild()?.nativeElement);
this.defaultHeight = getHeight(this.elementViewChild()?.nativeElement);
this.defaultContentWidth = getWidth(this.contentEl);
this.defaultContentHeight = getHeight(this.contentEl);
this.initialized = true;
}
}
}
init() {
if (!this._disabled()) {
this.bindResizeListener();
// wait for the next tick
setTimeout(() => {
this.setSpacerSize();
this.setSize();
this.calculateOptions();
this.calculateAutoSize();
this.cd.detectChanges();
}, 1);
}
}
setContentEl(el) {
this.contentEl = el || this.contentViewChild()?.nativeElement || findSingle(this.elementViewChild()?.nativeElement, '.p-virtualscroller-content');
}
setInitialState() {
this.first = this.both() ? { rows: 0, cols: 0 } : 0;
this.last = this.both() ? { rows: 0, cols: 0 } : 0;
this.numItemsInViewport = this.both() ? { rows: 0, cols: 0 } : 0;
this.lastScrollPos = this.both() ? { top: 0, left: 0 } : 0;
if (this.d_loading === undefined || this.d_loading === false) {
this.d_loading = this._loading() || false;
}
this.d_numToleratedItems = this._numToleratedItems();
this.loaderArr = this.loaderArr.length > 0 ? this.loaderArr : [];
}
getElementRef() {
return this.elementViewChild();
}
getPageByFirst(first) {
return Math.floor(((first ?? this.first) + this.d_numToleratedItems * 4) / (this._step() || 1));
}
isPageChanged(first) {
return this._step() ? this.page !== this.getPageByFirst(first ?? this.first) : true;
}
scrollTo(options) {
this.elementViewChild()?.nativeElement?.scrollTo(options);
}
scrollToIndex(index, behavior = 'auto') {
const valid = this.both() ? index.every((i) => i > -1) : index > -1;
if (valid) {
const first = this.first;
const { scrollTop = 0, scrollLeft = 0 } = this.elementViewChild()?.nativeElement;
const { numToleratedItems } = this.calculateNumItems();
const contentPos = this.getContentPosition();
const itemSize = this._itemSize();
const calculateFirst = (_index = 0, _numT) => (_index <= _numT ? 0 : _index);
const calculateCoord = (_first, _size, _cpos) => _first * _size + _cpos;
const scrollTo = (left = 0, top = 0) => this.scrollTo({ left, top, behavior });
let newFirst = this.both() ? { rows: 0, cols: 0 } : 0;
let isRangeChanged = false, isScrollChanged = false;
if (this.both()) {
newFirst = {
rows: calculateFirst(index[0], numToleratedItems[0]),
cols: calculateFirst(index[1], numToleratedItems[1])
};
scrollTo(calculateCoord(newFirst.cols, itemSize[1], contentPos.left), calculateCoord(newFirst.rows, itemSize[0], contentPos.top));
isScrollChanged = this.lastScrollPos.top !== scrollTop || this.lastScrollPos.left !== scrollLeft;
isRangeChanged = newFirst.rows !== first.rows || newFirst.cols !== first.cols;
}
else {
newFirst = calculateFirst(index, numToleratedItems);
this.horizontal() ? scrollTo(calculateCoord(newFirst, itemSize, contentPos.left), scrollTop) : scrollTo(scrollLeft, calculateCoord(newFirst, itemSize, contentPos.top));
isScrollChanged = this.lastScrollPos !== (this.horizontal() ? scrollLeft : scrollTop);
isRangeChanged = newFirst !== first;
}
this.isRangeChanged = isRangeChanged;
isScrollChanged && (this.first = newFirst);
}
}
scrollInView(index, to, behavior = 'auto') {
if (to) {
const { first, viewport } = this.getRenderedRange();
const scrollTo = (left = 0, top = 0) => this.scrollTo({ left, top, behavior });
const isToStart = to === 'to-start';
const isToEnd = to === 'to-end';
if (isToStart) {
if (this.both()) {
if (viewport.first.rows - first.rows > index[0]) {
scrollTo(viewport.first.cols * this._itemSize()[1], (viewport.first.rows - 1) * this._itemSize()[0]);
}
else if (viewport.first.cols - first.cols > index[1]) {
scrollTo((viewport.first.cols - 1) * this._itemSize()[1], viewport.first.rows * this._itemSize()[0]);
}
}
else {
if (viewport.first - first > index) {
const pos = (viewport.first - 1) * this._itemSize();
this.horizontal() ? scrollTo(pos, 0) : scrollTo(0, pos);
}
}
}
else if (isToEnd) {
if (this.both()) {
if (viewport.last.rows - first.rows <= index[0] + 1) {
scrollTo(viewport.first.cols * this._itemSize()[1], (viewport.first.rows + 1) * this._itemSize()[0]);
}
else if (viewport.last.cols - first.cols <= index[1] + 1) {
scrollTo((viewport.first.cols + 1) * this._itemSize()[1], viewport.first.rows * this._itemSize()[0]);
}
}
else {
if (viewport.last - first <= index + 1) {
const pos = (viewport.first + 1) * this._itemSize();
this.horizontal() ? scrollTo(pos, 0) : scrollTo(0, pos);
}
}
}
}
else {
this.scrollToIndex(index, behavior);
}
}
getRenderedRange() {
const calculateFirstInViewport = (_pos, _size) => (_size || _pos ? Math.floor(_pos / (_size || _pos)) : 0);
let firstInViewport = this.first;
let lastInViewport = 0;
const el = this.elementViewChild()?.nativeElement;
if (el) {
const { scrollTop, scrollLeft } = el;
if (this.both()) {
firstInViewport = {
rows: calculateFirstInViewport(scrollTop, this._itemSize()[0]),
cols: calculateFirstInViewport(scrollLeft, this._itemSize()[1])
};
lastInViewport = {
rows: firstInViewport.rows + this.numItemsInViewport.rows,
cols: firstInViewport.cols + this.numItemsInViewport.cols
};
}
else {
const scrollPos = this.horizontal() ? scrollLeft : scrollTop;
firstInViewport = calculateFirstInViewport(scrollPos, this._itemSize());
lastInViewport = firstInViewport + this.numItemsInViewport;
}
}
return {
first: this.first,
last: this.last,
viewport: {
first: firstInViewport,
last: lastInViewport
}
};
}
calculateNumItems() {
const contentPos = this.getContentPosition();
const el = this.elementViewChild()?.nativeElement;
const contentWidth = (el ? el.offsetWidth - contentPos.left : 0) || 0;
const contentHeight = (el ? el.offsetHeight - contentPos.top : 0) || 0;
const calculateNumItemsInViewport = (_contentSize, _itemSize) => (_itemSize || _contentSize ? Math.ceil(_contentSize / (_itemSize || _contentSize)) : 0);
const calculateNumToleratedItems = (_numItems) => Math.ceil(_numItems / 2);
const numItemsInViewport = this.both()
? {
rows: calculateNumItemsInViewport(contentHeight, this._itemSize()[0]),
cols: calculateNumItemsInViewport(contentWidth, this._itemSize()[1])
}
: calculateNumItemsInViewport(this.horizontal() ? contentWidth : contentHeight, this._itemSize());
const numToleratedItems = this.d_numToleratedItems || (this.both() ? [calculateNumToleratedItems(numItemsInViewport.rows), calculateNumToleratedItems(numItemsInViewport.cols)] : calculateNumToleratedItems(numItemsInViewport));
return { numItemsInViewport, numToleratedItems };
}
calculateOptions() {
const { numItemsInViewport, numToleratedItems } = this.calculateNumItems();
const calculateLast = (_first, _num, _numT, _isCols = false) => this.getLast(_first + _num + (_first < _numT ? 2 : 3) * _numT, _isCols);
const first = this.first;
const last = this.both()
? {
rows: calculateLast(this.first.rows, numItemsInViewport.rows, numToleratedItems[0]),
cols: calculateLast(this.first.cols, numItemsInViewport.cols, numToleratedItems[1], true)
}
: calculateLast(this.first, numItemsInViewport, numToleratedItems);
this.last = last;
this.numItemsInViewport = numItemsInViewport;
this.d_numToleratedItems = numToleratedItems;
if (this._showLoader()) {
this.loaderArr = this.both() ? Array.from({ length: numItemsInViewport.rows }).map(() => Array.from({ length: numItemsInViewport.cols })) : Array.from({ length: numItemsInViewport });
}
if (this._lazy()) {
Promise.resolve().then(() => {
this.lazyLoadState = {
first: this._step() ? (this.both() ? { rows: 0, cols: first.cols } : 0) : first,
last: Math.min(this._step() ? this._step() : this.last, this._items().length)
};
this.handleEvents('onLazyLoad', this.lazyLoadState);
});
}
}
calculateAutoSize() {
if (this._autoSize() && !this.d_loading) {
Promise.resolve().then(() => {
if (this.contentEl) {
this.contentEl.style.minHeight = this.contentEl.style.minWidth = 'auto';
this.contentEl.style.position = 'relative';
this.elementViewChild().nativeElement.style.contain = 'none';
const [contentWidth, contentHeight] = [getWidth(this.contentEl), getHeight(this.contentEl)];
contentWidth !== this.defaultContentWidth && (this.elementViewChild().nativeElement.style.width = '');
contentHeight !== this.defaultContentHeight && (this.elementViewChild().nativeElement.style.height = '');
const [width, height] = [getWidth(this.elementViewChild().nativeElement), getHeight(this.elementViewChild().nativeElement)];
(this.both() || this.horizontal()) && (this.elementViewChild().nativeElement.style.width = width < this.defaultWidth ? width + 'px' : this._scrollWidth() || this.defaultWidth + 'px');
(this.both() || this.vertical()) && (this.elementViewChild().nativeElement.style.height = height < this.defaultHeight ? height + 'px' : this._scrollHeight() || this.defaultHeight + 'px');
this.contentEl.style.minHeight = this.contentEl.style.minWidth = '';
this.contentEl.style.position = '';
this.elementViewChild().nativeElement.style.contain = '';
}
});
}
}
getLast(last = 0, isCols = false) {
const items = this._items();
const columns = this._columns();
return items ? Math.min(isCols ? (columns || items[0]).length : items.length, last) : 0;
}
getContentPosition() {
if (this.contentEl) {
const style = getComputedStyle(this.contentEl);
const left = parseFloat(style.paddingLeft) + Math.max(parseFloat(style.left) || 0, 0);
const right = parseFloat(style.paddingRight) + Math.max(parseFloat(style.right) || 0, 0);
const top = parseFloat(style.paddingTop) + Math.max(parseFloat(style.top) || 0, 0);
const bottom = parseFloat(style.paddingBottom) + Math.max(parseFloat(style.bottom) || 0, 0);
return { left, right, top, bottom, x: left + right, y: top + bottom };
}
return { left: 0, right: 0, top: 0, bottom: 0, x: 0, y: 0 };
}
setSize() {
const nativeElement = this.elementViewChild()?.nativeElement;
if (nativeElement) {
const parentElement = nativeElement.parentElement?.parentElement;
const elementWidth = nativeElement.offsetWidth;
const parentWidth = parentElement?.offsetWidth || 0;
const width = this._scrollWidth() || `${elementWidth || parentWidth}px`;
const elementHeight = nativeElement.offsetHeight;
const parentHeight = parentElement?.offsetHeight || 0;
const height = this._scrollHeight() || `${elementHeight || parentHeight}px`;
const setProp = (_name, _value) => (nativeElement.style[_name] = _value);
if (this.both() || this.horizontal()) {
setProp('height', height);
setProp('width', width);
}
else {
setProp('height', height);
}
}
}
setSpacerSize() {
const items = this._items();
if (items) {
const contentPos = this.getContentPosition();
const setProp = (_name, _value, _size, _cpos = 0) => (this.spacerStyle = {
...this.spacerStyle,
...{ [`${_name}`]: (_value || []).length * _size + _cpos + 'px' }
});
if (this.both()) {
setProp('height', items, this._itemSize()[0], contentPos.y);
setProp('width', this._columns() || items[1], this._itemSize()[1], contentPos.x);
}
else {
this.horizontal() ? setProp('width', this._columns() || items, this._itemSize(), contentPos.x) : setProp('height', items, this._itemSize(), contentPos.y);
}
}
}
setContentPosition(pos) {
if (this.contentEl && !this._appendOnly()) {
const first = pos ? pos.first : this.first;
const calculateTranslateVal = (_first, _size) => _first * _size;
const setTransform = (_x = 0, _y = 0) => (this.contentStyle = { ...this.contentStyle, ...{ transform: `translate3d(${_x}px, ${_y}px, 0)` } });
if (this.both()) {
setTransform(calculateTranslateVal(first.cols, this._itemSize()[1]), calculateTranslateVal(first.rows, this._itemSize()[0]));
}
else {
const translateVal = calculateTranslateVal(first, this._itemSize());
this.horizontal() ? setTransform(translateVal, 0) : setTransform(0, translateVal);
}
}
}
onScrollPositionChange(event) {
const target = event.target;
if (!target) {
throw new Error('Event target is null');
}
const contentPos = this.getContentPosition();
const calculateScrollPos = (_pos, _cpos) => (_pos ? (_pos > _cpos ? _pos - _cpos : _pos) : 0);
const calculateCurrentIndex = (_pos, _size) => (_size || _pos ? Math.floor(_pos / (_size || _pos)) : 0);
const calculateTriggerIndex = (_currentIndex, _first, _last, _num, _numT, _isScrollDownOrRight) => {
return _currentIndex <= _numT ? _numT : _isScrollDownOrRight ? _last - _num - _numT : _first + _numT - 1;
};
const calculateFirst = (_currentIndex, _triggerIndex, _first, _last, _num, _numT, _isScrollDownOrRight) => {
if (_currentIndex <= _numT)
return 0;
else
return Math.max(0, _isScrollDownOrRight ? (_currentIndex < _triggerIndex ? _first : _currentIndex - _numT) : _currentIndex > _triggerIndex ? _first : _currentIndex - 2 * _numT);
};
const calculateLast = (_currentIndex, _first, _last, _num, _numT, _isCols = false) => {
let lastValue = _first + _num + 2 * _numT;
if (_currentIndex >= _numT) {
lastValue += _numT + 1;
}
return this.getLast(lastValue, _isCols);
};
const scrollTop = calculateScrollPos(target.scrollTop, contentPos.top);
const scrollLeft = calculateScrollPos(target.scrollLeft, contentPos.left);
let newFirst = this.both() ? { rows: 0, cols: 0 } : 0;
let newLast = this.last;
let isRangeChanged = false;
let newScrollPos = this.lastScrollPos;
if (this.both()) {
const isScrollDown = this.lastScrollPos.top <= scrollTop;
const isScrollRight = this.lastScrollPos.left <= scrollLeft;
if (!this._appendOnly() || (this._appendOnly() && (isScrollDown || isScrollRight))) {
const currentIndex = {
rows: calculateCurrentIndex(scrollTop, this._itemSize()[0]),
cols: calculateCurrentIndex(scrollLeft, this._itemSize()[1])
};
const triggerIndex = {
rows: calculateTriggerIndex(currentIndex.rows, this.first.rows, this.last.rows, this.numItemsInViewport.rows, this.d_numToleratedItems[0], isScrollDown),
cols: calculateTriggerIndex(currentIndex.cols, this.first.cols, this.last.cols, this.numItemsInViewport.cols, this.d_numToleratedItems[1], isScrollRight)
};
newFirst = {
rows: calculateFirst(currentIndex.rows, triggerIndex.rows, this.first.rows, this.last.rows, this.numItemsInViewport.rows, this.d_numToleratedItems[0], isScrollDown),
cols: calculateFirst(currentIndex.cols, triggerIndex.cols, this.first.cols, this.last.cols, this.numItemsInViewport.cols, this.d_numToleratedItems[1], isScrollRight)
};
newLast = {
rows: calculateLast(currentIndex.rows, newFirst.rows, this.last.rows, this.numItemsInViewport.rows, this.d_numToleratedItems[0]),
cols: calculateLast(currentIndex.cols, newFirst.cols, this.last.cols, this.numItemsInViewport.cols, this.d_numToleratedItems[1], true)
};
isRangeChanged = newFirst.rows !== this.first.rows || newLast.rows !== this.last.rows || newFirst.cols !== this.first.cols || newLast.cols !== this.last.cols || this.isRangeChanged;
newScrollPos = { top: scrollTop, left: scrollLeft };
}
}
else {
const scrollPos = this.horizontal() ? scrollLeft : scrollTop;
const isScrollDownOrRight = this.lastScrollPos <= scrollPos;
if (!this._appendOnly() || (this._appendOnly() && isScrollDownOrRight)) {
const currentIndex = calculateCurrentIndex(scrollPos, this._itemSize());
const triggerIndex = calculateTriggerIndex(currentIndex, this.first, this.last, this.numItemsInViewport, this.d_numToleratedItems, isScrollDownOrRight);
newFirst = calculateFirst(currentIndex, triggerIndex, this.first, this.last, this.numItemsInViewport, this.d_numToleratedItems, isScrollDownOrRight);
newLast = calculateLast(currentIndex, newFirst, this.last, this.numItemsInViewport, this.d_numToleratedItems);
isRangeChanged = newFirst !== this.first || newLast !== this.last || this.isRangeChanged;
newScrollPos = scrollPos;
}
}
return {
first: newFirst,
last: newLast,
isRangeChanged,
scrollPos: newScrollPos
};
}
onScrollChange(event) {
const { first, last, isRangeChanged, scrollPos } = this.onScrollPositionChange(event);
if (isRangeChanged) {
const newState = { first, last };
this.setContentPosition(newState);
this.first = first;
this.last = last;
this.lastScrollPos = scrollPos;
this.handleEvents('onScrollIndexChange', newState);
if (this._lazy() && this.isPageChanged(first)) {
const lazyLoadState = {
first: this._step() ? Math.min(this.getPageByFirst(first) * this._step(), this._items().length - this._step()) : first,
last: Math.min(this._step() ? (this.getPageByFirst(first) + 1) * this._step() : last, this._items().length)
};
const isLazyStateChanged = this.lazyLoadState.first !== lazyLoadState.first || this.lazyLoadState.last !== lazyLoadState.last;
isLazyStateChanged && this.handleEvents('onLazyLoad', lazyLoadState);
this.lazyLoadState = lazyLoadState;
}
}
}
onContainerScroll(event) {
this.handleEvents('onScroll', { originalEvent: event });
if (this._delay()) {
if (this.scrollTimeout) {
clearTimeout(this.scrollTimeout);
}
if (!this.d_loading && this._showLoader()) {
const { isRangeChanged } = this.onScrollPositionChange(event);
const changed = isRangeChanged || (this._step() ? this.isPageChanged() : false);
if (changed) {
this.d_loading = true;
this.cd.detectChanges();
}
}
this.scrollTimeout = setTimeout(() => {
this.onScrollChange(event);
if (this.d_loading && this._showLoader() && (!this._lazy() || this._loading() === undefined)) {
this.d_loading = false;
this.page = this.getPageByFirst();
}
this.cd.detectChanges();
}, this._delay());
}
else {
!this.d_loading && this.onScrollChange(event);
}
}
bindResizeListener() {
if (isPlatformBrowser(this.platformId)) {
if (!this.windowResizeListener) {
const window = this.document.defaultView;
const event = isTouchDevice() ? 'orientationchange' : 'resize';
this.windowResizeListener = this.renderer.listen(window, event, this.onWindowResize.bind(this));
}
}
}
unbindResizeListener() {
if (this.windowResizeListener) {
this.windowResizeListener();
this.windowResizeListener = null;
}
}
onWindowResize() {
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
}
this.resizeTimeout = setTimeout(() => {
if (isVisible(this.elementViewChild()?.nativeElement)) {
const [width, height] = [getWidth(this.elementViewChild()?.nativeElement), getHeight(this.elementViewChild()?.nativeElement)];
const [isDiffWidth, isDiffHeight] = [width !== this.defaultWidth, height !== this.defaultHeight];
const reinit = this.both() ? isDiffWidth || isDiffHeight : this.horizontal() ? isDiffWidth : this.vertical() ? isDiffHeight : false;
if (reinit) {
this.d_numToleratedItems = this._numToleratedItems();
this.defaultWidth = width;
this.defaultHeight = height;
this.defaultContentWidth = getWidth(this.contentEl);
this.defaultContentHeight = getHeight(this.contentEl);
this.init();
}
}
}, this._resizeDelay());
}
handleEvents(name, params) {
// Pending timers / promise microtasks (e.g. the lazy-load Promise.resolve callback) can
// reach this after destroy; bail so we don't emit on a destroyed OutputRef.
if (this._destroyed)
return;
const opts = this.options();
return opts && opts[name] ? opts[name](params) : this[name].emit(params);
}
loaderIconContext = { options: { styleClass: 'p-virtualscroller-loading-icon' } };
getContentTemplateContext() {
return {
$implicit: this.loadedItems,
options: this.getContentOptions()
};
}
getItemTemplateContext(item, index) {
return {
$implicit: item,
options: this.getOptions(index)
};
}
getLoaderTemplateContext(index) {
return {
options: this.getLoaderOptions(index, this.both() && { numCols: this.numItemsInViewport.cols })
};
}
getDisabledContentTemplateContext() {
return {
$implicit: this.items(),
options: { rows: this._items(), columns: this.loadedColumns }
};
}
getContentOptions() {
return {
contentStyleClass: `p-virtualscroller-content ${this.d_loading ? 'p-virtualscroller-loading' : ''}`,
items: this.loadedItems,
getItemOptions: (index) => this.getOptions(index),
loading: this.d_loading,
getLoaderOptions: (index, options) => this.getLoaderOptions(index, options),
itemSize: this._itemSize(),
rows: this.loadedRows,
columns: this.loadedColumns,
spacerStyle: this.spacerStyle,
contentStyle: this.contentStyle,
vertical: this.vertical(),
horizontal: this.horizontal(),
both: this.both(),
scrollTo: this.scrollTo.bind(this),
scrollToIndex: this.scrollToIndex.bind(this),
orientation: this._orientation(),
scrollableElement: this.elementViewChild()?.nativeElement
};
}
getOptions(renderedIndex) {
const count = (this._items() || []).length;
const index = this.both() ? this.first.rows + renderedIndex : this.first + renderedIndex;
return {
index,
count,
first: index === 0,
last: index === count - 1,
even: index % 2 === 0,
odd: index % 2 !== 0
};
}
getLoaderOptions(index, extOptions) {
const count = this.loaderArr.length;
return {
index,
count,
first: index === 0,
last: index === count - 1,
even: index % 2 === 0,
odd: index % 2 !== 0,
loading: this.d_loading,
...extOptions
};
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: Scroller, deps: [], target: i0.ɵɵFactoryTarget.Component });
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.6", type: Scroller, isStandalone: true, selector: "p-scroller, p-virtualscroller, p-virtual-scroller", inputs: { hostName: { classPropertyName: "hostName", publicName: "hostName", isSignal: true, isRequired: false, transformFunction: null }, id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: false, transformFunction: null }, style: { classPropertyName: "style", p