Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat (v18): Modernize virtualscroller and expand test #16594

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/app/components/virtualscroller/virtualscroller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { ComponentRef } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { VirtualScroller, VirtualScrollerModule } from './virtualscroller';

describe('VirtualScroller', () => {
let virtualScroller: VirtualScroller;
let fixture: ComponentFixture<VirtualScroller>;
let virtualScrollerRef: ComponentRef<VirtualScroller>;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [NoopAnimationsModule, VirtualScrollerModule],
});

fixture = TestBed.createComponent(VirtualScroller);
virtualScroller = fixture.componentInstance;
virtualScrollerRef = fixture.componentRef;
});

it('should render the VirtualScroller with default inputs', () => {
fixture.detectChanges();

const virtualScrollerElement = fixture.nativeElement.querySelector('.p-virtualscroller');
expect(virtualScrollerElement).toBeTruthy();
});

it('should apply the correct style and styleClass', () => {
virtualScrollerRef.setInput('style', { 'max-height': '500px' });
virtualScrollerRef.setInput('styleClass', 'custom-class');
fixture.detectChanges();

const virtualScrollerElement = fixture.nativeElement.querySelector('.p-virtualscroller');
expect(virtualScrollerElement.style.maxHeight).toBe('500px');
expect(virtualScrollerElement.classList).toContain('custom-class');
});

it('should scroll to the specified index', () => {
spyOn(virtualScroller.scroller(), 'scrollToIndex');

virtualScroller.scrollToIndex(10);
fixture.detectChanges();

expect(virtualScroller.scroller().scrollToIndex).toHaveBeenCalledWith(10, undefined);
});
});
139 changes: 62 additions & 77 deletions src/app/components/virtualscroller/virtualscroller.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { CommonModule } from '@angular/common';
import { NgClass, NgStyle, NgTemplateOutlet } from '@angular/common';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
contentChild,
contentChildren,
ElementRef,
EventEmitter,
Input,
OutputEmitterRef,
input,
NgModule,
Output,
QueryList,
output,
Signal,
TemplateRef,
ViewChild,
viewChild,
ViewEncapsulation,
booleanAttribute,
numberAttribute,
computed,
inject,
} from '@angular/core';
import { BlockableUI, Footer, Header, PrimeTemplate, ScrollerOptions, SharedModule } from 'primeng/api';
import { Scroller } from 'primeng/scroller';
Expand All @@ -31,143 +32,127 @@ import { VirtualScrollerLazyLoadEvent } from './virtualscroller.interface';
template: `
<div
[ngClass]="'p-virtualscroller p-component'"
[ngStyle]="style"
[class]="styleClass"
[ngStyle]="style()"
[class]="styleClass()"
[attr.data-pc-name]="'virtualscroller'"
[attr.data-pc-section]="'root'"
>
<div class="p-virtualscroller-header" *ngIf="header || headerTemplate">
<ng-content select="p-header"></ng-content>
<ng-container *ngTemplateOutlet="headerTemplate"></ng-container>
</div>
@if (header() || headerTemplate()) {
<div class="p-virtualscroller-header">
<ng-content select="p-header"></ng-content>
<ng-container *ngTemplateOutlet="headerTemplate()"></ng-container>
</div>
}
<div #content class="p-virtualscroller-content" [attr.data-pc-section]="'content'">
<p-scroller
#scroller
[items]="value"
[items]="value()"
styleClass="p-virtualscroller-list"
[style]="{ height: scrollHeight }"
[itemSize]="itemSize"
[lazy]="lazy"
[style]="{ height: scrollHeight() }"
[itemSize]="itemSize()"
[lazy]="lazy()"
(onLazyLoad)="onLazyItemLoad($event)"
[options]="options"
[options]="options()"
>
<ng-template #item let-item let-scrollerOptions="options">
<div [ngStyle]="{ height: itemSize + 'px' }" class="p-virtualscroller-item">
<div [style.height.px]="itemSize()" class="p-virtualscroller-item">
<ng-container
*ngTemplateOutlet="
item ? itemTemplate : loadingItemTemplate;
item ? itemTemplate() : loadingItemTemplate();
context: { $implicit: item, options: scrollerOptions }
"
></ng-container>
</div>
</ng-template>
</p-scroller>
</div>
<div class="p-virtualscroller-footer" *ngIf="footer || footerTemplate" [attr.data-pc-section]="'footer'">
<ng-content select="p-footer"></ng-content>
<ng-container *ngTemplateOutlet="footerTemplate"></ng-container>
</div>
@if (footer() || footerTemplate()) {
<div class="p-virtualscroller-footer" [attr.data-pc-section]="'footer'">
<ng-content select="p-footer"></ng-content>
medbenmakhlouf marked this conversation as resolved.
Show resolved Hide resolved
<ng-container *ngTemplateOutlet="footerTemplate()"></ng-container>
</div>
}
</div>
`,
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None,
})
export class VirtualScroller implements AfterContentInit, BlockableUI {
export class VirtualScroller implements BlockableUI {
/**
* An array of objects to display.
* @group Props
*/
@Input() value: any[] | undefined;
value = input<any[]>();
/**
* Height of an item in the list.
* @group Props
*/
@Input({ transform: numberAttribute }) itemSize: number | undefined;
itemSize = input<number, any>(undefined, { transform: numberAttribute });
/**
* Inline style of the component.
* @group Props
*/
@Input() style: { [klass: string]: any } | null | undefined;
style = input<{ [klass: string]: any } | null>();
/**
* Style class of the component.
* @group Props
*/
@Input() styleClass: string | undefined;
styleClass = input<string>();
/**
* Max height of the content area in inline mode.
* @group Props
*/
@Input() scrollHeight: any;
scrollHeight = input<any>();
/**
* Defines if data is loaded and interacted with in lazy manner.
* @group Props
*/
@Input({ transform: booleanAttribute }) lazy: boolean | undefined;
lazy = input<boolean, any>(undefined, { transform: booleanAttribute });
/**
* Whether to use the scroller feature. The properties of scroller component can be used like an object in it.
* @group Props
*/
@Input() options: ScrollerOptions | undefined;
options = input<ScrollerOptions>();
/**
* Threshold in milliseconds to delay lazy loading during scrolling.
* @group Props
*/
@Input({ transform: numberAttribute }) delay: number = 250;
delay = input<number, any>(250, { transform: numberAttribute });
/**
* Callback to invoke in lazy mode to load new data.
* @param {VirtualScrollerLazyLoadEvent} event - custom lazy load event.
* @group Emits
*/
@Output() onLazyLoad: EventEmitter<VirtualScrollerLazyLoadEvent> = new EventEmitter<VirtualScrollerLazyLoadEvent>();
onLazyLoad: OutputEmitterRef<VirtualScrollerLazyLoadEvent> = output<VirtualScrollerLazyLoadEvent>();

@ContentChild(Header) header: Header | undefined;
header = contentChild<Header | undefined>(Header);

@ContentChild(Footer) footer: Footer | undefined;
footer = contentChild<Footer | undefined>(Footer);

@ContentChildren(PrimeTemplate) templates: Nullable<QueryList<PrimeTemplate>>;
templates: Signal<readonly PrimeTemplate[]> = contentChildren(PrimeTemplate);

@ViewChild('scroller') scroller: Nullable<Scroller>;
scroller = viewChild<Nullable<Scroller>>('scroller');

itemTemplate: Nullable<TemplateRef<any>>;
itemTemplate = computed<Nullable<TemplateRef<any>>>(() => this.mappedTemplates()['item']);

headerTemplate: Nullable<TemplateRef<any>>;
headerTemplate = computed<Nullable<TemplateRef<any>>>(() => this.mappedTemplates()['header']);

footerTemplate: Nullable<TemplateRef<any>>;
footerTemplate = computed<Nullable<TemplateRef<any>>>(() => this.mappedTemplates()['footer']);

loadingItemTemplate: Nullable<TemplateRef<any>>;
loadingItemTemplate = computed<Nullable<TemplateRef<any>>>(() => this.mappedTemplates()['loadingItem']);

virtualScrollTimeout: any;

constructor(
public el: ElementRef,
public cd: ChangeDetectorRef,
) {}

ngAfterContentInit() {
(this.templates as QueryList<PrimeTemplate>).forEach((item) => {
switch (item.getType()) {
case 'item':
this.itemTemplate = item.template;
break;

case 'loadingItem':
this.loadingItemTemplate = item.template;
break;

case 'header':
this.headerTemplate = item.template;
break;

case 'footer':
this.footerTemplate = item.template;
break;

default:
this.itemTemplate = item.template;
break;
}
});
}
private mappedTemplates = computed<{ [key: string]: TemplateRef<any> }>(() => {
return (this.templates() || []).reduce((prev, item) => {
prev[item.getType()] = item.template;
return prev;
}, {});
});

el = inject(ElementRef);

cd = inject(ChangeDetectorRef);

onLazyItemLoad(event: VirtualScrollerLazyLoadEvent) {
if (this.virtualScrollTimeout) {
Expand All @@ -180,20 +165,20 @@ export class VirtualScroller implements AfterContentInit, BlockableUI {
rows: <number>event.last - <number>event.first,
forceUpdate: () => this.cd.detectChanges(),
});
}, this.delay);
}, this.delay());
}

getBlockableElement(): HTMLElement {
return this.el.nativeElement.children[0];
}

scrollToIndex(index: number, mode?: ScrollBehavior): void {
this.scroller?.scrollToIndex(index, mode);
this.scroller()?.scrollToIndex(index, mode);
}
}

@NgModule({
imports: [CommonModule, SharedModule, Scroller],
imports: [NgClass, NgStyle, NgTemplateOutlet, SharedModule, Scroller],
exports: [VirtualScroller, SharedModule, Scroller],
declarations: [VirtualScroller],
})
Expand Down
Loading