Skip to content

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

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

Merged
merged 14 commits into from
Jul 25, 2018
Merged
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
1 change: 1 addition & 0 deletions src/cdk-experimental/scrolling/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ ng_module(
deps = [
"//src/cdk/coercion",
"//src/cdk/collections",
"//src/cdk/platform",
"@rxjs",
],
tsconfig = "//src/cdk-experimental:tsconfig-build.json",
Expand Down
7 changes: 7 additions & 0 deletions src/cdk-experimental/scrolling/auto-size-virtual-scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
11 changes: 11 additions & 0 deletions src/cdk-experimental/scrolling/fixed-size-virtual-scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
7 changes: 7 additions & 0 deletions src/cdk-experimental/scrolling/virtual-scroll-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
50 changes: 50 additions & 0 deletions src/cdk-experimental/scrolling/virtual-scroll-viewport.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,56 @@ describe('CdkVirtualScrollViewport', () => {
expect(viewport.getRenderedRange()).toEqual({start: 2, end: 6});
}));

it('should scroll to offset', fakeAsync(() => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a test for horizontal mode?

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);

Expand Down
32 changes: 31 additions & 1 deletion src/cdk-experimental/scrolling/virtual-scroll-viewport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import {ListRange} from '@angular/cdk/collections';
import {supportsScrollBehavior} from '@angular/cdk/platform';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Expand Down Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/cdk/platform/features.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>;

Expand Down
29 changes: 26 additions & 3 deletions src/demo-app/virtual-scroll/virtual-scroll-demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,30 @@ <h3>Random size</h3>

<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)
Expand Down Expand Up @@ -97,8 +120,8 @@ <h2>trackBy state name</h2>

<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>
Expand Down
3 changes: 3 additions & 0 deletions src/demo-app/virtual-scroll/virtual-scroll-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down