Skip to content
This repository has been archived by the owner on Jun 17, 2022. It is now read-only.

Commit

Permalink
Use custom virtual scroll strategy (#452)
Browse files Browse the repository at this point in the history
* Add CipherListVirtualScroll strategy

For use in cdk-virtual-scroll. Subclasses the default FixedSizeVirtualScroll
but reads the first available itemSize from the rendered content instead of
setting it in the template.

* Fix linting and style

* Refactor virtual scroll strategy

* linting and style

* Subclass virtual scroll strategy directive

* fix linting

* Fix filename conventions
  • Loading branch information
eliykat committed Aug 11, 2021
1 parent a2b6275 commit c70c8ec
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions angular/src/directives/cipherListVirtualScroll.directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
CdkFixedSizeVirtualScroll,
FixedSizeVirtualScrollStrategy,
VIRTUAL_SCROLL_STRATEGY,
} from '@angular/cdk/scrolling';
import {
Directive,
forwardRef,
} from '@angular/core';

// Custom virtual scroll strategy for cdk-virtual-scroll
// Uses a sample list item to set the itemSize for FixedSizeVirtualScrollStrategy
// The use case is the same as FixedSizeVirtualScrollStrategy, but it avoids locking in pixel sizes in the template.
export class CipherListVirtualScrollStrategy extends FixedSizeVirtualScrollStrategy {
private checkItemSizeCallback: any;
private timeout: any;

constructor(itemSize: number, minBufferPx: number, maxBufferPx: number, checkItemSizeCallback: any) {
super(itemSize, minBufferPx, maxBufferPx);
this.checkItemSizeCallback = checkItemSizeCallback;
}

onContentRendered() {
if (this.timeout != null) {
clearTimeout(this.timeout);
}

this.timeout = setTimeout(this.checkItemSizeCallback, 500);
}
}

export function _cipherListVirtualScrollStrategyFactory(cipherListDir: CipherListVirtualScroll) {
return cipherListDir._scrollStrategy;
}

@Directive({
selector: 'cdk-virtual-scroll-viewport[itemSize]',
providers: [{
provide: VIRTUAL_SCROLL_STRATEGY,
useFactory: _cipherListVirtualScrollStrategyFactory,
deps: [forwardRef(() => CipherListVirtualScroll)],
}],
})
export class CipherListVirtualScroll extends CdkFixedSizeVirtualScroll {
_scrollStrategy: CipherListVirtualScrollStrategy;

constructor() {
super();
this._scrollStrategy = new CipherListVirtualScrollStrategy(this.itemSize, this.minBufferPx, this.maxBufferPx,
this.checkAndUpdateItemSize);
}

checkAndUpdateItemSize = () => {
const sampleItem = document.querySelector('cdk-virtual-scroll-viewport .virtual-scroll-item') as HTMLElement;
const newItemSize = sampleItem?.offsetHeight;

if (newItemSize != null && newItemSize !== this.itemSize) {
this.itemSize = newItemSize;
this._scrollStrategy.updateItemAndBufferSize(this.itemSize, this.minBufferPx, this.maxBufferPx);
}
}
}

0 comments on commit c70c8ec

Please sign in to comment.