virtual-scroll: add support for scrollToOffset and scrollToIndex (#12272)

Note: `scrollToIndex` currently does not work with the `AutoSizeVirtualScrollStrategy`. Support for this will be added in a future PR.

This PR is based off #11498 by @amcdnl. I removed the `lazy` option from #11498 to avoid bloating the API. I'm not sure how common the use case is, and its relatively simple to implement on top using the current APIs.
This commit is contained in:
mmalerba
2018-07-24 19:22:40 -07:00
committed by GitHub
parent 60b9928f34
commit 6a0b8f79a4
9 changed files with 142 additions and 4 deletions
@@ -12,6 +12,7 @@ ng_module(
deps = [
"//src/cdk/coercion",
"//src/cdk/collections",
"//src/cdk/platform",
"@rxjs",
],
tsconfig = "//src/cdk-experimental:tsconfig-build.json",
@@ -151,6 +151,13 @@ export class AutoSizeVirtualScrollStrategy implements VirtualScrollStrategy {
}
}
/** Scroll to the offset for the given index. */
scrollToIndex(): void {
// TODO(mmalerba): Implement.
throw new Error('cdk-virtual-scroll: scrollToIndex is currently not supported for the autosize'
+ ' scroll strategy');
}
/**
* Update the buffer parameters.
* @param minBufferPx The minimum amount of buffer rendered beyond the viewport (in pixels).
@@ -77,6 +77,17 @@ export class FixedSizeVirtualScrollStrategy implements VirtualScrollStrategy {
/** @docs-private Implemented as part of VirtualScrollStrategy. */
onRenderedOffsetChanged() { /* no-op */ }
/**
* Scroll to the offset for the given index.
* @param index The index of the element to scroll to.
* @param behavior The ScrollBehavior to use when scrolling.
*/
scrollToIndex(index: number, behavior: ScrollBehavior): void {
if (this._viewport) {
this._viewport.scrollToOffset(index * this._itemSize, behavior);
}
}
/** Update the viewport's total content size. */
private _updateTotalContentSize() {
if (!this._viewport) {
@@ -37,4 +37,11 @@ export interface VirtualScrollStrategy {
/** Called when the offset of the rendered items changed. */
onRenderedOffsetChanged();
/**
* Scroll to the offset for the given index.
* @param index The index of the element to scroll to.
* @param behavior The ScrollBehavior to use when scrolling.
*/
scrollToIndex(index: number, behavior: ScrollBehavior): void;
}
@@ -156,6 +156,56 @@ describe('CdkVirtualScrollViewport', () => {
expect(viewport.getRenderedRange()).toEqual({start: 2, end: 6});
}));
it('should scroll to offset', fakeAsync(() => {
finishInit(fixture);
viewport.scrollToOffset(testComponent.itemSize * 2);
triggerScroll(viewport);
fixture.detectChanges();
flush();
expect(viewport.elementRef.nativeElement.scrollTop).toBe(testComponent.itemSize * 2);
expect(viewport.getRenderedRange()).toEqual({start: 2, end: 6});
}));
it('should scroll to index', fakeAsync(() => {
finishInit(fixture);
viewport.scrollToIndex(2);
triggerScroll(viewport);
fixture.detectChanges();
flush();
expect(viewport.elementRef.nativeElement.scrollTop).toBe(testComponent.itemSize * 2);
expect(viewport.getRenderedRange()).toEqual({start: 2, end: 6});
}));
it('should scroll to offset in horizontal mode', fakeAsync(() => {
testComponent.orientation = 'horizontal';
finishInit(fixture);
viewport.scrollToOffset(testComponent.itemSize * 2);
triggerScroll(viewport);
fixture.detectChanges();
flush();
expect(viewport.elementRef.nativeElement.scrollLeft).toBe(testComponent.itemSize * 2);
expect(viewport.getRenderedRange()).toEqual({start: 2, end: 6});
}));
it('should scroll to index in horizontal mode', fakeAsync(() => {
testComponent.orientation = 'horizontal';
finishInit(fixture);
viewport.scrollToIndex(2);
triggerScroll(viewport);
fixture.detectChanges();
flush();
expect(viewport.elementRef.nativeElement.scrollLeft).toBe(testComponent.itemSize * 2);
expect(viewport.getRenderedRange()).toEqual({start: 2, end: 6});
}));
it('should update viewport as user scrolls down', fakeAsync(() => {
finishInit(fixture);
@@ -7,6 +7,7 @@
*/
import {ListRange} from '@angular/cdk/collections';
import {supportsScrollBehavior} from '@angular/cdk/platform';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
@@ -245,7 +246,36 @@ export class CdkVirtualScrollViewport implements OnInit, OnDestroy {
}
}
/** Sets the scroll offset on the viewport. */
/**
* Scrolls to the offset on the viewport.
* @param offset The offset to scroll to.
* @param behavior The ScrollBehavior to use when scrolling. Default is behavior is `auto`.
*/
scrollToOffset(offset: number, behavior: ScrollBehavior = 'auto') {
const viewportElement = this.elementRef.nativeElement;
if (supportsScrollBehavior()) {
const offsetDirection = this.orientation === 'horizontal' ? 'left' : 'top';
viewportElement.scrollTo({[offsetDirection]: offset, behavior});
} else {
if (this.orientation === 'horizontal') {
viewportElement.scrollLeft = offset;
} else {
viewportElement.scrollTop = offset;
}
}
}
/**
* Scrolls to the offset for the given index.
* @param index The index of the element to scroll to.
* @param behavior The ScrollBehavior to use when scrolling. Default is behavior is `auto`.
*/
scrollToIndex(index: number, behavior: ScrollBehavior = 'auto') {
this._scrollStrategy.scrollToIndex(index, behavior);
}
/** @docs-private Internal method to set the scroll offset on the viewport. */
setScrollOffset(offset: number) {
// Rather than setting the offset immediately, we batch it up to be applied along with other DOM
// writes during the next change detection cycle.
+6
View File
@@ -27,6 +27,12 @@ export function supportsPassiveEventListeners(): boolean {
return supportsPassiveEvents;
}
/** Check whether the browser supports scroll behaviors. */
export function supportsScrollBehavior(): boolean {
return !!(document && document.documentElement && document.documentElement.style &&
'scrollBehavior' in document.documentElement.style);
}
/** Cached result Set of input types support by the current browser. */
let supportedInputTypes: Set<string>;
@@ -34,7 +34,30 @@
<h2>Fixed size</h2>
<cdk-virtual-scroll-viewport class="demo-viewport" [itemSize]="50">
<mat-form-field>
<mat-label>Behavior</mat-label>
<mat-select [(ngModel)]="scrollToBehavior">
<mat-option value="auto">Auto</mat-option>
<mat-option value="instant">Instant</mat-option>
<mat-option value="smooth">Smooth</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Offset</mat-label>
<input matInput type="number" [(ngModel)]="scrollToOffset">
</mat-form-field>
<button mat-button (click)="viewport1.scrollToOffset(scrollToOffset, scrollToBehavior)">
Go to offset
</button>
<mat-form-field>
<mat-label>Index</mat-label>
<input matInput type="number" [(ngModel)]="scrollToIndex">
</mat-form-field>
<button mat-button (click)="viewport1.scrollToIndex(scrollToIndex, scrollToBehavior)">
Go to index
</button>
<cdk-virtual-scroll-viewport class="demo-viewport" [itemSize]="50" #viewport1>
<div *cdkVirtualFor="let size of fixedSizeData; let i = index" class="demo-item"
[style.height.px]="size">
Item #{{i}} - ({{size}}px)
@@ -97,8 +120,8 @@
<h2>Use with <code>&lt;ol&gt;</code></h2>
<cdk-virtual-scroll-viewport class="demo-viewport" autosize #viewport>
<ol class="demo-ol" [start]="viewport.getRenderedRange().start + 1">
<cdk-virtual-scroll-viewport class="demo-viewport" autosize #viewport2>
<ol class="demo-ol" [start]="viewport2.getRenderedRange().start + 1">
<li *cdkVirtualFor="let state of statesObservable | async" class="demo-li">
{{state.name}} - {{state.capital}}
</li>
@@ -25,6 +25,9 @@ type State = {
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class VirtualScrollDemo {
scrollToOffset = 0;
scrollToIndex = 0;
scrollToBehavior: ScrollBehavior = 'auto';
fixedSizeData = Array(10000).fill(50);
increasingSizeData = Array(10000).fill(0).map((_, i) => (1 + Math.floor(i / 1000)) * 20);
decreasingSizeData = Array(10000).fill(0)