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 10 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() {
// 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
7 changes: 7 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,13 @@ export class FixedSizeVirtualScrollStrategy implements VirtualScrollStrategy {
/** @docs-private Implemented as part of VirtualScrollStrategy. */
onRenderedOffsetChanged() { /* no-op */ }

/** Scroll to the offset for the given index. */
scrollToIndex(index: number, behavior: ScrollBehavior) {
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 return type here since it's part of the public API. I think some of the other methods are missing return types as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh this actually doesn't return anything, must've put that by mistake

Copy link
Member

Choose a reason for hiding this comment

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

It should still have void, though, since dgeni can't use the inferred types. Also missing @param JsDocs

if (this._viewport) {
return this._viewport.scrollToOffset(index * this._itemSize, behavior);
}
}

/** Update the viewport's total content size. */
private _updateTotalContentSize() {
if (!this._viewport) {
Expand Down
3 changes: 3 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,7 @@ export interface VirtualScrollStrategy {

/** Called when the offset of the rendered items changed. */
onRenderedOffsetChanged();

/** Scroll to the offset for the given index. */
scrollToIndex(index: number, behavior: ScrollBehavior);
}
24 changes: 24 additions & 0 deletions src/cdk-experimental/scrolling/virtual-scroll-viewport.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,30 @@ 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 update viewport as user scrolls down', fakeAsync(() => {
finishInit(fixture);

Expand Down
24 changes: 23 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,28 @@ export class CdkVirtualScrollViewport implements OnInit, OnDestroy {
}
}

/** Sets the scroll offset on the viewport. */
/** Scrolls to the offset on the viewport. */
scrollToOffset(offset: number, behavior: ScrollBehavior = 'auto') {
Copy link
Member

Choose a reason for hiding this comment

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

Add @param JsDocs?

const viewportElement = this.elementRef.nativeElement;
const offsetDirection = this.orientation === 'horizontal' ? 'left' : 'top';
Copy link
Member

Choose a reason for hiding this comment

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

Seems like this variable is only used when the scroll behavior is supported. Consider moving it into the if.


if (supportsScrollBehavior()) {
Copy link
Member

Choose a reason for hiding this comment

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

Why do this differently based on scroll-behavior? Wouldn't that option just be ignored if it's not supported?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The method signatures aren't compatible, old browsers only support:
scrollTo(top: number, left: number)

The new ones also support:
scrollTo({top?: number, left?: number, behavior?: ScrollBehavior})

viewportElement.scrollTo({[offsetDirection]: offset, behavior});
} else {
if (this.orientation === 'horizontal') {
viewportElement.scrollLeft = offset;
} else {
viewportElement.scrollTop = offset;
}
}
}

/** Scroll the viewport to the specified index. */
scrollToIndex(index: number, behavior: ScrollBehavior = 'auto') {
this._scrollStrategy.scrollToIndex(index, behavior);
}

/** 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
5 changes: 5 additions & 0 deletions src/cdk/platform/features.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ export function supportsPassiveEventListeners(): boolean {
return supportsPassiveEvents;
}

/** Check whether the browser supports scroll behaviors. */
export function supportsScrollBehavior(): boolean {
return 'scrollBehavior' in document.documentElement.style;
Copy link
Member

Choose a reason for hiding this comment

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

This will probably throw an error in Universal.

}

/** 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 @@ -24,6 +24,9 @@ type State = {
encapsulation: ViewEncapsulation.None,
})
export class VirtualScrollDemo {
scrollToOffset = 0;
scrollToIndex = 0;
scrollToBehavior = '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