[ADF-5311] Extract infinite select scroll loading logic to a reusable component (#6536)

* move translation to core

* select scroll directive

* register directive

* add infinite scroll directive

* clean up component and aditional logic

* use  waitForAsync over async

* update docs

* change output emitter name

* revert to async

* restore default value;

* test
This commit is contained in:
Cilibiu Bogdan
2021-01-15 13:35:39 +02:00
committed by GitHub
parent c9705b06d5
commit 8471fe40a5
11 changed files with 200 additions and 41 deletions

View File

@@ -138,6 +138,7 @@ The main purpose of the Notification history component is list all the notificat
| [Node Restore directive](core/directives/node-restore.directive.md) | Restores deleted nodes to their original location. | [Source](../lib/core/directives/node-restore.directive.ts) |
| [Upload Directive](core/directives/upload.directive.md) | Uploads content in response to file drag and drop. | [Source](../lib/core/directives/upload.directive.ts) |
| [Version Compatibility Directive](core/directives/version-compatibility.directive.md) | Enables/disables components based on ACS version in use. | [Source](../lib/core/directives/version-compatibility.directive.ts) |
| [Infinite Select Scroll](core/directives/infinite-select-scroll.directive.md) | Load more options to select component if API returns more items. | [Source](../lib/core/directives/infinite-select-scroll.directive.ts) |
### Dialogs

View File

@@ -0,0 +1,30 @@
---
Title: Infinite Select Scroll directive
Added: v4.3.0
Status: Active
Last reviewed: 2020-01-14
---
# [Infinite Select Scroll](../../../lib/core/directives/infinite-select-scroll.directive.ts "Defined in infinite-select-scroll.directive.ts")
Load more options to select component if API returns more items
## Basic Usage
```html
<mat-select
adf-infinite-select-scroll
(scrollEnd)="load()">
<mat-option *ngFor="let option of options">
{{ option }}
</mat-option>
</mat-select>`
```
## Class members
### Events
| Name | Type | Description |
| --- | --- | --- |
| scrollEnd | [`EventEmitter`](https://angular.io/api/core/EventEmitter)`<`[`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event)`>` | Emitted when scroll reaches the last item. |

View File

@@ -30,9 +30,6 @@
"ARROW_ICON": "Arrow right icon"
}
},
"ADF_DROPDOWN": {
"LOADING": "Loading..."
},
"ADF_CONFIRM_DIALOG": {
"TITLE": "Confirm",
"ACTION": "Do you want to proceed?",

View File

@@ -1,6 +1,8 @@
<div id="site-dropdown-container" class="adf-site-dropdown-container">
<mat-form-field>
<mat-select
adf-infinite-select-scroll
(scrollEnd)="loadAllOnScroll()"
#siteSelect
data-automation-id="site-my-files-option"
class="adf-site-dropdown-list-element"

View File

@@ -16,7 +16,7 @@
*/
import { DebugElement } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DropdownSitesComponent, Relations } from './sites-dropdown.component';
import { SitesService, setupTestBed } from '@alfresco/adf-core';
@@ -89,7 +89,7 @@ describe('DropdownSitesComponent', () => {
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(element.querySelector('[data-automation-id="lsite-loading"]')).toBeNull();
expect(element.querySelector('[data-automation-id="site-loading"]')).toBeNull();
});
}));

View File

@@ -15,12 +15,10 @@
* limitations under the License.
*/
import { Component, EventEmitter, Input, OnInit, Output, ViewChild, ViewEncapsulation, OnDestroy } from '@angular/core';
import { SitesService, LogService } from '@alfresco/adf-core';
import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core';
import { SitesService, LogService, InfiniteSelectScrollDirective } from '@alfresco/adf-core';
import { SitePaging, SiteEntry } from '@alfresco/js-api';
import { MatSelect, MatSelectChange } from '@angular/material/select';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { MatSelectChange } from '@angular/material/select';
export enum Relations {
Members = 'members',
@@ -34,7 +32,7 @@ export enum Relations {
encapsulation: ViewEncapsulation.None,
host: { 'class': 'adf-sites-dropdown' }
})
export class DropdownSitesComponent implements OnInit, OnDestroy {
export class DropdownSitesComponent implements OnInit {
/** Hide the "My Files" option. */
@Input()
@@ -71,15 +69,8 @@ export class DropdownSitesComponent implements OnInit, OnDestroy {
@Output()
change: EventEmitter<SiteEntry> = new EventEmitter();
@ViewChild('siteSelect', { static: true })
siteSelect: MatSelect;
private loading = true;
private skipCount = 0;
private readonly MAX_ITEMS = 50;
private readonly ITEM_HEIGHT = 45;
private readonly ITEM_HEIGHT_TO_WAIT_BEFORE_LOAD_NEXT = (this.ITEM_HEIGHT * (this.MAX_ITEMS / 2));
private onDestroy$ = new Subject<boolean>();
selected: SiteEntry = null;
MY_FILES_VALUE = '-my-';
@@ -89,35 +80,18 @@ export class DropdownSitesComponent implements OnInit, OnDestroy {
}
ngOnInit() {
this.siteSelect.openedChange
.pipe(takeUntil(this.onDestroy$))
.subscribe(() => {
if (this.siteSelect.panelOpen) {
this.siteSelect.panel.nativeElement.addEventListener('scroll', (event) => this.loadAllOnScroll(event));
}
});
if (!this.siteList) {
this.loadSiteList();
}
}
ngOnDestroy() {
this.onDestroy$.next(true);
this.onDestroy$.complete();
}
loadAllOnScroll(event) {
if (this.isInfiniteScrollingEnabled() && this.isScrollInNextFetchArea(event)) {
loadAllOnScroll() {
if (this.isInfiniteScrollingEnabled()) {
this.loading = true;
this.loadSiteList();
}
}
isScrollInNextFetchArea(event) {
return event.target.scrollTop >= (event.target.scrollHeight - event.target.offsetHeight - this.ITEM_HEIGHT_TO_WAIT_BEFORE_LOAD_NEXT);
}
selectedSite(event: MatSelectChange) {
this.change.emit(event.value);
}
@@ -125,10 +99,10 @@ export class DropdownSitesComponent implements OnInit, OnDestroy {
private loadSiteList() {
const extendedOptions: any = {
skipCount: this.skipCount,
maxItems: this.MAX_ITEMS
maxItems: InfiniteSelectScrollDirective.MAX_ITEMS
};
this.skipCount += this.MAX_ITEMS;
this.skipCount += InfiniteSelectScrollDirective.MAX_ITEMS;
if (this.relations) {
extendedOptions.relations = [this.relations];

View File

@@ -31,6 +31,7 @@ import { VersionCompatibilityDirective } from './version-compatibility.directive
import { TooltipCardDirective } from './tooltip-card/tooltip-card.directive';
import { OverlayModule } from '@angular/cdk/overlay';
import { TooltipCardComponent } from './tooltip-card/tooltip-card.component';
import { InfiniteSelectScrollDirective } from './infinite-select-scroll.directive';
@NgModule({
imports: [
@@ -49,7 +50,8 @@ import { TooltipCardComponent } from './tooltip-card/tooltip-card.component';
UploadDirective,
VersionCompatibilityDirective,
TooltipCardDirective,
TooltipCardComponent
TooltipCardComponent,
InfiniteSelectScrollDirective
],
exports: [
HighlightDirective,
@@ -61,7 +63,8 @@ import { TooltipCardComponent } from './tooltip-card/tooltip-card.component';
NodeDownloadDirective,
UploadDirective,
VersionCompatibilityDirective,
TooltipCardDirective
TooltipCardDirective,
InfiniteSelectScrollDirective
]
})
export class DirectiveModule {}

View File

@@ -0,0 +1,82 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Component, ViewChild } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, TestBed } from '@angular/core/testing';
import { InfiniteSelectScrollDirective } from './infinite-select-scroll.directive';
import { setupTestBed } from '../testing/setup-test-bed';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
@Component({
template: `
<mat-select adf-infinite-select-scroll (scrollEnd)="load()" >
<mat-option *ngFor="let option of options; let idx=index">
{{ option.text }}
</mat-option>
</mat-select>`
})
class TestComponent {
options = new Array(50).fill({text: 'dummy'});
@ViewChild(MatSelect, { static: true })
matSelect: MatSelect;
open() {
this.matSelect.open();
}
load() {
this.options.push(...new Array(10).fill({text: 'dummy'}));
}
}
describe('InfiniteSelectScrollDirective', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
setupTestBed({
imports: [
MatSelectModule,
NoopAnimationsModule
],
declarations: [
TestComponent,
InfiniteSelectScrollDirective
]
});
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
beforeEach(fakeAsync(() => {
fixture.detectChanges();
component.open();
fixture.detectChanges();
flush();
}));
it('should call an action on scrollEnd event', fakeAsync(() => {
const panel = document.querySelector('.mat-select-panel') as HTMLElement;
panel.scrollTop = panel.scrollHeight;
panel.dispatchEvent(new Event('scroll'));
fixture.detectChanges();
expect(component.options.length).toBe(60);
}));
});

View File

@@ -0,0 +1,66 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Inject, AfterViewInit, Directive, EventEmitter, OnDestroy, Output } from '@angular/core';
import { MatSelect, SELECT_ITEM_HEIGHT_EM } from '@angular/material/select';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Directive({
selector: '[adf-infinite-select-scroll]'
})
export class InfiniteSelectScrollDirective implements AfterViewInit, OnDestroy {
static readonly MAX_ITEMS = 50;
@Output() scrollEnd = new EventEmitter<Event>();
private onDestroy$ = new Subject<boolean>();
private itemHeightToWaitBeforeLoadNext = 0;
constructor(@Inject(MatSelect) private matSelect: MatSelect) {}
ngAfterViewInit() {
this.matSelect.openedChange
.pipe(takeUntil(this.onDestroy$))
.subscribe((opened: boolean) => {
if (opened) {
this.itemHeightToWaitBeforeLoadNext = (this.getItemHeight() * (InfiniteSelectScrollDirective.MAX_ITEMS / 2));
this.matSelect.panel.nativeElement.addEventListener('scroll', (event: Event) => this.handleScrollEvent(event));
}
});
}
ngOnDestroy() {
this.onDestroy$.next(true);
this.onDestroy$.complete();
}
private handleScrollEvent(event: Event) {
if (this.isScrollInNextFetchArea(event)) {
this.scrollEnd.emit(event);
}
}
private isScrollInNextFetchArea(event: Event): boolean {
const target = event.target as HTMLElement;
return target.scrollTop >= (target.scrollHeight - target.offsetHeight - this.itemHeightToWaitBeforeLoadNext);
}
private getItemHeight(): number {
return parseFloat(getComputedStyle(this.matSelect.panel.nativeElement).fontSize || '0') * SELECT_ITEM_HEIGHT_EM;
}
}

View File

@@ -25,5 +25,6 @@ export * from './node-download.directive';
export * from './upload.directive';
export * from './version-compatibility.directive';
export * from './tooltip-card/tooltip-card.directive';
export * from './infinite-select-scroll.directive';
export * from './directive.module';

View File

@@ -529,5 +529,8 @@
"BUTTON": {
"ARIA_LABEL": "Clear"
}
},
"ADF_DROPDOWN": {
"LOADING": "Loading..."
}
}