Prettier upgrade and e2e type checks (#1522)

* upgrade prettier

* noImplicitAny rule

* fix type

* update tsconfig

* upgrade to 150 print width
This commit is contained in:
Denys Vuika
2020-07-14 10:03:23 +01:00
committed by GitHub
parent 32793ea7b0
commit ddc6f36ab4
339 changed files with 5170 additions and 8763 deletions

View File

@@ -48,15 +48,12 @@ export class AboutComponent implements OnInit {
adfVersion = '';
appVersion = version;
constructor(
private contentApi: ContentApiService,
appExtensions: AppExtensionService
) {
constructor(private contentApi: ContentApiService, appExtensions: AppExtensionService) {
this.extensions$ = appExtensions.references$;
}
ngOnInit() {
this.dependencyEntries = Object.keys(dependencies).map(key => {
this.dependencyEntries = Object.keys(dependencies).map((key) => {
if (key === '@alfresco/adf-core') {
this.adfVersion = dependencies[key].split('-')[0];
const adfCurrentCommit = dependencies[key].split('-')[1] || '';
@@ -70,11 +67,11 @@ export class AboutComponent implements OnInit {
this.contentApi
.getRepositoryInformation()
.pipe(map(node => node.entry.repository))
.subscribe(repository => {
.pipe(map((node) => node.entry.repository))
.subscribe((repository) => {
this.repository = repository;
this.statusEntries = Object.keys(repository.status).map(key => {
this.statusEntries = Object.keys(repository.status).map((key) => {
return {
property: key,
value: repository.status[key]
@@ -82,7 +79,7 @@ export class AboutComponent implements OnInit {
});
if (repository.license) {
this.licenseEntries = Object.keys(repository.license).map(key => {
this.licenseEntries = Object.keys(repository.license).map((key) => {
return {
property: key,
value: repository.license[key]

View File

@@ -47,20 +47,7 @@ const routes: Routes = [
];
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
RouterModule.forChild(routes),
AppLayoutModule,
MatTableModule
],
declarations: [
AboutComponent,
PackageListComponent,
ExtensionListComponent,
StatusListComponent,
ModuleListComponent,
LicenseListComponent
]
imports: [CommonModule, CoreModule.forChild(), RouterModule.forChild(routes), AppLayoutModule, MatTableModule],
declarations: [AboutComponent, PackageListComponent, ExtensionListComponent, StatusListComponent, ModuleListComponent, LicenseListComponent]
})
export class AboutModule {}

View File

@@ -23,12 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
Input
} from '@angular/core';
import { Component, ViewEncapsulation, ChangeDetectionStrategy, Input } from '@angular/core';
import { ExtensionRef } from '@alfresco/adf-extensions';
@Component({
@@ -71,7 +66,7 @@ export class ExtensionListComponent {
}
];
displayedColumns = this.columns.map(x => x.columnDef);
displayedColumns = this.columns.map((x) => x.columnDef);
@Input()
data: Array<ExtensionRef> = [];

View File

@@ -28,12 +28,7 @@ export interface LicenseData {
value: string;
}
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
Input
} from '@angular/core';
import { Component, ViewEncapsulation, ChangeDetectionStrategy, Input } from '@angular/core';
@Component({
selector: 'app-license-list',
@@ -55,7 +50,7 @@ export class LicenseListComponent {
}
];
displayedColumns = this.columns.map(x => x.columnDef);
displayedColumns = this.columns.map((x) => x.columnDef);
@Input()
data: Array<LicenseData> = [];

View File

@@ -23,12 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
Input
} from '@angular/core';
import { Component, ViewEncapsulation, ChangeDetectionStrategy, Input } from '@angular/core';
import { ModuleInfo } from '@alfresco/js-api';
@Component({
@@ -56,7 +51,7 @@ export class ModuleListComponent {
}
];
displayedColumns = this.columns.map(x => x.columnDef);
displayedColumns = this.columns.map((x) => x.columnDef);
@Input()
data: Array<ModuleInfo> = [];

View File

@@ -23,12 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
Input
} from '@angular/core';
import { Component, ViewEncapsulation, ChangeDetectionStrategy, Input } from '@angular/core';
export interface PackageInfo {
name: string;
@@ -55,7 +50,7 @@ export class PackageListComponent {
}
];
displayedColumns = this.columns.map(x => x.columnDef);
displayedColumns = this.columns.map((x) => x.columnDef);
@Input()
data: Array<PackageInfo> = [];

View File

@@ -23,12 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
Input
} from '@angular/core';
import { Component, ViewEncapsulation, ChangeDetectionStrategy, Input } from '@angular/core';
export interface StatusData {
property: string;
@@ -55,7 +50,7 @@ export class StatusListComponent {
}
];
displayedColumns = this.columns.map(x => x.columnDef);
displayedColumns = this.columns.map((x) => x.columnDef);
@Input()
data: Array<StatusData> = [];

View File

@@ -34,25 +34,8 @@ import { LanguagePickerComponent } from './language-picker/language-picker.compo
import { LogoutComponent } from './logout/logout.component';
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
ExtensionsModule,
GenericErrorModule
],
declarations: [
LocationLinkComponent,
ToggleSharedComponent,
LanguagePickerComponent,
LogoutComponent
],
exports: [
ExtensionsModule,
LocationLinkComponent,
GenericErrorModule,
ToggleSharedComponent,
LanguagePickerComponent,
LogoutComponent
]
imports: [CommonModule, CoreModule.forChild(), ExtensionsModule, GenericErrorModule],
declarations: [LocationLinkComponent, ToggleSharedComponent, LanguagePickerComponent, LogoutComponent],
exports: [ExtensionsModule, LocationLinkComponent, GenericErrorModule, ToggleSharedComponent, LanguagePickerComponent, LogoutComponent]
})
export class AppCommonModule {}

View File

@@ -23,14 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
Input,
ChangeDetectionStrategy,
OnInit,
ViewEncapsulation,
HostListener
} from '@angular/core';
import { Component, Input, ChangeDetectionStrategy, OnInit, ViewEncapsulation, HostListener } from '@angular/core';
import { PathInfo, MinimalNodeEntity } from '@alfresco/js-api';
import { Observable, BehaviorSubject, of } from 'rxjs';
@@ -42,12 +35,7 @@ import { TranslationService } from '@alfresco/adf-core';
@Component({
selector: 'aca-location-link',
template: `
<a
href=""
[title]="nodeLocation$ | async"
(click)="goToLocation()"
class="adf-datatable-cell-value"
>
<a href="" [title]="nodeLocation$ | async" (click)="goToLocation()" class="adf-datatable-cell-value">
{{ displayText | async | translate }}
</a>
`,
@@ -79,11 +67,7 @@ export class LocationLinkComponent implements OnInit {
this.getTooltip(this._path);
}
constructor(
private store: Store<AppStore>,
private contentApi: ContentApiService,
private translationService: TranslationService
) {}
constructor(private store: Store<AppStore>, private contentApi: ContentApiService, private translationService: TranslationService) {}
goToLocation() {
if (this.context) {
@@ -110,7 +94,7 @@ export class LocationLinkComponent implements OnInit {
// todo: review once 5.2.3 is out
private getDisplayText(path: PathInfo): Observable<string> {
const elements = path.elements.map(e => e.name);
const elements = path.elements.map((e) => e.name);
// for admin users
if (elements.length === 1 && elements[0] === 'Company Home') {
@@ -118,11 +102,7 @@ export class LocationLinkComponent implements OnInit {
}
// for non-admin users
if (
elements.length === 3 &&
elements[0] === 'Company Home' &&
elements[1] === 'User Homes'
) {
if (elements.length === 3 && elements[0] === 'Company Home' && elements[1] === 'User Homes') {
return of('APP.BROWSE.PERSONAL.TITLE');
}
@@ -131,12 +111,10 @@ export class LocationLinkComponent implements OnInit {
if (result === 'documentLibrary') {
const fragment = path.elements[path.elements.length - 2];
return new Observable<string>(observer => {
return new Observable<string>((observer) => {
this.contentApi.getNodeInfo(fragment.id).subscribe(
node => {
observer.next(
node.properties['cm:title'] || node.name || fragment.name
);
(node) => {
observer.next(node.properties['cm:title'] || node.name || fragment.name);
observer.complete();
},
() => {
@@ -158,13 +136,9 @@ export class LocationLinkComponent implements OnInit {
let result: string = null;
const elements = path.elements.map(e => Object.assign({}, e));
const personalFiles = this.translationService.instant(
'APP.BROWSE.PERSONAL.TITLE'
);
const fileLibraries = this.translationService.instant(
'APP.BROWSE.LIBRARIES.TITLE'
);
const elements = path.elements.map((e) => Object.assign({}, e));
const personalFiles = this.translationService.instant('APP.BROWSE.PERSONAL.TITLE');
const fileLibraries = this.translationService.instant('APP.BROWSE.LIBRARIES.TITLE');
if (elements[0].name === 'Company Home') {
elements[0].name = personalFiles;
@@ -173,14 +147,13 @@ export class LocationLinkComponent implements OnInit {
if (elements[1].name === 'Sites') {
const fragment = elements[2];
this.contentApi.getNodeInfo(fragment.id).subscribe(
node => {
(node) => {
elements.splice(0, 2);
elements[0].name =
node.properties['cm:title'] || node.name || fragment.name;
elements[0].name = node.properties['cm:title'] || node.name || fragment.name;
elements.splice(1, 1);
elements.unshift({ id: null, name: fileLibraries });
result = elements.map(e => e.name).join('/');
result = elements.map((e) => e.name).join('/');
this.nodeLocation$.next(result);
},
() => {
@@ -188,7 +161,7 @@ export class LocationLinkComponent implements OnInit {
elements.unshift({ id: null, name: fileLibraries });
elements.splice(2, 1);
result = elements.map(e => e.name).join('/');
result = elements.map((e) => e.name).join('/');
this.nodeLocation$.next(result);
}
);
@@ -201,7 +174,7 @@ export class LocationLinkComponent implements OnInit {
}
}
result = elements.map(e => e.name).join('/');
result = elements.map((e) => e.name).join('/');
this.nodeLocation$.next(result);
}
}

View File

@@ -24,11 +24,7 @@
*/
import { TestBed, ComponentFixture } from '@angular/core/testing';
import {
TranslateModule,
TranslateLoader,
TranslateFakeLoader
} from '@ngx-translate/core';
import { TranslateModule, TranslateLoader, TranslateFakeLoader } from '@ngx-translate/core';
import { LogoutComponent } from './logout.component';
import { Store } from '@ngrx/store';
import { SetSelectedNodesAction } from '@alfresco/aca-shared/store';

View File

@@ -45,10 +45,10 @@ describe('ToggleSharedComponent', () => {
component = new ToggleSharedComponent(storeMock);
});
it('should get Store selection entry on initialization', done => {
it('should get Store selection entry on initialization', (done) => {
component.ngOnInit();
component.selection$.subscribe(selection => {
component.selection$.subscribe((selection) => {
expect(selection.first.entry).toEqual(entry);
done();
});

View File

@@ -27,11 +27,7 @@ import { Component, OnInit, Input } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { SelectionState } from '@alfresco/adf-extensions';
import {
AppStore,
ShareNodeAction,
getAppSelection
} from '@alfresco/aca-shared/store';
import { AppStore, ShareNodeAction, getAppSelection } from '@alfresco/aca-shared/store';
@Component({
selector: 'app-toggle-shared',
@@ -50,20 +46,11 @@ export class ToggleSharedComponent implements OnInit {
isShared(selection: SelectionState) {
// workaround for shared files
if (
selection.first &&
selection.first.entry &&
(selection.first.entry as any).sharedByUser
) {
if (selection.first && selection.first.entry && (selection.first.entry as any).sharedByUser) {
return true;
}
return (
selection.first &&
selection.first.entry &&
selection.first.entry.properties &&
!!selection.first.entry.properties['qshare:sharedId']
);
return selection.first && selection.first.entry && selection.first.entry.properties && !!selection.first.entry.properties['qshare:sharedId'];
}
editSharedNode(selection: SelectionState) {

View File

@@ -27,11 +27,7 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AppTestingModule } from '../../testing/app-testing.module';
import { ContextMenuItemComponent } from './context-menu-item.component';
import { ContextMenuModule } from './context-menu.module';
import {
TranslateModule,
TranslateLoader,
TranslateFakeLoader
} from '@ngx-translate/core';
import { TranslateModule, TranslateLoader, TranslateFakeLoader } from '@ngx-translate/core';
import { AppExtensionService } from '@alfresco/aca-shared';
describe('ContextMenuComponent', () => {
@@ -75,9 +71,7 @@ describe('ContextMenuComponent', () => {
fixture.detectChanges();
const buttonElement = fixture.nativeElement.querySelector('button');
expect(buttonElement.querySelector('span').innerText.trim()).toBe(
contextItem.title
);
expect(buttonElement.querySelector('span').innerText.trim()).toBe(contextItem.title);
});
it('should not run action when entry has no click attribute defined', () => {
@@ -86,9 +80,7 @@ describe('ContextMenuComponent', () => {
component.actionRef = contextItem;
fixture.detectChanges();
fixture.nativeElement
.querySelector('#action-button')
.dispatchEvent(new MouseEvent('click'));
fixture.nativeElement.querySelector('#action-button').dispatchEvent(new MouseEvent('click'));
expect(extensionsService.runActionById).not.toHaveBeenCalled();
});
@@ -98,12 +90,8 @@ describe('ContextMenuComponent', () => {
component.actionRef = contextItem;
fixture.detectChanges();
fixture.nativeElement
.querySelector('#action-button')
.dispatchEvent(new MouseEvent('click'));
fixture.nativeElement.querySelector('#action-button').dispatchEvent(new MouseEvent('click'));
expect(extensionsService.runActionById).toHaveBeenCalledWith(
contextItem.actions.click
);
expect(extensionsService.runActionById).toHaveBeenCalledWith(contextItem.actions.click);
});
});

View File

@@ -23,13 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Directive,
Output,
EventEmitter,
OnInit,
OnDestroy
} from '@angular/core';
import { Directive, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';
@@ -47,13 +41,13 @@ export class OutsideEventDirective implements OnInit, OnDestroy {
ngOnInit() {
this.subscriptions = this.subscriptions.concat([
fromEvent(document.body, 'click')
.pipe(filter(event => !this.findAncestor(event.target as Element)))
.pipe(filter((event) => !this.findAncestor(event.target as Element)))
.subscribe(() => this.clickOutside.next())
]);
}
ngOnDestroy() {
this.subscriptions.forEach(subscription => subscription.unsubscribe());
this.subscriptions.forEach((subscription) => subscription.unsubscribe());
this.subscriptions = [];
}

View File

@@ -23,21 +23,12 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
TestBed,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { AppTestingModule } from '../../testing/app-testing.module';
import { ContextMenuComponent } from './context-menu.component';
import { ContextMenuModule } from './context-menu.module';
import { ContextMenuOverlayRef } from './context-menu-overlay';
import {
TranslateModule,
TranslateLoader,
TranslateFakeLoader
} from '@ngx-translate/core';
import { TranslateModule, TranslateLoader, TranslateFakeLoader } from '@ngx-translate/core';
import { of } from 'rxjs';
import { Store } from '@ngrx/store';
@@ -90,9 +81,7 @@ describe('ContextMenuComponent', () => {
contextMenuOverlayRef = TestBed.inject(ContextMenuOverlayRef);
extensionsService = TestBed.inject(AppExtensionService);
spyOn(extensionsService, 'getAllowedContextMenuActions').and.returnValue([
contextItem
]);
spyOn(extensionsService, 'getAllowedContextMenuActions').and.returnValue([contextItem]);
fixture.detectChanges();
});
@@ -106,14 +95,10 @@ describe('ContextMenuComponent', () => {
component.ngAfterViewInit();
tick(500);
const contextMenuElements = document.body
.querySelector('.aca-context-menu')
.querySelectorAll('button');
const contextMenuElements = document.body.querySelector('.aca-context-menu').querySelectorAll('button');
expect(contextMenuElements.length).toBe(1);
expect(contextMenuElements[0].querySelector('span').innerText).toBe(
contextItem.title
);
expect(contextMenuElements[0].querySelector('span').innerText).toBe(contextItem.title);
}));
it('should run action with provided action id', fakeAsync(() => {
@@ -121,8 +106,6 @@ describe('ContextMenuComponent', () => {
component.runAction(contextItem.actions.click);
expect(extensionsService.runActionById).toHaveBeenCalledWith(
contextItem.actions.click
);
expect(extensionsService.runActionById).toHaveBeenCalledWith(contextItem.actions.click);
}));
});

View File

@@ -23,16 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
ViewEncapsulation,
OnInit,
OnDestroy,
HostListener,
ViewChild,
AfterViewInit,
Inject
} from '@angular/core';
import { Component, ViewEncapsulation, OnInit, OnDestroy, HostListener, ViewChild, AfterViewInit, Inject } from '@angular/core';
import { MatMenuTrigger } from '@angular/material/menu';
import { AppStore, getAppSelection } from '@alfresco/aca-shared/store';
import { Store } from '@ngrx/store';
@@ -95,7 +86,7 @@ export class ContextMenuComponent implements OnInit, OnDestroy, AfterViewInit {
this.store
.select(getAppSelection)
.pipe(takeUntil(this.onDestroy$))
.subscribe(selection => {
.subscribe((selection) => {
if (selection.count) {
this.actions = this.extensions.getAllowedContextMenuActions();
}

View File

@@ -49,16 +49,7 @@ import { ContextActionsModule } from '@alfresco/aca-shared';
ExtensionsModule,
ContextActionsModule
],
declarations: [
ContextMenuComponent,
ContextMenuItemComponent,
OutsideEventDirective
],
exports: [
OutsideEventDirective,
ContextMenuComponent,
ContextMenuItemComponent,
ContextActionsModule
]
declarations: [ContextMenuComponent, ContextMenuItemComponent, OutsideEventDirective],
exports: [OutsideEventDirective, ContextMenuComponent, ContextMenuItemComponent, ContextActionsModule]
})
export class ContextMenuModule {}

View File

@@ -50,16 +50,8 @@ describe('ContextMenuService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreModule.forRoot(),
ContextMenuModule
],
providers: [
Overlay,
{ provide: Store, useValue: { select: () => of() } },
UserPreferencesService
]
imports: [TranslateModule.forRoot(), CoreModule.forRoot(), ContextMenuModule],
providers: [Overlay, { provide: Store, useValue: { select: () => of() } }, UserPreferencesService]
});
injector = TestBed.inject(Injector);
@@ -68,11 +60,7 @@ describe('ContextMenuService', () => {
});
it('should create a custom overlay', () => {
contextMenuService = new ContextMenuService(
injector,
overlay,
userPreferencesService
);
contextMenuService = new ContextMenuService(injector, overlay, userPreferencesService);
contextMenuService.open(overlayConfig);
@@ -80,11 +68,7 @@ describe('ContextMenuService', () => {
});
it('should render component', () => {
contextMenuService = new ContextMenuService(
injector,
overlay,
userPreferencesService
);
contextMenuService = new ContextMenuService(injector, overlay, userPreferencesService);
contextMenuService.open(overlayConfig);
@@ -92,11 +76,7 @@ describe('ContextMenuService', () => {
});
it('should have default LTR direction value', () => {
contextMenuService = new ContextMenuService(
injector,
overlay,
userPreferencesService
);
contextMenuService = new ContextMenuService(injector, overlay, userPreferencesService);
contextMenuService.open(overlayConfig);
@@ -106,11 +86,7 @@ describe('ContextMenuService', () => {
it('should change direction on textOrientation event', () => {
spyOn(userPreferencesService, 'select').and.returnValue(of('rtl'));
contextMenuService = new ContextMenuService(
injector,
overlay,
userPreferencesService
);
contextMenuService = new ContextMenuService(injector, overlay, userPreferencesService);
contextMenuService.open(overlayConfig);

View File

@@ -39,16 +39,10 @@ import { CONTEXT_MENU_DIRECTION } from './direction.token';
export class ContextMenuService {
private direction: Directionality;
constructor(
private injector: Injector,
private overlay: Overlay,
private userPreferenceService: UserPreferencesService
) {
this.userPreferenceService
.select('textOrientation')
.subscribe(textOrientation => {
this.direction = textOrientation;
});
constructor(private injector: Injector, private overlay: Overlay, private userPreferenceService: UserPreferencesService) {
this.userPreferenceService.select('textOrientation').subscribe((textOrientation) => {
this.direction = textOrientation;
});
}
open(config: ContextmenuOverlayConfig): ContextMenuOverlayRef {
@@ -65,27 +59,16 @@ export class ContextMenuService {
return this.overlay.create(overlayConfig);
}
private attachDialogContainer(
overlay: OverlayRef,
contextmenuOverlayRef: ContextMenuOverlayRef
): ContextMenuComponent {
private attachDialogContainer(overlay: OverlayRef, contextmenuOverlayRef: ContextMenuOverlayRef): ContextMenuComponent {
const injector = this.createInjector(contextmenuOverlayRef);
const containerPortal = new ComponentPortal(
ContextMenuComponent,
null,
injector
);
const containerRef: ComponentRef<ContextMenuComponent> = overlay.attach(
containerPortal
);
const containerPortal = new ComponentPortal(ContextMenuComponent, null, injector);
const containerRef: ComponentRef<ContextMenuComponent> = overlay.attach(containerPortal);
return containerRef.instance;
}
private createInjector(
contextmenuOverlayRef: ContextMenuOverlayRef
): PortalInjector {
private createInjector(contextmenuOverlayRef: ContextMenuOverlayRef): PortalInjector {
const injectionTokens = new WeakMap();
injectionTokens.set(ContextMenuOverlayRef, contextmenuOverlayRef);

View File

@@ -25,10 +25,7 @@
import { InjectionToken } from '@angular/core';
export const CONTEXT_MENU_DIRECTION = new InjectionToken(
'CONTEXT_MENU_DIRECTION',
{
providedIn: 'root',
factory: () => 'ltr'
}
);
export const CONTEXT_MENU_DIRECTION = new InjectionToken('CONTEXT_MENU_DIRECTION', {
providedIn: 'root',
factory: () => 'ltr'
});

View File

@@ -23,13 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
Input,
OnInit,
OnDestroy,
ViewEncapsulation
} from '@angular/core';
import { Component, Input, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import { ContentActionRef } from '@alfresco/adf-extensions';
import { AppStore, getCurrentFolder } from '@alfresco/aca-shared/store';
import { Store } from '@ngrx/store';
@@ -54,10 +48,7 @@ export class CreateMenuComponent implements OnInit, OnDestroy {
@Input()
expanded: boolean;
constructor(
private store: Store<AppStore>,
private extensions: AppExtensionService
) {}
constructor(private store: Store<AppStore>, private extensions: AppExtensionService) {}
ngOnInit() {
this.store

View File

@@ -28,11 +28,7 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AppTestingModule } from '../../testing/app-testing.module';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Store } from '@ngrx/store';
import {
AppState,
SetUserProfileAction,
SetSettingsParameterAction
} from '@alfresco/aca-shared/store';
import { AppState, SetUserProfileAction, SetSettingsParameterAction } from '@alfresco/aca-shared/store';
import { AppExtensionService } from '@alfresco/aca-shared';
describe('CurrentUserComponent', () => {
@@ -66,7 +62,7 @@ describe('CurrentUserComponent', () => {
component = fixture.componentInstance;
});
it('should get profile data', done => {
it('should get profile data', (done) => {
const expectedProfile = {
firstName: 'Test',
lastName: 'User',
@@ -78,9 +74,7 @@ describe('CurrentUserComponent', () => {
fixture.detectChanges();
store.dispatch(
new SetUserProfileAction({ person: person.entry, groups: [] })
);
store.dispatch(new SetUserProfileAction({ person: person.entry, groups: [] }));
component.profile$.subscribe((profile: any) => {
expect(profile).toEqual(jasmine.objectContaining(expectedProfile));
@@ -88,12 +82,10 @@ describe('CurrentUserComponent', () => {
});
});
it('should set language picker state', done => {
it('should set language picker state', (done) => {
fixture.detectChanges();
store.dispatch(
new SetSettingsParameterAction({ name: 'languagePicker', value: true })
);
store.dispatch(new SetSettingsParameterAction({ name: 'languagePicker', value: true }));
component.languagePicker$.subscribe((languagePicker: boolean) => {
expect(languagePicker).toBe(true);

View File

@@ -27,11 +27,7 @@ import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { ProfileState, ContentActionRef } from '@alfresco/adf-extensions';
import {
AppStore,
getUserProfile,
getLanguagePickerState
} from '@alfresco/aca-shared/store';
import { AppStore, getUserProfile, getLanguagePickerState } from '@alfresco/aca-shared/store';
import { AppExtensionService } from '@alfresco/aca-shared';
@Component({
@@ -45,10 +41,7 @@ export class CurrentUserComponent implements OnInit {
languagePicker$: Observable<boolean>;
actions: Array<ContentActionRef> = [];
constructor(
private store: Store<AppStore>,
private extensions: AppExtensionService
) {}
constructor(private store: Store<AppStore>, private extensions: AppExtensionService) {}
ngOnInit() {
this.profile$ = this.store.select(getUserProfile);

View File

@@ -32,12 +32,7 @@ import { UserMenuItemComponent } from './user-menu-item.component';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
RouterModule,
ExtensionsModule
],
imports: [CommonModule, CoreModule.forChild(), RouterModule, ExtensionsModule],
declarations: [CurrentUserComponent, UserMenuItemComponent],
exports: [CurrentUserComponent, UserMenuItemComponent]
})

View File

@@ -26,11 +26,7 @@
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AppTestingModule } from '../../testing/app-testing.module';
import { UserMenuItemComponent } from './user-menu-item.component';
import {
TranslateModule,
TranslateLoader,
TranslateFakeLoader
} from '@ngx-translate/core';
import { TranslateModule, TranslateLoader, TranslateFakeLoader } from '@ngx-translate/core';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ContentActionRef } from '@alfresco/adf-extensions';
import { AppExtensionService } from '@alfresco/aca-shared';
@@ -99,9 +95,7 @@ describe('UserMenuItemComponent', () => {
} as ContentActionRef;
fixture.detectChanges();
const componentElement = fixture.nativeElement.querySelector(
'#custom-component'
);
const componentElement = fixture.nativeElement.querySelector('#custom-component');
expect(componentElement).not.toBe(null);
});
@@ -119,8 +113,6 @@ describe('UserMenuItemComponent', () => {
const buttonElement = fixture.nativeElement.querySelector('#action-button');
buttonElement.dispatchEvent(new MouseEvent('click'));
expect(appExtensionService.runActionById).toHaveBeenCalledWith(
'TEST_EVENT'
);
expect(appExtensionService.runActionById).toHaveBeenCalledWith('TEST_EVENT');
});
});

View File

@@ -32,13 +32,7 @@ import { MaterialModule } from '../../material.module';
import { CoreModule } from '@alfresco/adf-core';
@NgModule({
imports: [
BrowserModule,
CoreModule.forChild(),
ContentModule.forChild(),
MaterialModule,
LockedByModule
],
imports: [BrowserModule, CoreModule.forChild(), ContentModule.forChild(), MaterialModule, LockedByModule],
declarations: [CustomNameColumnComponent],
exports: [CustomNameColumnComponent]
})

View File

@@ -64,9 +64,7 @@ describe('CustomNameColumnComponent', () => {
fixture.detectChanges();
expect(
fixture.debugElement.nativeElement.querySelector('aca-locked-by')
).toBe(null);
expect(fixture.debugElement.nativeElement.querySelector('aca-locked-by')).toBe(null);
});
it('should not render lock element if node is not a file', () => {
@@ -83,9 +81,7 @@ describe('CustomNameColumnComponent', () => {
fixture.detectChanges();
expect(
fixture.debugElement.nativeElement.querySelector('aca-locked-by')
).toBe(null);
expect(fixture.debugElement.nativeElement.querySelector('aca-locked-by')).toBe(null);
});
it('should render lock element if file is locked', () => {
@@ -103,9 +99,7 @@ describe('CustomNameColumnComponent', () => {
fixture.detectChanges();
expect(
fixture.debugElement.nativeElement.querySelector('aca-locked-by')
).not.toBe(null);
expect(fixture.debugElement.nativeElement.querySelector('aca-locked-by')).not.toBe(null);
});
it('should call parent component onClick method', () => {

View File

@@ -25,14 +25,7 @@
import { NameColumnComponent } from '@alfresco/adf-content-services';
import { AlfrescoApiService } from '@alfresco/adf-core';
import {
ChangeDetectorRef,
Component,
ElementRef,
OnDestroy,
OnInit,
ViewEncapsulation
} from '@angular/core';
import { ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { Actions, ofType } from '@ngrx/effects';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
@@ -48,43 +41,35 @@ import { isLocked } from '@alfresco/aca-shared';
class: ' adf-datatable-content-cell adf-datatable-link adf-name-column'
}
})
export class CustomNameColumnComponent extends NameColumnComponent
implements OnInit, OnDestroy {
export class CustomNameColumnComponent extends NameColumnComponent implements OnInit, OnDestroy {
private onDestroy$$ = new Subject<boolean>();
constructor(
element: ElementRef,
private cd: ChangeDetectorRef,
private actions$: Actions,
private apiService: AlfrescoApiService
) {
constructor(element: ElementRef, private cd: ChangeDetectorRef, private actions$: Actions, private apiService: AlfrescoApiService) {
super(element, apiService);
}
ngOnInit() {
this.updateValue();
this.apiService.nodeUpdated
.pipe(takeUntil(this.onDestroy$$))
.subscribe((node: any) => {
const row = this.context.row;
if (row) {
const { entry } = row.node;
const currentId = entry.nodeId || entry.id;
const updatedId = node.nodeId || node.id;
this.apiService.nodeUpdated.pipe(takeUntil(this.onDestroy$$)).subscribe((node: any) => {
const row = this.context.row;
if (row) {
const { entry } = row.node;
const currentId = entry.nodeId || entry.id;
const updatedId = node.nodeId || node.id;
if (currentId === updatedId) {
entry.name = node.name;
row.node = { entry };
this.updateValue();
}
if (currentId === updatedId) {
entry.name = node.name;
row.node = { entry };
this.updateValue();
}
});
}
});
this.actions$
.pipe(
ofType<any>(NodeActionTypes.EditOffline),
filter(val => {
filter((val) => {
return this.node.entry.id === val.payload.entry.id;
}),
takeUntil(this.onDestroy$$)

View File

@@ -26,13 +26,7 @@
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router } from '@angular/router';
import {
AlfrescoApiService,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe,
UserPreferencesService
} from '@alfresco/adf-core';
import { AlfrescoApiService, NodeFavoriteDirective, DataTableComponent, AppConfigPipe, UserPreferencesService } from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { FavoriteLibrariesComponent } from './favorite-libraries.component';
import { AppTestingModule } from '../../testing/app-testing.module';
@@ -65,17 +59,8 @@ describe('FavoriteLibrariesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppTestingModule,
EffectsModule.forRoot([RouterEffects, LibraryEffects])
],
declarations: [
DataTableComponent,
NodeFavoriteDirective,
DocumentListComponent,
FavoriteLibrariesComponent,
AppConfigPipe
],
imports: [AppTestingModule, EffectsModule.forRoot([RouterEffects, LibraryEffects])],
declarations: [DataTableComponent, NodeFavoriteDirective, DocumentListComponent, FavoriteLibrariesComponent, AppConfigPipe],
providers: [ContentManagementService, UserPreferencesService],
schemas: [NO_ERRORS_SCHEMA]
});
@@ -90,16 +75,12 @@ describe('FavoriteLibrariesComponent', () => {
alfrescoApi.reset();
router = TestBed.inject(Router);
spyOn(contentApiService, 'getNode').and.returnValue(
of({ entry: { id: 'libraryId' } } as NodeEntry)
);
spyOn(contentApiService, 'getNode').and.returnValue(of({ entry: { id: 'libraryId' } } as NodeEntry));
});
describe('on initialization', () => {
it('should set data', () => {
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(
of(page)
);
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(of(page));
fixture.detectChanges();
expect(component.list).toBe(page);
@@ -108,24 +89,17 @@ describe('FavoriteLibrariesComponent', () => {
it('should get data with user preference pagination size', () => {
userPreference.paginationSize = 1;
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(
of(page)
);
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(of(page));
fixture.detectChanges();
expect(contentApiService.getFavoriteLibraries).toHaveBeenCalledWith(
'-me-',
{
maxItems: userPreference.paginationSize
}
);
expect(contentApiService.getFavoriteLibraries).toHaveBeenCalledWith('-me-', {
maxItems: userPreference.paginationSize
});
});
it('should set data on error', () => {
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(
throwError('error')
);
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(throwError('error'));
fixture.detectChanges();
expect(component.list).toBe(null);
@@ -146,18 +120,13 @@ describe('FavoriteLibrariesComponent', () => {
spyOn(router, 'navigate').and.stub();
component.navigateTo({ entry: { guid: 'guid' } } as any);
expect(router.navigate).toHaveBeenCalledWith([
'favorite/libraries',
'libraryId'
]);
expect(router.navigate).toHaveBeenCalledWith(['favorite/libraries', 'libraryId']);
});
});
describe('Reload on actions', () => {
beforeEach(() => {
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(
of(page)
);
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(of(page));
fixture.detectChanges();
});
@@ -201,35 +170,23 @@ describe('FavoriteLibrariesComponent', () => {
});
it('should get list with pagination data onChange event', () => {
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(
of(page)
);
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(of(page));
component.onChange(pagination);
expect(contentApiService.getFavoriteLibraries).toHaveBeenCalledWith(
'-me-',
pagination
);
expect(contentApiService.getFavoriteLibraries).toHaveBeenCalledWith('-me-', pagination);
});
it('should get list with pagination data onChangePageSize event', () => {
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(
of(page)
);
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(of(page));
component.onChangePageSize(pagination);
expect(contentApiService.getFavoriteLibraries).toHaveBeenCalledWith(
'-me-',
pagination
);
expect(contentApiService.getFavoriteLibraries).toHaveBeenCalledWith('-me-', pagination);
});
it('should set preference page size onChangePageSize event', () => {
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(
of(page)
);
spyOn(contentApiService, 'getFavoriteLibraries').and.returnValue(of(page));
component.onChangePageSize(pagination);

View File

@@ -35,8 +35,7 @@ import { UserPreferencesService } from '@alfresco/adf-core';
@Component({
templateUrl: './favorite-libraries.component.html'
})
export class FavoriteLibrariesComponent extends PageComponent
implements OnInit {
export class FavoriteLibrariesComponent extends PageComponent implements OnInit {
pagination: Pagination = new Pagination({
skipCount: 0,
maxItems: 25,
@@ -71,20 +70,16 @@ export class FavoriteLibrariesComponent extends PageComponent
this.content.libraryLeft.subscribe(() => this.reloadList()),
this.content.favoriteLibraryToggle.subscribe(() => this.reloadList()),
this.breakpointObserver
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
this.breakpointObserver.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape]).subscribe((result) => {
this.isSmallScreen = result.matches;
})
]);
this.columns = this.extensions.documentListPresets.favoriteLibraries || [];
}
navigateTo(node: SiteEntry) {
if (node && node.entry && node.entry.guid) {
this.store.dispatch(
new NavigateLibraryAction(node.entry.guid, 'favorite/libraries')
);
this.store.dispatch(new NavigateLibraryAction(node.entry.guid, 'favorite/libraries'));
}
}

View File

@@ -25,19 +25,8 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router } from '@angular/router';
import {
TestBed,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import {
AlfrescoApiService,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe,
UploadService
} from '@alfresco/adf-core';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { AlfrescoApiService, NodeFavoriteDirective, DataTableComponent, AppConfigPipe, UploadService } from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { of } from 'rxjs';
import { FavoritesComponent } from './favorites.component';
@@ -61,10 +50,7 @@ describe('FavoritesComponent', () => {
beforeEach(() => {
page = {
list: {
entries: [
{ entry: { id: 1, target: { file: {} } } },
{ entry: { id: 2, target: { folder: {} } } }
],
entries: [{ entry: { id: 1, target: { file: {} } } }, { entry: { id: 2, target: { folder: {} } } }],
pagination: { data: 'data' }
}
};
@@ -82,13 +68,7 @@ describe('FavoritesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
DataTableComponent,
NodeFavoriteDirective,
DocumentListComponent,
FavoritesComponent,
AppConfigPipe
],
declarations: [DataTableComponent, NodeFavoriteDirective, DocumentListComponent, FavoritesComponent, AppConfigPipe],
providers: [
{
provide: Router,
@@ -103,9 +83,7 @@ describe('FavoritesComponent', () => {
alfrescoApi = TestBed.inject(AlfrescoApiService);
alfrescoApi.reset();
spyOn(alfrescoApi.favoritesApi, 'getFavorites').and.returnValue(
Promise.resolve(page)
);
spyOn(alfrescoApi.favoritesApi, 'getFavorites').and.returnValue(Promise.resolve(page));
contentApi = TestBed.inject(ContentApiService);
uploadService = TestBed.inject(UploadService);
@@ -124,10 +102,7 @@ describe('FavoritesComponent', () => {
component.navigate(node);
expect(router.navigate).toHaveBeenCalledWith([
'/libraries',
'folder-node'
]);
expect(router.navigate).toHaveBeenCalledWith(['/libraries', 'folder-node']);
});
it('navigates to `/personal-files` if node path has no `Sites`', () => {
@@ -135,10 +110,7 @@ describe('FavoritesComponent', () => {
component.navigate(node);
expect(router.navigate).toHaveBeenCalledWith([
'/personal-files',
'folder-node'
]);
expect(router.navigate).toHaveBeenCalledWith(['/personal-files', 'folder-node']);
});
it('does not navigate when node is not folder', () => {

View File

@@ -26,12 +26,7 @@
import { AppExtensionService, ContentApiService } from '@alfresco/aca-shared';
import { AppStore } from '@alfresco/aca-shared/store';
import { UploadService } from '@alfresco/adf-core';
import {
MinimalNodeEntity,
MinimalNodeEntryEntity,
PathElementEntity,
PathInfo
} from '@alfresco/js-api';
import { MinimalNodeEntity, MinimalNodeEntryEntity, PathElementEntity, PathInfo } from '@alfresco/js-api';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@@ -64,18 +59,12 @@ export class FavoritesComponent extends PageComponent implements OnInit {
super.ngOnInit();
this.subscriptions = this.subscriptions.concat([
this.uploadService.fileUploadComplete
.pipe(debounceTime(300))
.subscribe(_ => this.reload()),
this.uploadService.fileUploadDeleted
.pipe(debounceTime(300))
.subscribe(_ => this.reload()),
this.uploadService.fileUploadComplete.pipe(debounceTime(300)).subscribe((_) => this.reload()),
this.uploadService.fileUploadDeleted.pipe(debounceTime(300)).subscribe((_) => this.reload()),
this.breakpointObserver
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
this.breakpointObserver.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape]).subscribe((result) => {
this.isSmallScreen = result.matches;
})
]);
this.columns = this.extensions.documentListPresets.favorites;
@@ -86,17 +75,13 @@ export class FavoritesComponent extends PageComponent implements OnInit {
// TODO: rework as it will fail on non-English setups
const isSitePath = (path: PathInfo): boolean => {
return (
path &&
path.elements &&
path.elements.some(({ name }: PathElementEntity) => name === 'Sites')
);
return path && path.elements && path.elements.some(({ name }: PathElementEntity) => name === 'Sites');
};
if (isFolder) {
this.contentApi
.getNode(id)
.pipe(map(node => node.entry))
.pipe(map((node) => node.entry))
.subscribe(({ path }: MinimalNodeEntryEntity) => {
const routeUrl = isSitePath(path) ? '/libraries' : '/personal-files';
this.router.navigate([routeUrl, id]);

View File

@@ -23,12 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
TestBed,
fakeAsync,
tick,
ComponentFixture
} from '@angular/core/testing';
import { TestBed, fakeAsync, tick, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {
@@ -61,13 +56,7 @@ describe('FilesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
FilesComponent,
DataTableComponent,
NodeFavoriteDirective,
DocumentListComponent,
AppConfigPipe
],
declarations: [FilesComponent, DataTableComponent, NodeFavoriteDirective, DocumentListComponent, AppConfigPipe],
providers: [
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock },
{
@@ -138,16 +127,11 @@ describe('FilesComponent', () => {
it('should navigate to parent if node is not a folder', () => {
const nodeEntry = { isFolder: false, parentId: 'parent-id' };
spyOn(contentApi, 'getNode').and.returnValue(
of({ entry: nodeEntry } as any)
);
spyOn(contentApi, 'getNode').and.returnValue(of({ entry: nodeEntry } as any));
fixture.detectChanges();
expect(router.navigate['calls'].argsFor(0)[0]).toEqual([
'/personal-files',
'parent-id'
]);
expect(router.navigate['calls'].argsFor(0)[0]).toEqual(['/personal-files', 'parent-id']);
});
});
@@ -160,10 +144,7 @@ describe('FilesComponent', () => {
});
it('should call refresh onContentCopied event if parent is the same', () => {
const nodes: any[] = [
{ entry: { parentId: '1' } },
{ entry: { parentId: '2' } }
];
const nodes: any[] = [{ entry: { parentId: '1' } }, { entry: { parentId: '2' } }];
component.node = { id: '1' } as any;
@@ -173,10 +154,7 @@ describe('FilesComponent', () => {
});
it('should not call refresh onContentCopied event when parent mismatch', () => {
const nodes: any[] = [
{ entry: { parentId: '1' } },
{ entry: { parentId: '2' } }
];
const nodes: any[] = [{ entry: { parentId: '1' } }, { entry: { parentId: '2' } }];
component.node = { id: '3' } as any;
@@ -256,10 +234,7 @@ describe('FilesComponent', () => {
router.url = '/personal-files';
component.navigate(node.id);
expect(router.navigate).toHaveBeenCalledWith([
'/personal-files',
node.id
]);
expect(router.navigate).toHaveBeenCalledWith(['/personal-files', node.id]);
});
it('should navigates to home when id not provided', () => {

View File

@@ -27,29 +27,15 @@ import { FileUploadEvent, UploadService } from '@alfresco/adf-core';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import {
MinimalNodeEntity,
MinimalNodeEntryEntity,
PathElement,
PathElementEntity
} from '@alfresco/js-api';
import { MinimalNodeEntity, MinimalNodeEntryEntity, PathElement, PathElementEntity } from '@alfresco/js-api';
import { ContentManagementService } from '../../services/content-management.service';
import { NodeActionsService } from '../../services/node-actions.service';
import { PageComponent } from '../page.component';
import { AppExtensionService, ContentApiService } from '@alfresco/aca-shared';
import {
SetCurrentFolderAction,
isAdmin,
AppStore,
UploadFileVersionAction
} from '@alfresco/aca-shared/store';
import { SetCurrentFolderAction, isAdmin, AppStore, UploadFileVersionAction } from '@alfresco/aca-shared/store';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { debounceTime, takeUntil } from 'rxjs/operators';
import {
ShareDataRow,
SEARCH_QUERY_SERVICE_TOKEN,
SearchHeaderQueryBuilderService
} from '@alfresco/adf-content-services';
import { ShareDataRow, SEARCH_QUERY_SERVICE_TOKEN, SearchHeaderQueryBuilderService } from '@alfresco/adf-content-services';
@Component({
templateUrl: './files.component.html',
@@ -96,7 +82,7 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
const nodeId = folderId || data.defaultNodeId;
this.contentApi.getNode(nodeId).subscribe(
node => {
(node) => {
this.isValidPath = true;
if (node.entry && node.entry.isFolder) {
@@ -112,27 +98,19 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
});
this.subscriptions = this.subscriptions.concat([
nodeActionsService.contentCopied.subscribe(nodes =>
this.onContentCopied(nodes)
),
uploadService.fileUploadComplete
.pipe(debounceTime(300))
.subscribe(file => this.onFileUploadedEvent(file)),
uploadService.fileUploadDeleted
.pipe(debounceTime(300))
.subscribe(file => this.onFileUploadedEvent(file)),
nodeActionsService.contentCopied.subscribe((nodes) => this.onContentCopied(nodes)),
uploadService.fileUploadComplete.pipe(debounceTime(300)).subscribe((file) => this.onFileUploadedEvent(file)),
uploadService.fileUploadDeleted.pipe(debounceTime(300)).subscribe((file) => this.onFileUploadedEvent(file)),
this.breakpointObserver
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
this.breakpointObserver.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape]).subscribe((result) => {
this.isSmallScreen = result.matches;
})
]);
this.store
.select(isAdmin)
.pipe(takeUntil(this.onDestroy$))
.subscribe(value => {
.subscribe((value) => {
this.isAdmin = value;
});
@@ -177,10 +155,7 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
onBreadcrumbNavigate(route: PathElementEntity) {
// todo: review this approach once 5.2.3 is out
if (this.nodePath && this.nodePath.length > 2) {
if (
this.nodePath[1].name === 'Sites' &&
this.nodePath[2].id === route.id
) {
if (this.nodePath[1].name === 'Sites' && this.nodePath[2].id === route.id) {
return this.navigate(this.nodePath[3].id);
}
}
@@ -204,14 +179,11 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
if (event && event.file.options.parentId) {
if (this.nodePath) {
const correspondingNodePath = this.nodePath.find(
pathItem => pathItem.id === event.file.options.parentId
);
const correspondingNodePath = this.nodePath.find((pathItem) => pathItem.id === event.file.options.parentId);
// check if the current folder has the 'trigger-upload-folder' as one of its parents
if (correspondingNodePath) {
const correspondingIndex =
this.nodePath.length - this.nodePath.indexOf(correspondingNodePath);
const correspondingIndex = this.nodePath.length - this.nodePath.indexOf(correspondingNodePath);
this.displayFolderParent(event.file.options.path, correspondingIndex);
}
}
@@ -220,12 +192,9 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
displayFolderParent(filePath = '', index: number) {
const parentName = filePath.split('/')[index];
const currentFoldersDisplayed =
(this.documentList.data.getRows() as ShareDataRow[]) || [];
const currentFoldersDisplayed = (this.documentList.data.getRows() as ShareDataRow[]) || [];
const alreadyDisplayedParentFolder = currentFoldersDisplayed.find(
row => row.node.entry.isFolder && row.node.entry.name === parentName
);
const alreadyDisplayedParentFolder = currentFoldersDisplayed.find((row) => row.node.entry.isFolder && row.node.entry.name === parentName);
if (alreadyDisplayedParentFolder) {
return;
@@ -234,10 +203,8 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
}
onContentCopied(nodes: MinimalNodeEntity[]) {
const newNode = nodes.find(node => {
return (
node && node.entry && node.entry.parentId === this.getParentNodeId()
);
const newNode = nodes.find((node) => {
return node && node.entry && node.entry.parentId === this.getParentNodeId();
});
if (newNode) {
this.reload(this.selectedNode);
@@ -251,7 +218,7 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
if (node && node.path && node.path.elements) {
const elements = node.path.elements;
this.nodePath = elements.map(pathElement => {
this.nodePath = elements.map((pathElement) => {
return Object.assign({}, pathElement);
});
@@ -280,21 +247,17 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
if (this.isSiteContainer(node)) {
// rename 'documentLibrary' entry to the target site display name
// clicking on the breadcrumb entry loads the site content
const parentNode = await this.contentApi
.getNodeInfo(node.parentId)
.toPromise();
const parentNode = await this.contentApi.getNodeInfo(node.parentId).toPromise();
node.name = parentNode.properties['cm:title'] || parentNode.name;
// remove the site entry
elements.splice(1, 1);
} else {
// remove 'documentLibrary' in the middle of the path
const docLib = elements.findIndex(el => el.name === 'documentLibrary');
const docLib = elements.findIndex((el) => el.name === 'documentLibrary');
if (docLib > -1) {
const siteFragment = elements[docLib - 1];
const siteNode = await this.contentApi
.getNodeInfo(siteFragment.id)
.toPromise();
const siteNode = await this.contentApi.getNodeInfo(siteFragment.id).toPromise();
// apply Site Name to the parent fragment
siteFragment.name = siteNode.properties['cm:title'] || siteNode.name;
@@ -311,12 +274,7 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
}
isRootNode(nodeId: string): boolean {
if (
this.node &&
this.node.path &&
this.node.path.elements &&
this.node.path.elements.length > 0
) {
if (this.node && this.node.path && this.node.path.elements && this.node.path.elements.length > 0) {
return this.node.path.elements[0].id === nodeId;
}
return false;

View File

@@ -52,7 +52,7 @@ describe('AppHeaderComponent', () => {
} as AppState;
beforeEach(() => {
store.select.and.callFake(memoizeFn => {
store.select.and.callFake((memoizeFn) => {
return of(memoizeFn({ app }));
});
@@ -60,9 +60,9 @@ describe('AppHeaderComponent', () => {
});
it('should set header color, name and logo', async(() => {
component.appName$.subscribe(val => expect(val).toBe(app.appName));
component.logo$.subscribe(val => expect(val).toBe(app.logoPath));
component.headerColor$.subscribe(val => expect(val).toBe(app.headerColor));
component.appName$.subscribe((val) => expect(val).toBe(app.appName));
component.logo$.subscribe((val) => expect(val).toBe(app.logoPath));
component.headerColor$.subscribe((val) => expect(val).toBe(app.headerColor));
}));
it('should get header actions', () => {

View File

@@ -23,24 +23,11 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
ViewEncapsulation,
Output,
EventEmitter,
OnInit,
Input
} from '@angular/core';
import { Component, ViewEncapsulation, Output, EventEmitter, OnInit, Input } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { ContentActionRef } from '@alfresco/adf-extensions';
import {
AppStore,
getHeaderColor,
getAppName,
getLogoPath,
getHeaderImagePath
} from '@alfresco/aca-shared/store';
import { AppStore, getHeaderColor, getAppName, getLogoPath, getHeaderImagePath } from '@alfresco/aca-shared/store';
import { AppExtensionService } from '@alfresco/aca-shared';
@Component({
@@ -62,19 +49,13 @@ export class AppHeaderComponent implements OnInit {
actions: Array<ContentActionRef> = [];
constructor(
store: Store<AppStore>,
private appExtensions: AppExtensionService
) {
constructor(store: Store<AppStore>, private appExtensions: AppExtensionService) {
this.headerColor$ = store.select(getHeaderColor);
this.appName$ = store.select(getAppName);
this.logo$ = store.select(getLogoPath);
store.select(getHeaderImagePath).subscribe(path => {
document.body.style.setProperty(
'--header-background-image',
`url('${path}')`
);
store.select(getHeaderImagePath).subscribe((path) => {
document.body.style.setProperty('--header-background-image', `url('${path}')`);
});
}

View File

@@ -32,13 +32,7 @@ import { AppSearchInputModule } from '../search/search-input.module';
import { AppToolbarModule } from '../toolbar/toolbar.module';
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
AppCurrentUserModule,
AppSearchInputModule,
AppToolbarModule
],
imports: [CommonModule, CoreModule.forChild(), AppCurrentUserModule, AppSearchInputModule, AppToolbarModule],
declarations: [AppHeaderComponent],
exports: [AppHeaderComponent]
})

View File

@@ -41,9 +41,7 @@ describe('CommentsTabComponent', () => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [CommentsTabComponent],
providers: [
{ provide: NodePermissionService, useValue: permissionsMock }
],
providers: [{ provide: NodePermissionService, useValue: permissionsMock }],
schemas: [NO_ERRORS_SCHEMA]
});

View File

@@ -29,12 +29,7 @@ import { NodePermissionService, isLocked } from '@alfresco/aca-shared';
@Component({
selector: 'app-comments-tab',
template: `
<adf-comments
[readOnly]="!canUpdateNode"
[nodeId]="node?.id"
></adf-comments>
`
template: `<adf-comments [readOnly]="!canUpdateNode" [nodeId]="node?.id"></adf-comments>`
})
export class CommentsTabComponent {
@Input()
@@ -47,10 +42,7 @@ export class CommentsTabComponent {
return false;
}
if (
this.node.isFolder ||
(this.node.isFile && !isLocked({ entry: this.node }))
) {
if (this.node.isFolder || (this.node.isFile && !isLocked({ entry: this.node }))) {
return this.permission.check(this.node, ['update']);
}
return false;

View File

@@ -23,10 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
ContentMetadataModule,
VersionManagerModule
} from '@alfresco/adf-content-services';
import { ContentMetadataModule, VersionManagerModule } from '@alfresco/adf-content-services';
import { CoreModule } from '@alfresco/adf-core';
import { ExtensionsModule } from '@alfresco/adf-extensions';
import { CommonModule } from '@angular/common';
@@ -42,13 +39,7 @@ import { A11yModule } from '@angular/cdk/a11y';
import { SharedInfoDrawerModule } from '@alfresco/aca-shared';
export function components() {
return [
MetadataTabComponent,
CommentsTabComponent,
VersionsTabComponent,
LibraryMetadataTabComponent,
LibraryMetadataFormComponent
];
return [MetadataTabComponent, CommentsTabComponent, VersionsTabComponent, LibraryMetadataTabComponent, LibraryMetadataFormComponent];
}
@NgModule({

View File

@@ -23,12 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { LibraryMetadataFormComponent } from './library-metadata-form.component';
import {
TestBed,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { Store } from '@ngrx/store';
import { UpdateLibraryAction } from '@alfresco/aca-shared/store';
import { AppTestingModule } from '../../../testing/app-testing.module';
@@ -135,9 +130,7 @@ describe('LibraryMetadataFormComponent', () => {
component.update();
expect(storeMock.dispatch).toHaveBeenCalledWith(
new UpdateLibraryAction(siteEntryModel)
);
expect(storeMock.dispatch).toHaveBeenCalledWith(new UpdateLibraryAction(siteEntryModel));
});
it('should not update library node if it has no permission', () => {
@@ -158,9 +151,7 @@ describe('LibraryMetadataFormComponent', () => {
component.update();
expect(storeMock.dispatch).not.toHaveBeenCalledWith(
new UpdateLibraryAction(siteEntryModel)
);
expect(storeMock.dispatch).not.toHaveBeenCalledWith(new UpdateLibraryAction(siteEntryModel));
});
it('should not update library node if form is invalid', () => {
@@ -183,9 +174,7 @@ describe('LibraryMetadataFormComponent', () => {
component.update();
expect(storeMock.dispatch).not.toHaveBeenCalledWith(
new UpdateLibraryAction(siteEntryModel)
);
expect(storeMock.dispatch).not.toHaveBeenCalledWith(new UpdateLibraryAction(siteEntryModel));
});
it('should toggle edit mode', () => {
@@ -225,10 +214,7 @@ describe('LibraryMetadataFormComponent', () => {
it('should warn if library name input is used by another library', fakeAsync(() => {
const title = 'some-title';
spyOn(
alfrescoApiService.getInstance().core.queriesApi,
'findSites'
).and.returnValue(
spyOn(alfrescoApiService.getInstance().core.queriesApi, 'findSites').and.returnValue(
Promise.resolve({
list: { entries: [{ entry: { title } }] }
} as SitePaging)
@@ -256,10 +242,7 @@ describe('LibraryMetadataFormComponent', () => {
}));
it('should not warn if library name input is the same with library node data', fakeAsync(() => {
spyOn(
alfrescoApiService.getInstance().core.queriesApi,
'findSites'
).and.returnValue(
spyOn(alfrescoApiService.getInstance().core.queriesApi, 'findSites').and.returnValue(
Promise.resolve({
list: { entries: [{ entry: { title: 'libraryTitle' } }] }
} as SitePaging)
@@ -287,10 +270,7 @@ describe('LibraryMetadataFormComponent', () => {
}));
it('should not warn if library name is unique', fakeAsync(() => {
spyOn(
alfrescoApiService.getInstance().core.queriesApi,
'findSites'
).and.returnValue(
spyOn(alfrescoApiService.getInstance().core.queriesApi, 'findSites').and.returnValue(
Promise.resolve({
list: { entries: [] }
} as SitePaging)

View File

@@ -36,8 +36,7 @@ import { Observable, from, Subject } from 'rxjs';
selector: 'app-library-metadata-form',
templateUrl: './library-metadata-form.component.html'
})
export class LibraryMetadataFormComponent
implements OnInit, OnChanges, OnDestroy {
export class LibraryMetadataFormComponent implements OnInit, OnChanges, OnDestroy {
@Input()
node: SiteEntry;
@@ -52,29 +51,21 @@ export class LibraryMetadataFormComponent
form: FormGroup = new FormGroup({
id: new FormControl({ value: '', disabled: true }),
title: new FormControl({ value: '' }, [
Validators.required,
Validators.maxLength(256)
]),
title: new FormControl({ value: '' }, [Validators.required, Validators.maxLength(256)]),
description: new FormControl({ value: '' }, [Validators.maxLength(512)]),
visibility: new FormControl(this.libraryType[0].value)
});
onDestroy$: Subject<boolean> = new Subject<boolean>();
constructor(
private alfrescoApiService: AlfrescoApiService,
protected store: Store<AppStore>
) {}
constructor(private alfrescoApiService: AlfrescoApiService, protected store: Store<AppStore>) {}
get canUpdateLibrary() {
return (
this.node && this.node.entry && this.node.entry.role === 'SiteManager'
);
return this.node && this.node.entry && this.node.entry.role === 'SiteManager';
}
getVisibilityLabel(value: string) {
return this.libraryType.find(type => type.value === value).label;
return this.libraryType.find((type) => type.value === value).label;
}
toggleEdit() {
@@ -92,18 +83,17 @@ export class LibraryMetadataFormComponent
this.form.controls['title'].valueChanges
.pipe(
debounceTime(300),
mergeMap(title => this.findLibraryByTitle(title)),
mergeMap((title) => this.findLibraryByTitle(title)),
takeUntil(this.onDestroy$)
)
.subscribe(result => {
.subscribe((result) => {
const { entries } = result.list;
if (entries.length) {
if (this.form.controls.title.value === this.node.entry.title) {
this.libraryTitleExists = false;
} else {
this.libraryTitleExists =
this.form.controls.title.value === entries[0].entry.title;
this.libraryTitleExists = this.form.controls.title.value === entries[0].entry.title;
}
} else {
this.libraryTitleExists = false;
@@ -137,9 +127,7 @@ export class LibraryMetadataFormComponent
});
}
private findLibraryByTitle(
libraryTitle: string
): Observable<SitePaging | { list: { entries: any[] } }> {
private findLibraryByTitle(libraryTitle: string): Observable<SitePaging | { list: { entries: any[] } }> {
return from(
this.alfrescoApiService
.getInstance()

View File

@@ -28,8 +28,7 @@ import { SiteEntry } from '@alfresco/js-api';
@Component({
selector: 'app-metadata-tab',
template:
'<app-library-metadata-form [node]="node"></app-library-metadata-form>',
template: '<app-library-metadata-form [node]="node"></app-library-metadata-form>',
host: { class: 'app-metadata-tab' }
})
export class LibraryMetadataTabComponent {

View File

@@ -30,10 +30,7 @@ import { AppTestingModule } from '../../../testing/app-testing.module';
import { AppConfigService, setupTestBed, CoreModule } from '@alfresco/adf-core';
import { ContentMetadataModule } from '@alfresco/adf-content-services';
import { Store } from '@ngrx/store';
import {
SetInfoDrawerMetadataAspectAction,
AppState
} from '@alfresco/aca-shared/store';
import { SetInfoDrawerMetadataAspectAction, AppState } from '@alfresco/aca-shared/store';
import { By } from '@angular/platform-browser';
import { AppExtensionService } from '@alfresco/aca-shared';
@@ -74,12 +71,8 @@ describe('MetadataTabComponent', () => {
fixture = TestBed.createComponent(MetadataTabComponent);
expect(appConfig.config['content-metadata']).not.toEqual(
'initial config'
);
expect(appConfig.config['content-metadata']).toEqual(
extensions.contentMetadata
);
expect(appConfig.config['content-metadata']).not.toEqual('initial config');
expect(appConfig.config['content-metadata']).toEqual(extensions.contentMetadata);
});
});
@@ -141,21 +134,17 @@ describe('MetadataTabComponent', () => {
});
it('show pass empty when store is in initial state', () => {
const initialState = fixture.debugElement.query(
By.css('adf-content-metadata-card')
);
const initialState = fixture.debugElement.query(By.css('adf-content-metadata-card'));
expect(initialState.componentInstance.displayAspect).toBeFalsy();
});
it('should update the exif if store got updated', () => {
store.dispatch(new SetInfoDrawerMetadataAspectAction('EXIF'));
component.displayAspect$.subscribe(aspect => {
component.displayAspect$.subscribe((aspect) => {
expect(aspect).toBe('EXIF');
});
fixture.detectChanges();
const initialState = fixture.debugElement.query(
By.css('adf-content-metadata-card')
);
const initialState = fixture.debugElement.query(By.css('adf-content-metadata-card'));
expect(initialState.componentInstance.displayAspect).toBe('EXIF');
});
});

View File

@@ -23,19 +23,9 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
Input,
ViewEncapsulation,
OnInit,
OnDestroy
} from '@angular/core';
import { Component, Input, ViewEncapsulation, OnInit, OnDestroy } from '@angular/core';
import { MinimalNodeEntryEntity } from '@alfresco/js-api';
import {
NodePermissionService,
isLocked,
AppExtensionService
} from '@alfresco/aca-shared';
import { NodePermissionService, isLocked, AppExtensionService } from '@alfresco/aca-shared';
import { AppStore, infoDrawerMetadataAspect } from '@alfresco/aca-shared/store';
import { AppConfigService, NotificationService } from '@alfresco/adf-core';
import { Observable, Subject } from 'rxjs';
@@ -46,12 +36,7 @@ import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-metadata-tab',
template: `
<adf-content-metadata-card
[readOnly]="!canUpdateNode"
[preset]="'custom'"
[node]="node"
[displayAspect]="displayAspect$ | async"
>
<adf-content-metadata-card [readOnly]="!canUpdateNode" [preset]="'custom'" [node]="node" [displayAspect]="displayAspect$ | async">
</adf-content-metadata-card>
`,
encapsulation: ViewEncapsulation.None,
@@ -74,9 +59,7 @@ export class MetadataTabComponent implements OnInit, OnDestroy {
private contentMetadataService: ContentMetadataService
) {
if (this.extensions.contentMetadata) {
this.appConfig.config[
'content-metadata'
] = this.extensions.contentMetadata;
this.appConfig.config['content-metadata'] = this.extensions.contentMetadata;
}
this.displayAspect$ = this.store.select(infoDrawerMetadataAspect);
}
@@ -90,11 +73,9 @@ export class MetadataTabComponent implements OnInit, OnDestroy {
}
ngOnInit() {
this.contentMetadataService.error
.pipe(takeUntil(this.onDestroy$))
.subscribe((err: { message: string }) => {
this.notificationService.showError(err.message);
});
this.contentMetadataService.error.pipe(takeUntil(this.onDestroy$)).subscribe((err: { message: string }) => {
this.notificationService.showError(err.message);
});
}
ngOnDestroy() {

View File

@@ -31,12 +31,8 @@ import { MinimalNodeEntryEntity } from '@alfresco/js-api';
template: `
<ng-container *ngIf="isFileSelected; else empty">
<adf-version-manager
[showComments]="
'adf-version-manager.allowComments' | adfAppConfig: true
"
[allowDownload]="
'adf-version-manager.allowDownload' | adfAppConfig: true
"
[showComments]="'adf-version-manager.allowComments' | adfAppConfig: true"
[allowDownload]="'adf-version-manager.allowDownload' | adfAppConfig: true"
[node]="node"
>
</adf-version-manager>

View File

@@ -29,11 +29,7 @@ import { AppConfigService, UserPreferencesService } from '@alfresco/adf-core';
import { AppLayoutComponent } from './app-layout.component';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { Store } from '@ngrx/store';
import {
AppStore,
SetSelectedNodesAction,
ResetSelectionAction
} from '@alfresco/aca-shared/store';
import { AppStore, SetSelectedNodesAction, ResetSelectionAction } from '@alfresco/aca-shared/store';
import { Router, NavigationStart } from '@angular/router';
import { Subject } from 'rxjs';
@@ -110,7 +106,7 @@ describe('AppLayoutComponent', () => {
preserveState: true
};
spyOn(userPreference, 'get').and.callFake(key => {
spyOn(userPreference, 'get').and.callFake((key) => {
if (key === 'expandedSidenav') {
return 'true';
}
@@ -128,7 +124,7 @@ describe('AppLayoutComponent', () => {
preserveState: true
};
spyOn(userPreference, 'get').and.callFake(key => {
spyOn(userPreference, 'get').and.callFake((key) => {
if (key === 'expandedSidenav') {
return 'false';
}
@@ -149,9 +145,7 @@ describe('AppLayoutComponent', () => {
router.navigateByUrl('somewhere/over/the/rainbow');
fixture.detectChanges();
expect(store.dispatch['calls'].mostRecent().args).toEqual([
new ResetSelectionAction()
]);
expect(store.dispatch['calls'].mostRecent().args).toEqual([new ResetSelectionAction()]);
});
it('should close menu on mobile screen size', () => {

View File

@@ -23,29 +23,15 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
AppConfigService,
SidenavLayoutComponent,
UserPreferencesService
} from '@alfresco/adf-core';
import {
Component,
OnDestroy,
OnInit,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import { AppConfigService, SidenavLayoutComponent, UserPreferencesService } from '@alfresco/adf-core';
import { Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { NavigationEnd, Router, NavigationStart } from '@angular/router';
import { Store } from '@ngrx/store';
import { Subject, Observable } from 'rxjs';
import { filter, takeUntil, map, withLatestFrom } from 'rxjs/operators';
import { NodePermissionService } from '@alfresco/aca-shared';
import { BreakpointObserver } from '@angular/cdk/layout';
import {
AppStore,
getCurrentFolder,
ResetSelectionAction
} from '@alfresco/aca-shared/store';
import { AppStore, getCurrentFolder, ResetSelectionAction } from '@alfresco/aca-shared/store';
import { Directionality } from '@angular/cdk/bidi';
@Component({
@@ -82,17 +68,11 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
) {}
ngOnInit() {
this.isSmallScreen$ = this.breakpointObserver
.observe(['(max-width: 600px)'])
.pipe(map(result => result.matches));
this.isSmallScreen$ = this.breakpointObserver.observe(['(max-width: 600px)']).pipe(map((result) => result.matches));
this.hideSidenav = this.hideConditions.some(el =>
this.router.routerState.snapshot.url.includes(el)
);
this.hideSidenav = this.hideConditions.some((el) => this.router.routerState.snapshot.url.includes(el));
this.minimizeSidenav = this.minimizeConditions.some(el =>
this.router.routerState.snapshot.url.includes(el)
);
this.minimizeSidenav = this.minimizeConditions.some((el) => this.router.routerState.snapshot.url.includes(el));
if (!this.minimizeSidenav) {
this.expandedSidenav = this.getSidenavState();
@@ -103,7 +83,7 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
this.store
.select(getCurrentFolder)
.pipe(takeUntil(this.onDestroy$))
.subscribe(node => {
.subscribe((node) => {
this.currentFolderId = node ? node.id : null;
this.canUpload = node && this.permission.check(node, ['create']);
});
@@ -111,10 +91,7 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
this.router.events
.pipe(
withLatestFrom(this.isSmallScreen$),
filter(
([event, isSmallScreen]) =>
isSmallScreen && event instanceof NavigationEnd
),
filter(([event, isSmallScreen]) => isSmallScreen && event instanceof NavigationEnd),
takeUntil(this.onDestroy$)
)
.subscribe(() => {
@@ -123,23 +100,19 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
filter((event) => event instanceof NavigationEnd),
takeUntil(this.onDestroy$)
)
.subscribe((event: NavigationEnd) => {
this.minimizeSidenav = this.minimizeConditions.some(el =>
event.urlAfterRedirects.includes(el)
);
this.hideSidenav = this.hideConditions.some(el =>
event.urlAfterRedirects.includes(el)
);
this.minimizeSidenav = this.minimizeConditions.some((el) => event.urlAfterRedirects.includes(el));
this.hideSidenav = this.hideConditions.some((el) => event.urlAfterRedirects.includes(el));
this.updateState();
});
this.router.events
.pipe(
filter(event => event instanceof NavigationStart),
filter((event) => event instanceof NavigationStart),
takeUntil(this.onDestroy$)
)
.subscribe(() => {
@@ -176,29 +149,17 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
}
onExpanded(state: boolean) {
if (
!this.minimizeSidenav &&
this.appConfigService.get('sideNav.preserveState')
) {
if (!this.minimizeSidenav && this.appConfigService.get('sideNav.preserveState')) {
this.userPreferenceService.set('expandedSidenav', state);
}
}
private getSidenavState(): boolean {
const expand = this.appConfigService.get<boolean>(
'sideNav.expandedSidenav',
true
);
const preserveState = this.appConfigService.get<boolean>(
'sideNav.preserveState',
true
);
const expand = this.appConfigService.get<boolean>('sideNav.expandedSidenav', true);
const preserveState = this.appConfigService.get<boolean>('sideNav.preserveState', true);
if (preserveState) {
return (
this.userPreferenceService.get('expandedSidenav', expand.toString()) ===
'true'
);
return this.userPreferenceService.get('expandedSidenav', expand.toString()) === 'true';
}
return expand;

View File

@@ -26,12 +26,7 @@
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router } from '@angular/router';
import {
AlfrescoApiService,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe
} from '@alfresco/adf-core';
import { AlfrescoApiService, NodeFavoriteDirective, DataTableComponent, AppConfigPipe } from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { LibrariesComponent } from './libraries.component';
import { AppTestingModule } from '../../testing/app-testing.module';
@@ -57,13 +52,7 @@ describe('LibrariesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule, EffectsModule.forRoot([LibraryEffects])],
declarations: [
DataTableComponent,
NodeFavoriteDirective,
DocumentListComponent,
LibrariesComponent,
AppConfigPipe
],
declarations: [DataTableComponent, NodeFavoriteDirective, DocumentListComponent, LibrariesComponent, AppConfigPipe],
schemas: [NO_ERRORS_SCHEMA]
});
@@ -74,12 +63,8 @@ describe('LibrariesComponent', () => {
alfrescoApi.reset();
router = TestBed.inject(Router);
spyOn(alfrescoApi.sitesApi, 'getSites').and.returnValue(
Promise.resolve(page)
);
spyOn(alfrescoApi.peopleApi, 'getSiteMembership').and.returnValue(
Promise.resolve({})
);
spyOn(alfrescoApi.sitesApi, 'getSites').and.returnValue(Promise.resolve(page));
spyOn(alfrescoApi.peopleApi, 'getSiteMembership').and.returnValue(Promise.resolve({}));
});
describe('Node navigation', () => {

View File

@@ -57,11 +57,9 @@ export class LibrariesComponent extends PageComponent implements OnInit {
this.content.libraryUpdated.subscribe(() => this.reload()),
this.content.libraryLeft.subscribe(() => this.reload()),
this.breakpointObserver
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
this.breakpointObserver.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape]).subscribe((result) => {
this.isSmallScreen = result.matches;
})
);
this.columns = this.extensions.documentListPresets.libraries || [];

View File

@@ -34,11 +34,7 @@ describe('AppNodeVersionFormComponent', () => {
let component;
setupTestBed({
imports: [
TranslateModule.forRoot(),
CoreModule.forRoot(),
NoopAnimationsModule
],
imports: [TranslateModule.forRoot(), CoreModule.forRoot(), NoopAnimationsModule],
declarations: [AppNodeVersionFormComponent]
});
@@ -49,9 +45,7 @@ describe('AppNodeVersionFormComponent', () => {
});
it('should have minor version option selected', () => {
const isSelected = fixture.debugElement.nativeElement
.querySelectorAll('.form__version--option')[0]
.classList.contains('mat-radio-checked');
const isSelected = fixture.debugElement.nativeElement.querySelectorAll('.form__version--option')[0].classList.contains('mat-radio-checked');
expect(isSelected).toBe(true);
});

View File

@@ -23,14 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
OnDestroy,
OnInit,
ViewEncapsulation,
Output,
EventEmitter
} from '@angular/core';
import { Component, OnDestroy, OnInit, ViewEncapsulation, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@@ -67,11 +60,9 @@ export class AppNodeVersionFormComponent implements OnInit, OnDestroy {
version: [this.versionOptions[0].value]
});
this.form.valueChanges
.pipe(takeUntil(this.onDestroy$))
.subscribe((values: VersionFormEntry) => {
this.update.emit(values);
});
this.form.valueChanges.pipe(takeUntil(this.onDestroy$)).subscribe((values: VersionFormEntry) => {
this.update.emit(values);
});
}
get versions() {

View File

@@ -25,13 +25,7 @@
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { PageComponent } from './page.component';
import {
ReloadDocumentListAction,
SetSelectedNodesAction,
SetInfoDrawerStateAction,
AppState,
AppStore
} from '@alfresco/aca-shared/store';
import { ReloadDocumentListAction, SetSelectedNodesAction, SetInfoDrawerStateAction, AppState, AppStore } from '@alfresco/aca-shared/store';
import { AppExtensionService } from '@alfresco/aca-shared';
import { MinimalNodeEntity } from '@alfresco/js-api';
import { ContentManagementService } from '../services/content-management.service';
@@ -48,11 +42,7 @@ import { Component } from '@angular/core';
class TestComponent extends PageComponent {
node: any;
constructor(
store: Store<AppStore>,
extensions: AppExtensionService,
content: ContentManagementService
) {
constructor(store: Store<AppStore>, extensions: AppExtensionService, content: ContentManagementService) {
super(store, extensions, content);
}
}
@@ -95,12 +85,12 @@ describe('PageComponent', () => {
window.history.pushState({}, null, locationHref);
});
it('should open info drawer on action event', done => {
it('should open info drawer on action event', (done) => {
window.history.pushState({}, null, `${locationHref}#test`);
fixture.detectChanges();
fixture.whenStable().then(() => {
component.infoDrawerOpened$.subscribe(state => {
component.infoDrawerOpened$.subscribe((state) => {
expect(state).toBe(true);
done();
});
@@ -109,12 +99,12 @@ describe('PageComponent', () => {
store.dispatch(new SetInfoDrawerStateAction(true));
});
it('should not open info drawer if viewer outlet is active', done => {
it('should not open info drawer if viewer outlet is active', (done) => {
window.history.pushState({}, null, `${locationHref}#test(viewer:view)`);
fixture.detectChanges();
fixture.whenStable().then(() => {
component.infoDrawerOpened$.subscribe(state => {
component.infoDrawerOpened$.subscribe((state) => {
expect(state).toBe(false);
done();
});
@@ -143,9 +133,7 @@ describe('PageComponent', () => {
spyOn(store, 'dispatch');
component.reload();
expect(store.dispatch).toHaveBeenCalledWith(
new ReloadDocumentListAction()
);
expect(store.dispatch).toHaveBeenCalledWith(new ReloadDocumentListAction());
});
it('should set selection after reload if node is passed', () => {
@@ -157,9 +145,7 @@ describe('PageComponent', () => {
spyOn(store, 'dispatch');
component.reload(node);
expect(store.dispatch['calls'].mostRecent().args[0]).toEqual(
new SetSelectedNodesAction([node])
);
expect(store.dispatch['calls'].mostRecent().args[0]).toEqual(new SetSelectedNodesAction([node]));
});
});
});

View File

@@ -23,27 +23,12 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
DocumentListComponent,
ShareDataRow
} from '@alfresco/adf-content-services';
import { DocumentListComponent, ShareDataRow } from '@alfresco/adf-content-services';
import { ShowHeaderMode } from '@alfresco/adf-core';
import { ContentActionRef, SelectionState } from '@alfresco/adf-extensions';
import {
OnDestroy,
OnInit,
OnChanges,
ViewChild,
SimpleChanges,
Directive
} from '@angular/core';
import { OnDestroy, OnInit, OnChanges, ViewChild, SimpleChanges, Directive } from '@angular/core';
import { Store } from '@ngrx/store';
import {
MinimalNodeEntity,
MinimalNodeEntryEntity,
Pagination,
NodePaging
} from '@alfresco/js-api';
import { MinimalNodeEntity, MinimalNodeEntryEntity, Pagination, NodePaging } from '@alfresco/js-api';
import { Observable, Subject, Subscription } from 'rxjs';
import { takeUntil, map } from 'rxjs/operators';
import { ContentManagementService } from '../services/content-management.service';
@@ -85,16 +70,12 @@ export abstract class PageComponent implements OnInit, OnDestroy, OnChanges {
protected subscriptions: Subscription[] = [];
constructor(
protected store: Store<AppStore>,
protected extensions: AppExtensionService,
protected content: ContentManagementService
) {}
constructor(protected store: Store<AppStore>, protected extensions: AppExtensionService, protected content: ContentManagementService) {}
ngOnInit() {
this.sharedPreviewUrl$ = this.store.select(getSharedUrl);
this.infoDrawerOpened$ = this.store.select(isInfoDrawerOpened).pipe(
map(infoDrawerState => {
map((infoDrawerState) => {
return !this.isOutletPreviewUrl() && infoDrawerState;
})
);
@@ -104,28 +85,24 @@ export abstract class PageComponent implements OnInit, OnDestroy, OnChanges {
this.store
.select(getAppSelection)
.pipe(takeUntil(this.onDestroy$))
.subscribe(selection => {
.subscribe((selection) => {
this.selection = selection;
this.actions = this.extensions.getAllowedToolbarActions();
this.viewerToolbarActions = this.extensions.getViewerToolbarActions();
this.canUpdateNode =
this.selection.count === 1 &&
this.content.canUpdateNode(selection.first);
this.canUpdateNode = this.selection.count === 1 && this.content.canUpdateNode(selection.first);
});
this.store
.select(getCurrentFolder)
.pipe(takeUntil(this.onDestroy$))
.subscribe(node => {
.subscribe((node) => {
this.canUpload = node && this.content.canUploadContent(node);
});
if (this.documentList && this.documentList.pagination) {
this.documentList.pagination
.pipe(takeUntil(this.onDestroy$))
.subscribe((newPagination: Pagination) => {
this.pagination = newPagination;
});
this.documentList.pagination.pipe(takeUntil(this.onDestroy$)).subscribe((newPagination: Pagination) => {
this.pagination = newPagination;
});
}
}
@@ -136,7 +113,7 @@ export abstract class PageComponent implements OnInit, OnDestroy, OnChanges {
}
ngOnDestroy() {
this.subscriptions.forEach(subscription => subscription.unsubscribe());
this.subscriptions.forEach((subscription) => subscription.unsubscribe());
this.subscriptions = [];
this.onDestroy$.next(true);
@@ -145,8 +122,7 @@ export abstract class PageComponent implements OnInit, OnDestroy, OnChanges {
showPreview(node: MinimalNodeEntity, extras?: ViewNodeExtras) {
if (node && node.entry) {
const id =
(node as any).entry.nodeId || (node as any).entry.guid || node.entry.id;
const id = (node as any).entry.nodeId || (node as any).entry.guid || node.entry.id;
this.store.dispatch(new ViewNodeAction(id, extras));
}

View File

@@ -24,10 +24,7 @@
*/
import { AppStore, SnackbarErrorAction } from '@alfresco/aca-shared/store';
import {
NodePermissionDialogService,
PermissionListComponent
} from '@alfresco/adf-content-services';
import { NodePermissionDialogService, PermissionListComponent } from '@alfresco/adf-content-services';
import { MinimalNodeEntryEntity } from '@alfresco/js-api';
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
@@ -56,11 +53,9 @@ export class PermissionsManagerComponent implements OnInit {
) {}
ngOnInit() {
this.contentApi
.getNodeInfo(this.nodeId, { include: ['permissions'] })
.subscribe((currentNode: MinimalNodeEntryEntity) => {
this.toggleStatus = currentNode.permissions.isInheritanceEnabled;
});
this.contentApi.getNodeInfo(this.nodeId, { include: ['permissions'] }).subscribe((currentNode: MinimalNodeEntryEntity) => {
this.toggleStatus = currentNode.permissions.isInheritanceEnabled;
});
}
onError(errorMessage: string) {
@@ -77,19 +72,17 @@ export class PermissionsManagerComponent implements OnInit {
}
openAddPermissionDialog() {
this.nodePermissionDialogService
.updateNodePermissionByDialog(this.nodeId)
.subscribe(
() => {
this.dialog.open(NodePermissionsDialogComponent, {
data: { nodeId: this.nodeId },
panelClass: 'aca-permissions-dialog-panel',
width: '800px'
});
},
error => {
this.store.dispatch(new SnackbarErrorAction(error));
}
);
this.nodePermissionDialogService.updateNodePermissionByDialog(this.nodeId).subscribe(
() => {
this.dialog.open(NodePermissionsDialogComponent, {
data: { nodeId: this.nodeId },
panelClass: 'aca-permissions-dialog-panel',
width: '800px'
});
},
(error) => {
this.store.dispatch(new SnackbarErrorAction(error));
}
);
}
}

View File

@@ -25,20 +25,8 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {
TestBed,
ComponentFixture,
async,
fakeAsync,
tick
} from '@angular/core/testing';
import {
UserPreferencesService,
AppConfigPipe,
NodeFavoriteDirective,
UploadService,
AlfrescoApiService
} from '@alfresco/adf-core';
import { TestBed, ComponentFixture, async, fakeAsync, tick } from '@angular/core/testing';
import { UserPreferencesService, AppConfigPipe, NodeFavoriteDirective, UploadService, AlfrescoApiService } from '@alfresco/adf-core';
import { ClosePreviewAction } from '@alfresco/aca-shared/store';
import { PreviewComponent } from './preview.component';
import { of, throwError } from 'rxjs';
@@ -48,14 +36,7 @@ import { AppTestingModule } from '../../testing/app-testing.module';
import { ContentApiService } from '@alfresco/aca-shared';
import { ContentManagementService } from '../../services/content-management.service';
import { Store } from '@ngrx/store';
import {
Node,
NodePaging,
FavoritePaging,
SharedLinkPaging,
PersonEntry,
ResultSetPaging
} from '@alfresco/js-api';
import { Node, NodePaging, FavoritePaging, SharedLinkPaging, PersonEntry, ResultSetPaging } from '@alfresco/js-api';
describe('PreviewComponent', () => {
let fixture: ComponentFixture<PreviewComponent>;
@@ -106,12 +87,7 @@ describe('PreviewComponent', () => {
component.previousNodeId = 'previous1';
component.onNavigateBefore(clickEvent);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'folder1',
'preview',
'previous1'
]);
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1', 'preview', 'previous1']);
});
it('should navigate back to previous node in the root path', () => {
@@ -123,11 +99,7 @@ describe('PreviewComponent', () => {
component.previousNodeId = 'previous1';
component.onNavigateBefore(clickEvent);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'preview',
'previous1'
]);
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'previous1']);
});
it('should not navigate back if node unset', () => {
@@ -149,12 +121,7 @@ describe('PreviewComponent', () => {
component.nextNodeId = 'next1';
component.onNavigateNext(clickEvent);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'folder1',
'preview',
'next1'
]);
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1', 'preview', 'next1']);
});
it('should navigate to next node in the root path', () => {
@@ -166,11 +133,7 @@ describe('PreviewComponent', () => {
component.nextNodeId = 'next1';
component.onNavigateNext(clickEvent);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'preview',
'next1'
]);
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'next1']);
});
it('should not navigate back if node unset', () => {
@@ -186,31 +149,19 @@ describe('PreviewComponent', () => {
it('should generate preview path for a folder only', () => {
component.previewLocation = 'personal-files';
expect(component.getPreviewPath('folder1', null)).toEqual([
'personal-files',
'folder1'
]);
expect(component.getPreviewPath('folder1', null)).toEqual(['personal-files', 'folder1']);
});
it('should generate preview path for a folder and a node', () => {
component.previewLocation = 'personal-files';
expect(component.getPreviewPath('folder1', 'node1')).toEqual([
'personal-files',
'folder1',
'preview',
'node1'
]);
expect(component.getPreviewPath('folder1', 'node1')).toEqual(['personal-files', 'folder1', 'preview', 'node1']);
});
it('should generate preview path for a node only', () => {
component.previewLocation = 'personal-files';
expect(component.getPreviewPath(null, 'node1')).toEqual([
'personal-files',
'preview',
'node1'
]);
expect(component.getPreviewPath(null, 'node1')).toEqual(['personal-files', 'preview', 'node1']);
});
it('should generate preview for the location only', () => {
@@ -351,9 +302,7 @@ describe('PreviewComponent', () => {
});
it('should return nearest nodes', async () => {
spyOn(component, 'getFileIds').and.returnValue(
Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5'])
);
spyOn(component, 'getFileIds').and.returnValue(Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5']));
let nearest = await component.getNearestNodes('node1', 'folder1');
expect(nearest).toEqual({ left: null, right: 'node2' });
@@ -366,9 +315,7 @@ describe('PreviewComponent', () => {
});
it('should return empty nearest nodes if node is already deleted', async () => {
spyOn(component, 'getFileIds').and.returnValue(
Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5'])
);
spyOn(component, 'getFileIds').and.returnValue(Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5']));
const nearest = await component.getNearestNodes('node9', 'folder1');
expect(nearest).toEqual({ left: null, right: null });
@@ -429,9 +376,7 @@ describe('PreviewComponent', () => {
isFile: true
} as Node)
);
spyOn(component, 'getNearestNodes').and.returnValue(
Promise.reject('error')
);
spyOn(component, 'getNearestNodes').and.returnValue(Promise.reject('error'));
component.previewLocation = 'personal-files';
await component.displayNode('folder1');
@@ -471,10 +416,7 @@ describe('PreviewComponent', () => {
spyOn(contentApi, 'getNodeChildren').and.returnValue(
of({
list: {
entries: [
{ entry: { id: 'node1', name: 'node 1' } },
{ entry: { id: 'node2', name: 'node 2' } }
]
entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }]
}
} as NodePaging)
);
@@ -490,10 +432,7 @@ describe('PreviewComponent', () => {
spyOn(contentApi, 'getNodeChildren').and.returnValue(
of({
list: {
entries: [
{ entry: { id: 'node1', name: 'node 1' } },
{ entry: { id: 'node2', name: 'node 2' } }
]
entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }]
}
} as NodePaging)
);
@@ -532,10 +471,7 @@ describe('PreviewComponent', () => {
spyOn(contentApi, 'getNodeChildren').and.returnValue(
of({
list: {
entries: [
{ entry: { id: 'node1', name: 'node 1' } },
{ entry: { id: 'node2', name: 'node 2' } }
]
entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }]
}
} as NodePaging)
);
@@ -776,7 +712,7 @@ describe('PreviewComponent', () => {
parent.className = 'adf-viewer__sidebar';
const child = document.createElement('button');
child.addEventListener('keyup', function(e) {
child.addEventListener('keyup', function (e) {
component.onNavigateNext(e);
});
parent.appendChild(child);
@@ -792,7 +728,7 @@ describe('PreviewComponent', () => {
parent.className = 'cdk-overlay-container';
const child = document.createElement('button');
child.addEventListener('keyup', function(e) {
child.addEventListener('keyup', function (e) {
component.onNavigateNext(e);
});
parent.appendChild(child);

View File

@@ -23,35 +23,12 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
OnInit,
OnDestroy,
ViewEncapsulation,
HostListener
} from '@angular/core';
import {
ActivatedRoute,
Router,
UrlTree,
UrlSegmentGroup,
UrlSegment,
PRIMARY_OUTLET
} from '@angular/router';
import { Component, OnInit, OnDestroy, ViewEncapsulation, HostListener } from '@angular/core';
import { ActivatedRoute, Router, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET } from '@angular/router';
import { debounceTime, map, takeUntil } from 'rxjs/operators';
import {
UserPreferencesService,
ObjectUtils,
UploadService,
AlfrescoApiService
} from '@alfresco/adf-core';
import { UserPreferencesService, ObjectUtils, UploadService, AlfrescoApiService } from '@alfresco/adf-core';
import { Store } from '@ngrx/store';
import {
AppStore,
ClosePreviewAction,
ViewerActionTypes,
SetSelectedNodesAction
} from '@alfresco/aca-shared/store';
import { AppStore, ClosePreviewAction, ViewerActionTypes, SetSelectedNodesAction } from '@alfresco/aca-shared/store';
import { PageComponent } from '../page.component';
import { AppExtensionService, ContentApiService } from '@alfresco/aca-shared';
import { ContentManagementService } from '../../services/content-management.service';
@@ -67,18 +44,11 @@ import { Actions, ofType } from '@ngrx/effects';
encapsulation: ViewEncapsulation.None,
host: { class: 'app-preview' }
})
export class PreviewComponent extends PageComponent
implements OnInit, OnDestroy {
export class PreviewComponent extends PageComponent implements OnInit, OnDestroy {
previewLocation: string = null;
routesSkipNavigation = ['shared', 'recent-files', 'favorites'];
navigateSource: string = null;
navigationSources = [
'favorites',
'libraries',
'personal-files',
'recent-files',
'shared'
];
navigationSources = ['favorites', 'libraries', 'personal-files', 'recent-files', 'shared'];
folderId: string = null;
nodeId: string = null;
previousNodeId: string;
@@ -112,11 +82,7 @@ export class PreviewComponent extends PageComponent
'-TYPE:"lnk:link"'
];
private containersSkipNavigation = [
'adf-viewer__sidebar',
'cdk-overlay-container',
'adf-image-viewer'
];
private containersSkipNavigation = ['adf-viewer__sidebar', 'cdk-overlay-container', 'adf-image-viewer'];
constructor(
private contentApi: ContentApiService,
@@ -138,13 +104,11 @@ export class PreviewComponent extends PageComponent
from(this.infoDrawerOpened$)
.pipe(takeUntil(this.onDestroy$))
.subscribe(val => {
.subscribe((val) => {
this.showRightSide = val;
});
this.previewLocation = this.router.url
.substr(0, this.router.url.indexOf('/', 1))
.replace(/\//g, '');
this.previewLocation = this.router.url.substr(0, this.router.url.indexOf('/', 1)).replace(/\//g, '');
const routeData = this.route.snapshot.data;
@@ -159,7 +123,7 @@ export class PreviewComponent extends PageComponent
}
}
this.route.params.subscribe(params => {
this.route.params.subscribe((params) => {
this.folderId = params.folderId;
const id = params.nodeId;
if (id) {
@@ -168,17 +132,11 @@ export class PreviewComponent extends PageComponent
});
this.subscriptions = this.subscriptions.concat([
this.content.nodesDeleted.subscribe(() =>
this.navigateToFileLocation(true)
),
this.content.nodesDeleted.subscribe(() => this.navigateToFileLocation(true)),
this.uploadService.fileUploadDeleted.subscribe(() =>
this.navigateToFileLocation(true)
),
this.uploadService.fileUploadDeleted.subscribe(() => this.navigateToFileLocation(true)),
this.uploadService.fileUploadComplete
.pipe(debounceTime(300))
.subscribe(file => this.apiService.nodeUpdated.next(file.data.entry)),
this.uploadService.fileUploadComplete.pipe(debounceTime(300)).subscribe((file) => this.apiService.nodeUpdated.next(file.data.entry)),
this.actions$
.pipe(
@@ -206,10 +164,7 @@ export class PreviewComponent extends PageComponent
this.store.dispatch(new SetSelectedNodesAction([{ entry: this.node }]));
if (this.node && this.node.isFile) {
const nearest = await this.getNearestNodes(
this.node.id,
this.node.parentId
);
const nearest = await this.getNearestNodes(this.node.id, this.node.parentId);
this.previousNodeId = nearest.left;
this.nextNodeId = nearest.right;
@@ -247,9 +202,7 @@ export class PreviewComponent extends PageComponent
}
navigateToFileLocation(shouldNavigate: boolean) {
const shouldSkipNavigation = this.routesSkipNavigation.includes(
this.previewLocation
);
const shouldSkipNavigation = this.routesSkipNavigation.includes(this.previewLocation);
if (shouldNavigate) {
const route = this.getNavigationCommands(this.previewLocation);
@@ -264,26 +217,18 @@ export class PreviewComponent extends PageComponent
/** Handles navigation to a previous document */
onNavigateBefore(event: MouseEvent | KeyboardEvent): void {
if (
event.type !== 'click' &&
this.shouldNavigate(event.target as HTMLElement)
) {
if (event.type !== 'click' && this.shouldNavigate(event.target as HTMLElement)) {
return;
}
if (this.previousNodeId) {
this.router.navigate(
this.getPreviewPath(this.folderId, this.previousNodeId)
);
this.router.navigate(this.getPreviewPath(this.folderId, this.previousNodeId));
}
}
/** Handles navigation to a next document */
onNavigateNext(event: MouseEvent | KeyboardEvent): void {
if (
event.type !== 'click' &&
this.shouldNavigate(event.target as HTMLElement)
) {
if (event.type !== 'click' && this.shouldNavigate(event.target as HTMLElement)) {
return;
}
@@ -316,10 +261,7 @@ export class PreviewComponent extends PageComponent
* @param nodeId Unique identifier of the document node
* @param folderId Unique identifier of the containing folder node.
*/
async getNearestNodes(
nodeId: string,
folderId: string
): Promise<{ left: string; right: string }> {
async getNearestNodes(nodeId: string, folderId: string): Promise<{ left: string; right: string }> {
const empty = {
left: null,
right: null
@@ -353,10 +295,8 @@ export class PreviewComponent extends PageComponent
*/
async getFileIds(source: string, folderId?: string): Promise<string[]> {
if ((source === 'personal-files' || source === 'libraries') && folderId) {
const sortKey =
this.preferences.get('personal-files.sorting.key') || 'modifiedAt';
const sortDirection =
this.preferences.get('personal-files.sorting.direction') || 'desc';
const sortKey = this.preferences.get('personal-files.sorting.key') || 'modifiedAt';
const sortDirection = this.preferences.get('personal-files.sorting.direction') || 'desc';
const nodes = await this.contentApi
.getNodeChildren(folderId, {
// orderBy: `${sortKey} ${sortDirection}`,
@@ -365,10 +305,10 @@ export class PreviewComponent extends PageComponent
})
.toPromise();
const entries = nodes.list.entries.map(obj => obj.entry);
const entries = nodes.list.entries.map((obj) => obj.entry);
this.sort(entries, sortKey, sortDirection);
return entries.map(obj => obj.id);
return entries.map((obj) => obj.id);
}
if (source === 'favorites') {
@@ -379,21 +319,17 @@ export class PreviewComponent extends PageComponent
})
.toPromise();
const sortKey =
this.preferences.get('favorites.sorting.key') || 'modifiedAt';
const sortDirection =
this.preferences.get('favorites.sorting.direction') || 'desc';
const files = nodes.list.entries.map(obj => obj.entry.target.file);
const sortKey = this.preferences.get('favorites.sorting.key') || 'modifiedAt';
const sortDirection = this.preferences.get('favorites.sorting.direction') || 'desc';
const files = nodes.list.entries.map((obj) => obj.entry.target.file);
this.sort(files, sortKey, sortDirection);
return files.map(f => f.id);
return files.map((f) => f.id);
}
if (source === 'shared') {
const sortingKey =
this.preferences.get('shared.sorting.key') || 'modifiedAt';
const sortingDirection =
this.preferences.get('shared.sorting.direction') || 'desc';
const sortingKey = this.preferences.get('shared.sorting.key') || 'modifiedAt';
const sortingDirection = this.preferences.get('shared.sorting.direction') || 'desc';
const nodes = await this.contentApi
.findSharedLinks({
@@ -401,19 +337,17 @@ export class PreviewComponent extends PageComponent
})
.toPromise();
const entries = nodes.list.entries.map(obj => obj.entry);
const entries = nodes.list.entries.map((obj) => obj.entry);
this.sort(entries, sortingKey, sortingDirection);
return entries.map(obj => obj.nodeId);
return entries.map((obj) => obj.nodeId);
}
if (source === 'recent-files') {
const person = await this.contentApi.getPerson('-me-').toPromise();
const username = person.entry.id;
const sortingKey =
this.preferences.get('recent-files.sorting.key') || 'modifiedAt';
const sortingDirection =
this.preferences.get('recent-files.sorting.direction') || 'desc';
const sortingKey = this.preferences.get('recent-files.sorting.key') || 'modifiedAt';
const sortingDirection = this.preferences.get('recent-files.sorting.direction') || 'desc';
const query: SearchRequest = {
query: {
@@ -439,10 +373,10 @@ export class PreviewComponent extends PageComponent
};
const nodes = await this.contentApi.search(query).toPromise();
const entries = nodes.list.entries.map(obj => obj.entry);
const entries = nodes.list.entries.map((obj) => obj.entry);
this.sort(entries, sortingKey, sortingDirection);
return entries.map(obj => obj.id);
return entries.map((obj) => obj.id);
}
return [];
@@ -458,23 +392,19 @@ export class PreviewComponent extends PageComponent
items.sort((a: any, b: any) => {
let left = ObjectUtils.getValue(a, key);
if (left) {
left =
left instanceof Date ? left.valueOf().toString() : left.toString();
left = left instanceof Date ? left.valueOf().toString() : left.toString();
} else {
left = '';
}
let right = ObjectUtils.getValue(b, key);
if (right) {
right =
right instanceof Date ? right.valueOf().toString() : right.toString();
right = right instanceof Date ? right.valueOf().toString() : right.toString();
} else {
right = '';
}
return direction === 'asc'
? left.localeCompare(right, undefined, options)
: right.localeCompare(left, undefined, options);
return direction === 'asc' ? left.localeCompare(right, undefined, options) : right.localeCompare(left, undefined, options);
});
}
@@ -492,8 +422,7 @@ export class PreviewComponent extends PageComponent
private getNavigationCommands(url: string): any[] {
const urlTree: UrlTree = this.router.parseUrl(url);
const urlSegmentGroup: UrlSegmentGroup =
urlTree.root.children[PRIMARY_OUTLET];
const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
if (!urlSegmentGroup) {
return [url];
@@ -501,7 +430,7 @@ export class PreviewComponent extends PageComponent
const urlSegments: UrlSegment[] = urlSegmentGroup.segments;
return urlSegments.reduce(function(acc, item) {
return urlSegments.reduce(function (acc, item) {
acc.push(item.path, item.parameters);
return acc;
}, []);
@@ -518,8 +447,6 @@ export class PreviewComponent extends PageComponent
}
private isChild(list: DOMTokenList): boolean {
return Array.from(list).some((className: string) =>
this.containersSkipNavigation.includes(className)
);
return Array.from(list).some((className: string) => this.containersSkipNavigation.includes(className));
}
}

View File

@@ -23,20 +23,9 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
TestBed,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
AlfrescoApiService,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe,
UploadService
} from '@alfresco/adf-core';
import { AlfrescoApiService, NodeFavoriteDirective, DataTableComponent, AppConfigPipe, UploadService } from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { RecentFilesComponent } from './recent-files.component';
import { AppTestingModule } from '../../testing/app-testing.module';
@@ -65,13 +54,7 @@ describe('RecentFilesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
DataTableComponent,
NodeFavoriteDirective,
DocumentListComponent,
RecentFilesComponent,
AppConfigPipe
],
declarations: [DataTableComponent, NodeFavoriteDirective, DocumentListComponent, RecentFilesComponent, AppConfigPipe],
providers: [
{
provide: Router,
@@ -94,9 +77,7 @@ describe('RecentFilesComponent', () => {
} as PersonEntry)
);
spyOn(alfrescoApi.searchApi, 'search').and.returnValue(
Promise.resolve(page)
);
spyOn(alfrescoApi.searchApi, 'search').and.returnValue(Promise.resolve(page));
});
it('should call document list reload on fileUploadComplete event', fakeAsync(() => {

View File

@@ -58,18 +58,12 @@ export class RecentFilesComponent extends PageComponent implements OnInit {
super.ngOnInit();
this.subscriptions = this.subscriptions.concat([
this.uploadService.fileUploadComplete
.pipe(debounceTime(300))
.subscribe(() => this.onFileUploadedEvent()),
this.uploadService.fileUploadDeleted
.pipe(debounceTime(300))
.subscribe(() => this.onFileUploadedEvent()),
this.uploadService.fileUploadComplete.pipe(debounceTime(300)).subscribe(() => this.onFileUploadedEvent()),
this.uploadService.fileUploadDeleted.pipe(debounceTime(300)).subscribe(() => this.onFileUploadedEvent()),
this.breakpointObserver
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
this.breakpointObserver.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape]).subscribe((result) => {
this.isSmallScreen = result.matches;
})
]);
this.columns = this.extensions.documentListPresets.recent || [];

View File

@@ -50,7 +50,7 @@ describe('SearchInputControlComponent', () => {
const keyboardEvent = { target: { value: 'a' } };
let eventArgs = null;
component.submit.subscribe(args => (eventArgs = args));
component.submit.subscribe((args) => (eventArgs = args));
await component.searchSubmit(keyboardEvent);
expect(eventArgs).toBe(keyboardEvent);
@@ -60,7 +60,7 @@ describe('SearchInputControlComponent', () => {
const searchTerm = 'b';
let eventArgs = null;
component.searchChange.subscribe(args => (eventArgs = args));
component.searchChange.subscribe((args) => (eventArgs = args));
await component.inputChange(searchTerm);
expect(eventArgs).toBe(searchTerm);
@@ -68,7 +68,7 @@ describe('SearchInputControlComponent', () => {
it('should emit searchChange event on clear', async () => {
let eventArgs = null;
component.searchChange.subscribe(args => (eventArgs = args));
component.searchChange.subscribe((args) => (eventArgs = args));
await component.clear();
expect(eventArgs).toBe('');

View File

@@ -23,16 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
EventEmitter,
Input,
OnDestroy,
Output,
ViewEncapsulation,
ViewChild,
ElementRef
} from '@angular/core';
import { Component, EventEmitter, Input, OnDestroy, Output, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core';
import { Subject } from 'rxjs';
@Component({

View File

@@ -32,12 +32,7 @@ import { ContentModule } from '@alfresco/adf-content-services';
import { A11yModule } from '@angular/cdk/a11y';
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
ContentModule.forChild(),
A11yModule
],
imports: [CommonModule, CoreModule.forChild(), ContentModule.forChild(), A11yModule],
declarations: [SearchInputComponent, SearchInputControlComponent],
exports: [SearchInputComponent, SearchInputControlComponent]
})

View File

@@ -24,21 +24,11 @@
*/
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
TestBed,
async,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import { TestBed, async, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { SearchInputComponent } from './search-input.component';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { Actions, ofType } from '@ngrx/effects';
import {
SearchByTermAction,
SearchActionTypes
} from '@alfresco/aca-shared/store';
import { SearchByTermAction, SearchActionTypes } from '@alfresco/aca-shared/store';
import { map } from 'rxjs/operators';
import { SearchQueryBuilderService } from '@alfresco/adf-content-services';
import { SearchLibrariesQueryBuilderService } from '../search-libraries-results/search-libraries-query-builder.service';
@@ -79,9 +69,7 @@ describe('SearchInputComponent', () => {
});
it('should have library constraint on 400 error received', () => {
const libItem = component.searchOptions.find(
item => item.key.toLowerCase().indexOf('libraries') > 0
);
const libItem = component.searchOptions.find((item) => item.key.toLowerCase().indexOf('libraries') > 0);
libItem.value = true;
content.library400Error.next();
@@ -89,12 +77,12 @@ describe('SearchInputComponent', () => {
});
describe('onSearchSubmit()', () => {
it('should call search action with correct search options', fakeAsync(done => {
it('should call search action with correct search options', fakeAsync((done) => {
const searchedTerm = 's';
const currentSearchOptions = [{ key: 'test' }];
actions$.pipe(
ofType<SearchByTermAction>(SearchActionTypes.SearchByTerm),
map(action => {
map((action) => {
expect(action.searchOptions[0].key).toBe(currentSearchOptions[0].key);
done();
})
@@ -103,11 +91,11 @@ describe('SearchInputComponent', () => {
tick();
}));
it('should call search action with correct searched term', fakeAsync(done => {
it('should call search action with correct searched term', fakeAsync((done) => {
const searchedTerm = 's';
actions$.pipe(
ofType<SearchByTermAction>(SearchActionTypes.SearchByTerm),
map(action => {
map((action) => {
expect(action.payload).toBe(searchedTerm);
done();
})
@@ -118,12 +106,12 @@ describe('SearchInputComponent', () => {
});
describe('onSearchChange()', () => {
it('should call search action with correct search options', fakeAsync(done => {
it('should call search action with correct search options', fakeAsync((done) => {
const searchedTerm = 's';
const currentSearchOptions = [{ key: 'test' }];
actions$.pipe(
ofType<SearchByTermAction>(SearchActionTypes.SearchByTerm),
map(action => {
map((action) => {
expect(action.searchOptions[0].key).toBe(currentSearchOptions[0].key);
done();
})
@@ -132,11 +120,11 @@ describe('SearchInputComponent', () => {
tick(1000);
}));
it('should call search action with correct searched term', fakeAsync(done => {
it('should call search action with correct searched term', fakeAsync((done) => {
const searchedTerm = 's';
actions$.pipe(
ofType<SearchByTermAction>(SearchActionTypes.SearchByTerm),
map(action => {
map((action) => {
expect(action.payload).toBe(searchedTerm);
done();
})
@@ -152,9 +140,7 @@ describe('SearchInputComponent', () => {
});
it('should return true when libraries checked', () => {
const libItem = component.searchOptions.find(
item => item.key.toLowerCase().indexOf('libraries') > 0
);
const libItem = component.searchOptions.find((item) => item.key.toLowerCase().indexOf('libraries') > 0);
libItem.value = true;
expect(component.isLibrariesChecked()).toBe(true);
});
@@ -166,29 +152,21 @@ describe('SearchInputComponent', () => {
});
it('should return true when files checked', () => {
const filesItem = component.searchOptions.find(
item => item.key.toLowerCase().indexOf('files') > 0
);
const filesItem = component.searchOptions.find((item) => item.key.toLowerCase().indexOf('files') > 0);
filesItem.value = true;
expect(component.isContentChecked()).toBe(true);
});
it('should return true when folders checked', () => {
const foldersItem = component.searchOptions.find(
item => item.key.toLowerCase().indexOf('folders') > 0
);
const foldersItem = component.searchOptions.find((item) => item.key.toLowerCase().indexOf('folders') > 0);
foldersItem.value = true;
expect(component.isContentChecked()).toBe(true);
});
it('should return true when both files and folders checked', () => {
const filesItem = component.searchOptions.find(
item => item.key.toLowerCase().indexOf('files') > 0
);
const filesItem = component.searchOptions.find((item) => item.key.toLowerCase().indexOf('files') > 0);
filesItem.value = true;
const foldersItem = component.searchOptions.find(
item => item.key.toLowerCase().indexOf('folders') > 0
);
const foldersItem = component.searchOptions.find((item) => item.key.toLowerCase().indexOf('folders') > 0);
foldersItem.value = true;
expect(component.isContentChecked()).toBe(true);
});

View File

@@ -23,31 +23,12 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
AppStore,
SearchByTermAction,
SearchOptionIds,
SearchOptionModel
} from '@alfresco/aca-shared/store';
import { AppStore, SearchByTermAction, SearchOptionIds, SearchOptionModel } from '@alfresco/aca-shared/store';
import { SearchQueryBuilderService } from '@alfresco/adf-content-services';
import { AppConfigService } from '@alfresco/adf-core';
import {
Component,
OnDestroy,
OnInit,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import { Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { MatMenuTrigger } from '@angular/material/menu';
import {
NavigationEnd,
PRIMARY_OUTLET,
Router,
RouterEvent,
UrlSegment,
UrlSegmentGroup,
UrlTree
} from '@angular/router';
import { NavigationEnd, PRIMARY_OUTLET, Router, RouterEvent, UrlSegment, UrlSegmentGroup, UrlTree } from '@angular/router';
import { Store } from '@ngrx/store';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
@@ -105,10 +86,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
private router: Router,
private store: Store<AppStore>
) {
this.searchOnChange = this.config.get<boolean>(
'search.aca:triggeredOnChange',
true
);
this.searchOnChange = this.config.get<boolean>('search.aca:triggeredOnChange', true);
}
ngOnInit() {
@@ -116,18 +94,16 @@ export class SearchInputComponent implements OnInit, OnDestroy {
this.router.events
.pipe(takeUntil(this.onDestroy$))
.pipe(filter(e => e instanceof RouterEvent))
.subscribe(event => {
.pipe(filter((e) => e instanceof RouterEvent))
.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.showInputValue();
}
});
this.content.library400Error
.pipe(takeUntil(this.onDestroy$))
.subscribe(() => {
this.has400LibraryError = true;
});
this.content.library400Error.pipe(takeUntil(this.onDestroy$)).subscribe(() => {
this.has400LibraryError = true;
});
}
showInputValue() {
@@ -155,9 +131,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
* @param event Parameters relating to the search
*/
onSearchSubmit(event: any) {
const searchTerm = event.target
? (event.target as HTMLInputElement).value
: event;
const searchTerm = event.target ? (event.target as HTMLInputElement).value : event;
if (searchTerm) {
this.searchedWord = searchTerm;
@@ -187,9 +161,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
this.navigationTimer = setTimeout(() => {
if (searchTerm) {
this.store.dispatch(
new SearchByTermAction(searchTerm, this.searchOptions)
);
this.store.dispatch(new SearchByTermAction(searchTerm, this.searchOptions));
}
this.hasOneChange = false;
}, 1000);
@@ -202,9 +174,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
if (this.onLibrariesSearchResults && this.isSameSearchTerm()) {
this.queryLibrariesBuilder.update();
} else if (this.searchedWord) {
this.store.dispatch(
new SearchByTermAction(this.searchedWord, this.searchOptions)
);
this.store.dispatch(new SearchByTermAction(this.searchedWord, this.searchOptions));
}
} else {
if (this.isFoldersChecked() && !this.isFilesChecked()) {
@@ -218,9 +188,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
if (this.onSearchResults && this.isSameSearchTerm()) {
this.queryBuilder.update();
} else if (this.searchedWord) {
this.store.dispatch(
new SearchByTermAction(this.searchedWord, this.searchOptions)
);
this.store.dispatch(new SearchByTermAction(this.searchedWord, this.searchOptions));
}
}
}
@@ -230,9 +198,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
}
get onSearchResults() {
return (
!this.onLibrariesSearchResults && this.router.url.indexOf('/search') === 0
);
return !this.onLibrariesSearchResults && this.router.url.indexOf('/search') === 0;
}
isFilesChecked(): boolean {
@@ -248,7 +214,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
}
isOptionChecked(optionId: string): boolean {
const libItem = this.searchOptions.find(item => item.id === optionId);
const libItem = this.searchOptions.find((item) => item.id === optionId);
return !!libItem && libItem.value;
}
@@ -258,18 +224,13 @@ export class SearchInputComponent implements OnInit, OnDestroy {
hasLibraryConstraint(): boolean {
if (this.isLibrariesChecked()) {
return (
this.has400LibraryError || this.searchInputControl.isTermTooShort()
);
return this.has400LibraryError || this.searchInputControl.isTermTooShort();
}
return false;
}
filterContent(option: SearchOptionIds.Folders | SearchOptionIds.Files) {
const oppositeOption =
option === SearchOptionIds.Folders
? SearchOptionIds.Files
: SearchOptionIds.Folders;
const oppositeOption = option === SearchOptionIds.Folders ? SearchOptionIds.Files : SearchOptionIds.Folders;
this.queryBuilder.addFilterQuery(`+TYPE:'cm:${option}'`);
this.queryBuilder.removeFilterQuery(`+TYPE:'cm:${oppositeOption}'`);
@@ -277,9 +238,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
removeContentFilters() {
this.queryBuilder.removeFilterQuery(`+TYPE:'cm:${SearchOptionIds.Files}'`);
this.queryBuilder.removeFilterQuery(
`+TYPE:'cm:${SearchOptionIds.Folders}'`
);
this.queryBuilder.removeFilterQuery(`+TYPE:'cm:${SearchOptionIds.Folders}'`);
}
syncInputValues() {
@@ -296,14 +255,11 @@ export class SearchInputComponent implements OnInit, OnDestroy {
let searchTerm = '';
if (this.onSearchResults || this.onLibrariesSearchResults) {
const urlTree: UrlTree = this.router.parseUrl(this.router.url);
const urlSegmentGroup: UrlSegmentGroup =
urlTree.root.children[PRIMARY_OUTLET];
const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
if (urlSegmentGroup) {
const urlSegments: UrlSegment[] = urlSegmentGroup.segments;
searchTerm = urlSegments[0].parameters['q']
? decodeURIComponent(urlSegments[0].parameters['q'])
: '';
searchTerm = urlSegments[0].parameters['q'] ? decodeURIComponent(urlSegments[0].parameters['q']) : '';
}
}

View File

@@ -26,10 +26,7 @@
import { TestBed } from '@angular/core/testing';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { AlfrescoApiService } from '@alfresco/adf-core';
import {
SearchLibrariesQueryBuilderService,
LibrarySearchQuery
} from './search-libraries-query-builder.service';
import { SearchLibrariesQueryBuilderService, LibrarySearchQuery } from './search-libraries-query-builder.service';
describe('SearchLibrariesQueryBuilderService', () => {
let apiService: AlfrescoApiService;
@@ -61,7 +58,7 @@ describe('SearchLibrariesQueryBuilderService', () => {
spyOn(builder, 'buildQuery').and.returnValue(query);
let eventArgs = null;
builder.updated.subscribe(args => (eventArgs = args));
builder.updated.subscribe((args) => (eventArgs = args));
await builder.update();
expect(eventArgs).toBe(query);
@@ -74,7 +71,7 @@ describe('SearchLibrariesQueryBuilderService', () => {
spyOn(builder, 'buildQuery').and.returnValue(query);
let eventArgs = null;
builder.executed.subscribe(args => (eventArgs = args));
builder.executed.subscribe((args) => (eventArgs = args));
await builder.execute();
expect(eventArgs).toBe(data);
@@ -111,7 +108,7 @@ describe('SearchLibrariesQueryBuilderService', () => {
spyOn(builder, 'buildQuery').and.returnValue(query);
let eventArgs = null;
builder.hadError.subscribe(args => (eventArgs = args));
builder.hadError.subscribe((args) => (eventArgs = args));
await builder.execute();
expect(eventArgs).toBe(err);

View File

@@ -92,7 +92,7 @@ export class SearchLibrariesQueryBuilderService {
return this.alfrescoApiService
.getInstance()
.core.queriesApi.findSites(libraryQuery.term, libraryQuery.opts)
.catch(err => {
.catch((err) => {
this.hadError.next(err);
return { list: { pagination: { totalItems: 0 }, entries: [] } };
});

View File

@@ -40,12 +40,7 @@ describe('SearchLibrariesResultsComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
DataTableComponent,
DocumentListComponent,
SearchLibrariesResultsComponent,
AppConfigPipe
],
declarations: [DataTableComponent, DocumentListComponent, SearchLibrariesResultsComponent, AppConfigPipe],
schemas: [NO_ERRORS_SCHEMA],
providers: [SearchLibrariesQueryBuilderService]
});

View File

@@ -39,8 +39,7 @@ import { AppExtensionService } from '@alfresco/aca-shared';
templateUrl: './search-libraries-results.component.html',
styleUrls: ['./search-libraries-results.component.scss']
})
export class SearchLibrariesResultsComponent extends PageComponent
implements OnInit {
export class SearchLibrariesResultsComponent extends PageComponent implements OnInit {
isSmallScreen = false;
searchedWord: string;
queryParamName = 'q';
@@ -71,15 +70,9 @@ export class SearchLibrariesResultsComponent extends PageComponent
this.columns = this.extensions.documentListPresets.searchLibraries || [];
this.subscriptions.push(
this.content.libraryJoined.subscribe(() =>
this.librariesQueryBuilder.update()
),
this.content.libraryDeleted.subscribe(() =>
this.librariesQueryBuilder.update()
),
this.content.libraryLeft.subscribe(() =>
this.librariesQueryBuilder.update()
),
this.content.libraryJoined.subscribe(() => this.librariesQueryBuilder.update()),
this.content.libraryDeleted.subscribe(() => this.librariesQueryBuilder.update()),
this.content.libraryLeft.subscribe(() => this.librariesQueryBuilder.update()),
this.librariesQueryBuilder.updated.subscribe(() => {
this.isLoading = true;
@@ -87,12 +80,12 @@ export class SearchLibrariesResultsComponent extends PageComponent
this.librariesQueryBuilder.execute();
}),
this.librariesQueryBuilder.executed.subscribe(data => {
this.librariesQueryBuilder.executed.subscribe((data) => {
this.onSearchResultLoaded(data);
this.isLoading = false;
}),
this.librariesQueryBuilder.hadError.subscribe(err => {
this.librariesQueryBuilder.hadError.subscribe((err) => {
try {
const {
error: { statusCode }
@@ -103,18 +96,14 @@ export class SearchLibrariesResultsComponent extends PageComponent
} catch (e) {}
}),
this.breakpointObserver
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
this.breakpointObserver.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape]).subscribe((result) => {
this.isSmallScreen = result.matches;
})
);
if (this.route) {
this.route.params.forEach((params: Params) => {
this.searchedWord = params.hasOwnProperty(this.queryParamName)
? params[this.queryParamName]
: null;
this.searchedWord = params.hasOwnProperty(this.queryParamName) ? params[this.queryParamName] : null;
const query = this.formatSearchQuery(this.searchedWord);
if (query && query.length > 1) {

View File

@@ -23,14 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
Input,
OnInit,
ViewEncapsulation,
ChangeDetectionStrategy,
OnDestroy
} from '@angular/core';
import { Component, Input, OnInit, ViewEncapsulation, ChangeDetectionStrategy, OnDestroy } from '@angular/core';
import { MinimalNodeEntity } from '@alfresco/js-api';
import { ViewNodeAction, NavigateToFolder } from '@alfresco/aca-shared/store';
import { Store } from '@ngrx/store';
@@ -57,30 +50,24 @@ export class SearchResultsRowComponent implements OnInit, OnDestroy {
name$ = new BehaviorSubject<string>('');
title$ = new BehaviorSubject<string>('');
constructor(
private store: Store<any>,
private alfrescoApiService: AlfrescoApiService,
private router: Router
) {}
constructor(private store: Store<any>, private alfrescoApiService: AlfrescoApiService, private router: Router) {}
ngOnInit() {
this.updateValues();
this.alfrescoApiService.nodeUpdated
.pipe(takeUntil(this.onDestroy$))
.subscribe((node: any) => {
const row = this.context.row;
if (row) {
const { entry } = row.node;
this.alfrescoApiService.nodeUpdated.pipe(takeUntil(this.onDestroy$)).subscribe((node: any) => {
const row = this.context.row;
if (row) {
const { entry } = row.node;
if (entry.id === node.id) {
entry.name = node.name;
entry.properties = Object.assign({}, node.properties);
if (entry.id === node.id) {
entry.name = node.name;
entry.properties = Object.assign({}, node.properties);
this.updateValues();
}
this.updateValues();
}
});
}
});
}
private updateValues() {
@@ -125,9 +112,7 @@ export class SearchResultsRowComponent implements OnInit, OnDestroy {
showPreview(event: MouseEvent) {
event.stopPropagation();
this.store.dispatch(
new ViewNodeAction(this.node.entry.id, { location: this.router.url })
);
this.store.dispatch(new ViewNodeAction(this.node.entry.id, { location: this.router.url }));
}
navigate(event: MouseEvent) {

View File

@@ -49,15 +49,7 @@ import { ContextMenuModule } from '../context-menu/context-menu.module';
AppLayoutModule,
ContextMenuModule
],
declarations: [
SearchResultsComponent,
SearchLibrariesResultsComponent,
SearchResultsRowComponent
],
exports: [
SearchResultsComponent,
SearchLibrariesResultsComponent,
SearchResultsRowComponent
]
declarations: [SearchResultsComponent, SearchLibrariesResultsComponent, SearchResultsRowComponent],
exports: [SearchResultsComponent, SearchLibrariesResultsComponent, SearchResultsRowComponent]
})
export class AppSearchResultsModule {}

View File

@@ -23,28 +23,13 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
ComponentFixture,
TestBed,
fakeAsync,
tick
} from '@angular/core/testing';
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { SearchResultsComponent } from './search-results.component';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { AppSearchResultsModule } from '../search-results.module';
import {
CoreModule,
AppConfigService,
AlfrescoApiService,
AlfrescoApiServiceMock,
TranslationService
} from '@alfresco/adf-core';
import { CoreModule, AppConfigService, AlfrescoApiService, AlfrescoApiServiceMock, TranslationService } from '@alfresco/adf-core';
import { Store } from '@ngrx/store';
import {
NavigateToFolder,
SnackbarErrorAction
} from '@alfresco/aca-shared/store';
import { NavigateToFolder, SnackbarErrorAction } from '@alfresco/aca-shared/store';
import { Pagination, SearchRequest } from '@alfresco/js-api';
import { SearchQueryBuilderService } from '@alfresco/adf-content-services';
import { ActivatedRoute, Router } from '@angular/router';
@@ -63,12 +48,7 @@ describe('SearchComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreModule.forRoot(),
AppTestingModule,
AppSearchResultsModule
],
imports: [TranslateModule.forRoot(), CoreModule.forRoot(), AppTestingModule, AppSearchResultsModule],
providers: [
{
provide: AlfrescoApiService,
@@ -84,8 +64,7 @@ describe('SearchComponent', () => {
},
params: [
{
q:
'TYPE: "cm:folder" AND %28=cm: name: email OR cm: name: budget%29'
q: 'TYPE: "cm:folder" AND %28=cm: name: email OR cm: name: budget%29'
}
]
}
@@ -121,9 +100,7 @@ describe('SearchComponent', () => {
queryBuilder.execute();
tick();
expect(store.dispatch).toHaveBeenCalledWith(
new SnackbarErrorAction('APP.BROWSE.SEARCH.ERRORS.GENERIC')
);
expect(store.dispatch).toHaveBeenCalledWith(new SnackbarErrorAction('APP.BROWSE.SEARCH.ERRORS.GENERIC'));
}));
it('should raise a known error if search fails', fakeAsync(() => {
@@ -146,9 +123,7 @@ describe('SearchComponent', () => {
queryBuilder.execute();
tick();
expect(store.dispatch).toHaveBeenCalledWith(
new SnackbarErrorAction('Known Error')
);
expect(store.dispatch).toHaveBeenCalledWith(new SnackbarErrorAction('Known Error'));
}));
it('should raise a generic error if search fails', fakeAsync(() => {
@@ -171,15 +146,11 @@ describe('SearchComponent', () => {
queryBuilder.execute();
tick();
expect(store.dispatch).toHaveBeenCalledWith(
new SnackbarErrorAction('Generic Error')
);
expect(store.dispatch).toHaveBeenCalledWith(new SnackbarErrorAction('Generic Error'));
}));
it('should decode encoded URI', () => {
expect(queryBuilder.userQuery).toEqual(
'(TYPE: "cm:folder" AND (=cm: name: email OR cm: name: budget))'
);
expect(queryBuilder.userQuery).toEqual('(TYPE: "cm:folder" AND (=cm: name: email OR cm: name: budget))');
});
it('should return null if formatting invalid query', () => {
@@ -228,9 +199,7 @@ describe('SearchComponent', () => {
const query = component.formatSearchQuery('big yellow banana');
expect(query).toBe(
`(cm:name:"big*") AND (cm:name:"yellow*") AND (cm:name:"banana*")`
);
expect(query).toBe(`(cm:name:"big*") AND (cm:name:"yellow*") AND (cm:name:"banana*")`);
});
it('should support conjunctions with AND operator', () => {
@@ -282,9 +251,7 @@ describe('SearchComponent', () => {
const query = component.formatSearchQuery('=test1.pdf or =test2.pdf');
expect(query).toBe(
`(=cm:name:"test1.pdf" OR =cm:title:"test1.pdf") or (=cm:name:"test2.pdf" OR =cm:title:"test2.pdf")`
);
expect(query).toBe(`(=cm:name:"test1.pdf" OR =cm:title:"test1.pdf") or (=cm:name:"test2.pdf" OR =cm:title:"test2.pdf")`);
});
it('should navigate to folder on double click', () => {

View File

@@ -24,24 +24,12 @@
*/
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import {
Pagination,
MinimalNodeEntity,
ResultSetPaging
} from '@alfresco/js-api';
import { Pagination, MinimalNodeEntity, ResultSetPaging } from '@alfresco/js-api';
import { ActivatedRoute, Params, Router } from '@angular/router';
import {
SearchQueryBuilderService,
SearchFilterComponent
} from '@alfresco/adf-content-services';
import { SearchQueryBuilderService, SearchFilterComponent } from '@alfresco/adf-content-services';
import { PageComponent } from '../../page.component';
import { Store } from '@ngrx/store';
import {
AppStore,
NavigateToFolder,
SnackbarErrorAction,
showFacetFilter
} from '@alfresco/aca-shared/store';
import { AppStore, NavigateToFolder, SnackbarErrorAction, showFacetFilter } from '@alfresco/aca-shared/store';
import { ContentManagementService } from '../../../services/content-management.service';
import { AppConfigService, TranslationService } from '@alfresco/adf-core';
import { Observable } from 'rxjs';
@@ -93,14 +81,14 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
this.sorting = this.getSorting();
this.subscriptions.push(
this.queryBuilder.updated.subscribe(query => {
this.queryBuilder.updated.subscribe((query) => {
if (query) {
this.sorting = this.getSorting();
this.isLoading = true;
}
}),
this.queryBuilder.executed.subscribe(data => {
this.queryBuilder.executed.subscribe((data) => {
this.queryBuilder.paging.skipCount = 0;
this.onSearchResultLoaded(data);
@@ -114,9 +102,7 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
if (this.route) {
this.route.params.forEach((params: Params) => {
this.searchedWord = params.hasOwnProperty(this.queryParamName)
? params[this.queryParamName]
: null;
this.searchedWord = params.hasOwnProperty(this.queryParamName) ? params[this.queryParamName] : null;
const query = this.formatSearchQuery(this.searchedWord);
if (query) {
@@ -139,9 +125,7 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
let translated = this.translationService.instant(messageKey);
if (translated === messageKey) {
translated = this.translationService.instant(
`APP.BROWSE.SEARCH.ERRORS.GENERIC`
);
translated = this.translationService.instant(`APP.BROWSE.SEARCH.ERRORS.GENERIC`);
}
this.store.dispatch(new SnackbarErrorAction(translated));
@@ -167,11 +151,7 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
term = term.substring(1);
}
return (
'(' +
fields.map(field => `${prefix}${field}:"${term}${suffix}"`).join(' OR ') +
')'
);
return '(' + fields.map((field) => `${prefix}${field}:"${term}${suffix}"`).join(' OR ') + ')';
}
formatSearchQuery(userInput: string) {
@@ -192,7 +172,7 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
const separator = words.some(this.isOperator) ? ' ' : ' AND ';
return words
.map(term => {
.map((term) => {
if (this.isOperator(term)) {
return term;
}
@@ -219,16 +199,11 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
}
isFiltered(): boolean {
return (
this.searchFilter.selectedBuckets.length > 0 ||
this.hasCheckedCategories()
);
return this.searchFilter.selectedBuckets.length > 0 || this.hasCheckedCategories();
}
hasCheckedCategories() {
const checkedCategory = this.queryBuilder.categories.find(
category => !!this.queryBuilder.queryFragments[category.id]
);
const checkedCategory = this.queryBuilder.categories.find((category) => !!this.queryBuilder.queryFragments[category.id]);
return !!checkedCategory;
}

View File

@@ -29,15 +29,8 @@ import { setupTestBed, StorageService } from '@alfresco/adf-core';
import { AppSettingsModule } from './settings.module';
import { AppTestingModule } from '../../testing/app-testing.module';
import { By } from '@angular/platform-browser';
import {
TranslateModule,
TranslateLoader,
TranslateFakeLoader
} from '@ngx-translate/core';
import {
AppExtensionService,
SettingsParameterRef
} from '@alfresco/aca-shared';
import { TranslateModule, TranslateLoader, TranslateFakeLoader } from '@ngx-translate/core';
import { AppExtensionService, SettingsParameterRef } from '@alfresco/aca-shared';
describe('SettingsComponent', () => {
let fixture: ComponentFixture<SettingsComponent>;
@@ -100,10 +93,7 @@ describe('SettingsComponent', () => {
component.setParamValue(stringParam, 'test');
expect(stringParam.value).toBe('test');
expect(storage.setItem).toHaveBeenCalledWith(
stringParam.key,
stringParam.value
);
expect(storage.setItem).toHaveBeenCalledWith(stringParam.key, stringParam.value);
});
it('should save param value only if changed', () => {
@@ -148,9 +138,7 @@ describe('SettingsComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
const panels = fixture.debugElement.queryAll(
By.css('.mat-expansion-panel')
);
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
expect(panels.length).toBe(3);
});
});

View File

@@ -24,27 +24,13 @@
*/
import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import {
AppConfigService,
StorageService,
OauthConfigModel
} from '@alfresco/adf-core';
import { AppConfigService, StorageService, OauthConfigModel } from '@alfresco/adf-core';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import {
AppStore,
getHeaderColor,
getAppName,
getUserProfile,
SetSettingsParameterAction
} from '@alfresco/aca-shared/store';
import { AppStore, getHeaderColor, getAppName, getUserProfile, SetSettingsParameterAction } from '@alfresco/aca-shared/store';
import { ProfileState } from '@alfresco/adf-extensions';
import {
AppExtensionService,
SettingsGroupRef,
SettingsParameterRef
} from '@alfresco/aca-shared';
import { AppExtensionService, SettingsGroupRef, SettingsParameterRef } from '@alfresco/aca-shared';
interface RepositoryConfig {
ecmHost: string;
@@ -89,14 +75,8 @@ export class SettingsComponent implements OnInit {
ngOnInit() {
this.form = this.fb.group({
ecmHost: [
'',
[Validators.required, Validators.pattern('^(http|https)://.*[^/]$')]
],
aisHost: [
'',
[Validators.required, Validators.pattern('^(http|https)://.*[^/]$')]
],
ecmHost: ['', [Validators.required, Validators.pattern('^(http|https)://.*[^/]$')]],
aisHost: ['', [Validators.required, Validators.pattern('^(http|https)://.*[^/]$')]],
authType: ['']
});
@@ -108,10 +88,7 @@ export class SettingsComponent implements OnInit {
this.storage.setItem('ecmHost', model.ecmHost);
this.storage.setItem('authType', model.authType);
const config: OauthConfigModel = this.appConfig.get<OauthConfigModel>(
'oauth2',
null
);
const config: OauthConfigModel = this.appConfig.get<OauthConfigModel>('oauth2', null);
config.host = model.aisHost;
this.storage.setItem('oauth2', JSON.stringify(config));
@@ -120,15 +97,10 @@ export class SettingsComponent implements OnInit {
}
reset() {
const config: OauthConfigModel = this.appConfig.get<OauthConfigModel>(
'oauth2',
null
);
const config: OauthConfigModel = this.appConfig.get<OauthConfigModel>('oauth2', null);
this.form.reset({
ecmHost:
this.storage.getItem('ecmHost') ||
this.appConfig.get<string>('ecmHost'),
ecmHost: this.storage.getItem('ecmHost') || this.appConfig.get<string>('ecmHost'),
aisHost: config.host,
authType: this.appConfig.get<string>('authType')
});
@@ -157,12 +129,7 @@ export class SettingsComponent implements OnInit {
}
private saveToStorage(param: SettingsParameterRef) {
this.storage.setItem(
param.key,
param.value ? param.value.toString() : param.value
);
this.store.dispatch(
new SetSettingsParameterAction({ name: param.key, value: param.value })
);
this.storage.setItem(param.key, param.value ? param.value.toString() : param.value);
this.store.dispatch(new SetSettingsParameterAction({ name: param.key, value: param.value }));
}
}

View File

@@ -23,12 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
TestBed,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
AlfrescoApiService,
@@ -67,13 +62,7 @@ describe('SharedFilesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
DataTableComponent,
NodeFavoriteDirective,
DocumentListComponent,
SharedFilesComponent,
AppConfigPipe
],
declarations: [DataTableComponent, NodeFavoriteDirective, DocumentListComponent, SharedFilesComponent, AppConfigPipe],
providers: [
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock },
{
@@ -92,9 +81,7 @@ describe('SharedFilesComponent', () => {
alfrescoApi = TestBed.inject(AlfrescoApiService);
alfrescoApi.reset();
spyOn(alfrescoApi.sharedLinksApi, 'findSharedLinks').and.returnValue(
Promise.resolve(page)
);
spyOn(alfrescoApi.sharedLinksApi, 'findSharedLinks').and.returnValue(Promise.resolve(page));
});
it('should call document list reload on linksUnshared event', fakeAsync(() => {

View File

@@ -57,22 +57,14 @@ export class SharedFilesComponent extends PageComponent implements OnInit {
super.ngOnInit();
this.subscriptions = this.subscriptions.concat([
this.content.linksUnshared
.pipe(debounceTime(300))
.subscribe(() => this.reload()),
this.content.linksUnshared.pipe(debounceTime(300)).subscribe(() => this.reload()),
this.uploadService.fileUploadComplete
.pipe(debounceTime(300))
.subscribe(_ => this.reload()),
this.uploadService.fileUploadDeleted
.pipe(debounceTime(300))
.subscribe(_ => this.reload()),
this.uploadService.fileUploadComplete.pipe(debounceTime(300)).subscribe((_) => this.reload()),
this.uploadService.fileUploadDeleted.pipe(debounceTime(300)).subscribe((_) => this.reload()),
this.breakpointObserver
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
this.breakpointObserver.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape]).subscribe((result) => {
this.isSmallScreen = result.matches;
})
]);
this.columns = this.extensions.documentListPresets.shared || [];

View File

@@ -24,12 +24,7 @@
*/
import { SharedLinkViewComponent } from './shared-link-view.component';
import {
TestBed,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { Store } from '@ngrx/store';
import { AppTestingModule } from '../../testing/app-testing.module';
import { ActivatedRoute } from '@angular/router';
@@ -81,10 +76,7 @@ describe('SharedLinkViewComponent', () => {
alfrescoApiService = TestBed.inject(AlfrescoApiService);
appExtensionService = TestBed.inject(AppExtensionService);
spyGetSharedLink = spyOn(
alfrescoApiService.sharedLinksApi,
'getSharedLink'
);
spyGetSharedLink = spyOn(alfrescoApiService.sharedLinksApi, 'getSharedLink');
storeMock.dispatch.calls.reset();
});
@@ -94,16 +86,12 @@ describe('SharedLinkViewComponent', () => {
});
it('should update store selection', fakeAsync(() => {
spyGetSharedLink.and.returnValue(
Promise.resolve({ entry: { id: 'shared-id' } })
);
spyGetSharedLink.and.returnValue(Promise.resolve({ entry: { id: 'shared-id' } }));
fixture.detectChanges();
tick();
expect(storeMock.dispatch).toHaveBeenCalledWith(
new SetSelectedNodesAction([{ entry: { id: 'shared-id' } } as any])
);
expect(storeMock.dispatch).toHaveBeenCalledWith(new SetSelectedNodesAction([{ entry: { id: 'shared-id' } } as any]));
}));
it('should not update store on error', fakeAsync(() => {
@@ -118,9 +106,7 @@ describe('SharedLinkViewComponent', () => {
it('should not update actions reference if selection is empty', fakeAsync(() => {
spyOn(storeMock, 'select').and.returnValue(of({ isEmpty: true }));
spyGetSharedLink.and.returnValue(
Promise.resolve({ entry: { id: 'shared-id' } })
);
spyGetSharedLink.and.returnValue(Promise.resolve({ entry: { id: 'shared-id' } }));
fixture.detectChanges();
tick();
@@ -131,22 +117,16 @@ describe('SharedLinkViewComponent', () => {
it('should update actions reference if selection is not empty', fakeAsync(() => {
spyOn(storeMock, 'select').and.returnValue(of({ isEmpty: false }));
spyOn(appExtensionService, 'getSharedLinkViewerToolbarActions');
spyGetSharedLink.and.returnValue(
Promise.resolve({ entry: { id: 'shared-id' } })
);
spyGetSharedLink.and.returnValue(Promise.resolve({ entry: { id: 'shared-id' } }));
fixture.detectChanges();
tick();
expect(
appExtensionService.getSharedLinkViewerToolbarActions
).toHaveBeenCalled();
expect(appExtensionService.getSharedLinkViewerToolbarActions).toHaveBeenCalled();
}));
it('should fetch link id from the active route', fakeAsync(() => {
spyGetSharedLink.and.returnValue(
Promise.resolve({ entry: { id: 'shared-id' } })
);
spyGetSharedLink.and.returnValue(Promise.resolve({ entry: { id: 'shared-id' } }));
fixture.detectChanges();
tick();

View File

@@ -23,11 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
AppStore,
SetSelectedNodesAction,
getAppSelection
} from '@alfresco/aca-shared/store';
import { AppStore, SetSelectedNodesAction, getAppSelection } from '@alfresco/aca-shared/store';
import { AlfrescoApiService } from '@alfresco/adf-core';
import { ContentActionRef } from '@alfresco/adf-extensions';
import { SharedLinkEntry } from '@alfresco/js-api';
@@ -59,13 +55,8 @@ export class SharedLinkViewComponent implements OnInit {
ngOnInit() {
this.route.params
.pipe(
flatMap(params =>
forkJoin(
from(
this.alfrescoApiService.sharedLinksApi.getSharedLink(params.id)
),
of(params.id)
).pipe(catchError(() => of([null, params.id])))
flatMap((params) =>
forkJoin(from(this.alfrescoApiService.sharedLinksApi.getSharedLink(params.id)), of(params.id)).pipe(catchError(() => of([null, params.id])))
)
)
.subscribe(([sharedEntry, sharedId]: [SharedLinkEntry, string]) => {
@@ -75,9 +66,8 @@ export class SharedLinkViewComponent implements OnInit {
this.sharedLinkId = sharedId;
});
this.store.select(getAppSelection).subscribe(selection => {
if (!selection.isEmpty)
this.viewerToolbarActions = this.extensions.getSharedLinkViewerToolbarActions();
this.store.select(getAppSelection).subscribe((selection) => {
if (!selection.isEmpty) this.viewerToolbarActions = this.extensions.getSharedLinkViewerToolbarActions();
});
}

View File

@@ -27,11 +27,7 @@ import { ButtonMenuComponent } from './button-menu.component';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { Router } from '@angular/router';
import {
TranslateModule,
TranslateLoader,
TranslateFakeLoader
} from '@ngx-translate/core';
import { TranslateModule, TranslateLoader, TranslateFakeLoader } from '@ngx-translate/core';
import { AppSidenavModule } from '../sidenav.module';
describe('ButtonMenuComponent', () => {
@@ -88,9 +84,7 @@ describe('ButtonMenuComponent', () => {
fixture.detectChanges();
const actionButton = document.body.querySelector(
'[id="test-action-button"]'
);
const actionButton = document.body.querySelector('[id="test-action-button"]');
actionButton.dispatchEvent(new Event('click'));
expect(document.querySelector('[id="child-1"]')).not.toBeNull();

View File

@@ -23,13 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
Input,
ViewEncapsulation,
OnInit,
ChangeDetectorRef
} from '@angular/core';
import { Component, Input, ViewEncapsulation, OnInit, ChangeDetectorRef } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
@Component({
@@ -41,10 +35,7 @@ import { OverlayContainer } from '@angular/cdk/overlay';
export class ButtonMenuComponent implements OnInit {
@Input() item;
constructor(
private cd: ChangeDetectorRef,
private overlayContainer: OverlayContainer
) {
constructor(private cd: ChangeDetectorRef, private overlayContainer: OverlayContainer) {
this.overlayContainer.getContainerElement().classList.add('aca-menu-panel');
}

View File

@@ -27,11 +27,7 @@ import { ExpandMenuComponent } from './expand-menu.component';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { Router } from '@angular/router';
import {
TranslateModule,
TranslateLoader,
TranslateFakeLoader
} from '@ngx-translate/core';
import { TranslateModule, TranslateLoader, TranslateFakeLoader } from '@ngx-translate/core';
import { AppSidenavModule } from '../sidenav.module';
describe('ExpandMenuComponent', () => {
@@ -88,9 +84,7 @@ describe('ExpandMenuComponent', () => {
fixture.detectChanges();
const actionButton = document.body.querySelector(
'[id="test-action-button"]'
);
const actionButton = document.body.querySelector('[id="test-action-button"]');
actionButton.dispatchEvent(new Event('click'));
expect(document.querySelector('[id="child-1"]')).not.toBeNull();

View File

@@ -23,13 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
OnInit,
Input,
ViewEncapsulation,
ChangeDetectorRef
} from '@angular/core';
import { Component, OnInit, Input, ViewEncapsulation, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-expand-menu',

View File

@@ -60,7 +60,7 @@ export class ActionDirective {
const urlSegments = urlSegmentGroup.segments;
return urlSegments.reduce(function(acc, item) {
return urlSegments.reduce(function (acc, item) {
acc.push(item.path, item.parameters);
return acc;
}, []);

View File

@@ -32,13 +32,7 @@ import { Subject } from 'rxjs';
@Component({
selector: 'app-test-component',
template: `
<span
id="test-element"
acaActiveLink="active-link-class"
[action]="item"
></span>
`
template: ` <span id="test-element" acaActiveLink="active-link-class" [action]="item"></span> `
})
class TestComponent {
item = {
@@ -81,29 +75,17 @@ describe('ActionDirective', () => {
fixture.detectChanges();
router.navigateByUrl('/dummy');
// fixture.detectChanges();
expect(
document.body
.querySelector('#test-element')
.className.includes('active-link-class')
).toBe(true);
expect(document.body.querySelector('#test-element').className.includes('active-link-class')).toBe(true);
});
it('should remove class name if route not active', () => {
fixture.detectChanges();
router.navigateByUrl('/dummy');
expect(
document.body
.querySelector('#test-element')
.className.includes('active-link-class')
).toBe(true);
expect(document.body.querySelector('#test-element').className.includes('active-link-class')).toBe(true);
router.navigateByUrl('/other');
expect(
document.body
.querySelector('#test-element')
.className.includes('active-link-class')
).not.toBe(true);
expect(document.body.querySelector('#test-element').className.includes('active-link-class')).not.toBe(true);
});
});

View File

@@ -23,17 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Directive,
OnInit,
Input,
ElementRef,
Renderer2,
ContentChildren,
QueryList,
AfterContentInit,
Optional
} from '@angular/core';
import { Directive, OnInit, Input, ElementRef, Renderer2, ContentChildren, QueryList, AfterContentInit, Optional } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
@@ -51,17 +41,12 @@ export class ActiveLinkDirective implements OnInit, AfterContentInit {
private onDestroy$: Subject<boolean> = new Subject<boolean>();
constructor(
private router: Router,
private element: ElementRef,
private renderer: Renderer2,
@Optional() private action?: ActionDirective
) {}
constructor(private router: Router, private element: ElementRef, private renderer: Renderer2, @Optional() private action?: ActionDirective) {}
ngOnInit() {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
filter((event) => event instanceof NavigationEnd),
takeUntil(this.onDestroy$)
)
.subscribe((event: NavigationEnd) => {
@@ -75,7 +60,7 @@ export class ActiveLinkDirective implements OnInit, AfterContentInit {
this.render(url, itemUrl);
}
this.links.map(item => {
this.links.map((item) => {
const itemUrl = this.resolveUrl(item);
this.render(url, itemUrl);
});
@@ -97,9 +82,6 @@ export class ActiveLinkDirective implements OnInit, AfterContentInit {
}
private resolveUrl(item): string {
return (
(item.action && item.action.click && item.action.click.payload) ||
item.action.route
);
return (item.action && item.action.click && item.action.click.payload) || item.action.route;
}
}

View File

@@ -65,11 +65,7 @@ describe('AcaExpansionPanel', () => {
const item = {
children: [{ url: 'dummy-route-1' }, { url: 'dummy-route-2' }]
};
const directive = new ExpansionPanelDirective(
mockStore,
router,
mockMatExpansionPanel
);
const directive = new ExpansionPanelDirective(mockStore, router, mockMatExpansionPanel);
directive.acaExpansionPanel = item;
@@ -80,11 +76,7 @@ describe('AcaExpansionPanel', () => {
const item = {
children: [{ url: 'dummy-route-1' }, { url: 'dummy-route-2' }]
};
const directive = new ExpansionPanelDirective(
mockStore,
router,
mockMatExpansionPanel
);
const directive = new ExpansionPanelDirective(mockStore, router, mockMatExpansionPanel);
directive.acaExpansionPanel = item;
@@ -102,11 +94,7 @@ describe('AcaExpansionPanel', () => {
mockMatExpansionPanel.expanded = true;
const directive = new ExpansionPanelDirective(
mockStore,
router,
mockMatExpansionPanel
);
const directive = new ExpansionPanelDirective(mockStore, router, mockMatExpansionPanel);
directive.acaExpansionPanel = item;
@@ -122,11 +110,7 @@ describe('AcaExpansionPanel', () => {
children: [{ url: 'dummy-route-1' }, { url: 'dummy-route-2' }]
};
const directive = new ExpansionPanelDirective(
mockStore,
router,
mockMatExpansionPanel
);
const directive = new ExpansionPanelDirective(mockStore, router, mockMatExpansionPanel);
directive.acaExpansionPanel = item;
mockMatExpansionPanel.expanded = true;

View File

@@ -23,13 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Directive,
Input,
HostListener,
OnInit,
OnDestroy
} from '@angular/core';
import { Directive, Input, HostListener, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, PRIMARY_OUTLET } from '@angular/router';
import { filter, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
@@ -61,15 +55,11 @@ export class ExpansionPanelDirective implements OnInit, OnDestroy {
}
}
constructor(
private store: Store<any>,
private router: Router,
private expansionPanel: MatExpansionPanel
) {}
constructor(private store: Store<any>, private router: Router, private expansionPanel: MatExpansionPanel) {}
hasActiveLinks() {
if (this.acaExpansionPanel && this.acaExpansionPanel.children) {
return this.acaExpansionPanel.children.some(child => {
return this.acaExpansionPanel.children.some((child) => {
return this.router.url.startsWith(child.url || child.action.payload);
});
}
@@ -81,7 +71,7 @@ export class ExpansionPanelDirective implements OnInit, OnDestroy {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
filter((event) => event instanceof NavigationEnd),
takeUntil(this.onDestroy$)
)
.subscribe(() => {
@@ -104,7 +94,7 @@ export class ExpansionPanelDirective implements OnInit, OnDestroy {
const urlSegments = urlSegmentGroup.segments;
return urlSegments.reduce(function(acc, item) {
return urlSegments.reduce(function (acc, item) {
acc.push(item.path, item.parameters);
return acc;
}, []);

View File

@@ -23,13 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Directive,
Input,
OnInit,
OnDestroy,
HostListener
} from '@angular/core';
import { Directive, Input, OnInit, OnDestroy, HostListener } from '@angular/core';
import { Router, NavigationEnd, PRIMARY_OUTLET } from '@angular/router';
import { filter, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
@@ -64,7 +58,7 @@ export class MenuPanelDirective implements OnInit, OnDestroy {
hasActiveLinks() {
if (this.acaMenuPanel && this.acaMenuPanel.children) {
return this.acaMenuPanel.children.some(child => {
return this.acaMenuPanel.children.some((child) => {
return this.router.url.startsWith(child.url || child.action.payload);
});
}
@@ -76,7 +70,7 @@ export class MenuPanelDirective implements OnInit, OnDestroy {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
filter((event) => event instanceof NavigationEnd),
takeUntil(this.onDestroy$)
)
.subscribe(() => {
@@ -99,7 +93,7 @@ export class MenuPanelDirective implements OnInit, OnDestroy {
const urlSegments = urlSegmentGroup.segments;
return urlSegments.reduce(function(acc, item) {
return urlSegments.reduce(function (acc, item) {
acc.push(item.path, item.parameters);
return acc;
}, []);

View File

@@ -23,15 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Component,
ContentChild,
Input,
TemplateRef,
OnInit,
ViewEncapsulation,
OnDestroy
} from '@angular/core';
import { Component, ContentChild, Input, TemplateRef, OnInit, ViewEncapsulation, OnDestroy } from '@angular/core';
import { CollapsedTemplateDirective } from './directives/collapsed-template.directive';
import { ExpandedTemplateDirective } from './directives/expanded-template.directive';
import { NavBarGroupRef } from '@alfresco/adf-extensions';
@@ -50,7 +42,8 @@ import { AppExtensionService } from '@alfresco/aca-shared';
host: { class: 'app-sidenav' }
})
export class SidenavComponent implements OnInit, OnDestroy {
@Input() mode: 'collapsed' | 'expanded' = 'expanded';
@Input()
mode: 'collapsed' | 'expanded' = 'expanded';
@ContentChild(ExpandedTemplateDirective, { read: TemplateRef })
expandedTemplate;
@@ -63,24 +56,14 @@ export class SidenavComponent implements OnInit, OnDestroy {
groups: Array<NavBarGroupRef> = [];
private onDestroy$: Subject<boolean> = new Subject<boolean>();
constructor(
private store: Store<AppStore>,
private extensions: AppExtensionService,
private authService: AuthenticationService
) {}
constructor(private store: Store<AppStore>, private extensions: AppExtensionService, private authService: AuthenticationService) {}
ngOnInit() {
this.store
.select(getSideNavState)
.pipe(
debounceTime(300),
distinctUntilChanged(),
takeUntil(this.onDestroy$)
)
.pipe(debounceTime(300), distinctUntilChanged(), takeUntil(this.onDestroy$))
.subscribe(() => {
this.groups = this.extensions.getApplicationNavigation(
this.extensions.navbar
);
this.groups = this.extensions.getApplicationNavigation(this.extensions.navbar);
});
}

View File

@@ -40,14 +40,7 @@ import { ExpandMenuComponent } from './components/expand-menu.component';
import { ButtonMenuComponent } from './components/button-menu.component';
import { ActionDirective } from './directives/action.directive';
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
CoreExtensionsModule.forChild(),
ExtensionsModule.forChild(),
RouterModule,
AppCreateMenuModule
],
imports: [CommonModule, CoreModule.forChild(), CoreExtensionsModule.forChild(), ExtensionsModule.forChild(), RouterModule, AppCreateMenuModule],
declarations: [
MenuPanelDirective,
ExpansionPanelDirective,

View File

@@ -26,11 +26,7 @@
import { Component, ViewEncapsulation } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import {
AppStore,
ToggleDocumentDisplayMode,
getDocumentDisplayMode
} from '@alfresco/aca-shared/store';
import { AppStore, ToggleDocumentDisplayMode, getDocumentDisplayMode } from '@alfresco/aca-shared/store';
@Component({
selector: 'app-document-display-mode',
@@ -59,9 +55,7 @@ export class DocumentDisplayModeComponent {
}
getTitle(displayMode: string): string {
return displayMode === 'list'
? 'APP.ACTIONS.LIST_MODE'
: 'APP.ACTIONS.GALLERY_MODE';
return displayMode === 'list' ? 'APP.ACTIONS.LIST_MODE' : 'APP.ACTIONS.GALLERY_MODE';
}
onClick() {

View File

@@ -30,11 +30,7 @@ import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { Store } from '@ngrx/store';
import { NodeEntry } from '@alfresco/js-api';
import {
DownloadNodesAction,
EditOfflineAction,
SnackbarErrorAction
} from '@alfresco/aca-shared/store';
import { DownloadNodesAction, EditOfflineAction, SnackbarErrorAction } from '@alfresco/aca-shared/store';
import { TranslateModule } from '@ngx-translate/core';
describe('ToggleEditOfflineComponent', () => {
@@ -89,9 +85,7 @@ describe('ToggleEditOfflineComponent', () => {
fixture.detectChanges();
expect(dispatchSpy.calls.argsFor(0)).toEqual([
new DownloadNodesAction([selection.file as NodeEntry])
]);
expect(dispatchSpy.calls.argsFor(0)).toEqual([new DownloadNodesAction([selection.file as NodeEntry])]);
});
it('should not download content if node is not locked', () => {
@@ -103,9 +97,7 @@ describe('ToggleEditOfflineComponent', () => {
fixture.detectChanges();
expect(dispatchSpy.calls.argsFor(0)).not.toEqual([
new DownloadNodesAction([selection.file as NodeEntry])
]);
expect(dispatchSpy.calls.argsFor(0)).not.toEqual([new DownloadNodesAction([selection.file as NodeEntry])]);
});
it('should dispatch EditOfflineAction action', () => {
@@ -117,9 +109,7 @@ describe('ToggleEditOfflineComponent', () => {
fixture.detectChanges();
expect(dispatchSpy.calls.argsFor(0)).toEqual([
new EditOfflineAction(selection.file as NodeEntry)
]);
expect(dispatchSpy.calls.argsFor(0)).toEqual([new EditOfflineAction(selection.file as NodeEntry)]);
});
it('should raise notification on lock error', () => {

View File

@@ -23,13 +23,7 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
AppStore,
DownloadNodesAction,
EditOfflineAction,
SnackbarErrorAction,
getAppSelection
} from '@alfresco/aca-shared/store';
import { AppStore, DownloadNodesAction, EditOfflineAction, SnackbarErrorAction, getAppSelection } from '@alfresco/aca-shared/store';
import { MinimalNodeEntity } from '@alfresco/js-api';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Store } from '@ngrx/store';
@@ -44,11 +38,7 @@ import { Store } from '@ngrx/store';
(lockError)="onLockError()"
(unlockError)="onUnlockLockError()"
[acaLockNode]="selection"
[attr.title]="
lock.isNodeLocked()
? ('APP.ACTIONS.EDIT_OFFLINE_CANCEL' | translate)
: ('APP.ACTIONS.EDIT_OFFLINE' | translate)
"
[attr.title]="lock.isNodeLocked() ? ('APP.ACTIONS.EDIT_OFFLINE_CANCEL' | translate) : ('APP.ACTIONS.EDIT_OFFLINE' | translate)"
>
<ng-container *ngIf="lock.isNodeLocked()">
<mat-icon>cancel</mat-icon>

View File

@@ -24,11 +24,7 @@
*/
import { TestBed, ComponentFixture } from '@angular/core/testing';
import {
CoreModule,
AlfrescoApiService,
AlfrescoApiServiceMock
} from '@alfresco/adf-core';
import { CoreModule, AlfrescoApiService, AlfrescoApiServiceMock } from '@alfresco/adf-core';
import { ToggleFavoriteLibraryComponent } from './toggle-favorite-library.component';
import { LibraryFavoriteDirective } from '../../../directives/library-favorite.directive';
import { NO_ERRORS_SCHEMA } from '@angular/core';
@@ -50,11 +46,7 @@ describe('ToggleFavoriteLibraryComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreModule.forRoot(),
AppTestingModule
],
imports: [TranslateModule.forRoot(), CoreModule.forRoot(), AppTestingModule],
declarations: [ToggleFavoriteLibraryComponent, LibraryFavoriteDirective],
providers: [
{
@@ -84,9 +76,7 @@ describe('ToggleFavoriteLibraryComponent', () => {
contentManagementService = TestBed.inject(ContentManagementService);
const api = TestBed.inject(AlfrescoApiService);
spyOn(api.peopleApi, 'getFavoriteSite').and.returnValue(
Promise.resolve(null)
);
spyOn(api.peopleApi, 'getFavoriteSite').and.returnValue(Promise.resolve(null));
});
it('should get library selection from Store', async () => {
@@ -112,8 +102,6 @@ describe('ToggleFavoriteLibraryComponent', () => {
component.onToggleEvent();
expect(
contentManagementService.favoriteLibraryToggle.next
).toHaveBeenCalled();
expect(contentManagementService.favoriteLibraryToggle.next).toHaveBeenCalled();
});
});

View File

@@ -39,20 +39,11 @@ import { Subject } from 'rxjs';
mat-menu-item
(toggle)="onToggleEvent()"
[acaFavoriteLibrary]="library"
[attr.title]="
library.isFavorite
? ('APP.ACTIONS.REMOVE_FAVORITE' | translate)
: ('APP.ACTIONS.FAVORITE' | translate)
"
[attr.title]="library.isFavorite ? ('APP.ACTIONS.REMOVE_FAVORITE' | translate) : ('APP.ACTIONS.FAVORITE' | translate)"
>
<mat-icon *ngIf="library.isFavorite">star</mat-icon>
<mat-icon *ngIf="!library.isFavorite">star_border</mat-icon>
<span>{{
(library.isFavorite
? 'APP.ACTIONS.REMOVE_FAVORITE'
: 'APP.ACTIONS.FAVORITE'
) | translate
}}</span>
<span>{{ (library.isFavorite ? 'APP.ACTIONS.REMOVE_FAVORITE' : 'APP.ACTIONS.FAVORITE') | translate }}</span>
</button>
`,
encapsulation: ViewEncapsulation.None,
@@ -62,16 +53,10 @@ export class ToggleFavoriteLibraryComponent implements OnInit, OnDestroy {
library;
private onDestroy$: Subject<boolean> = new Subject<boolean>();
constructor(
private store: Store<AppStore>,
private content: ContentManagementService,
private router: Router
) {}
constructor(private store: Store<AppStore>, private content: ContentManagementService, private router: Router) {}
ngOnInit() {
const isFavoriteLibraries = this.router.url.startsWith(
'/favorite/libraries'
);
const isFavoriteLibraries = this.router.url.startsWith('/favorite/libraries');
this.store
.select(getAppSelection)

View File

@@ -51,17 +51,9 @@ describe('ToggleFavoriteComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
CoreModule.forRoot(),
AppTestingModule
],
imports: [TranslateModule.forRoot(), CoreModule.forRoot(), AppTestingModule],
declarations: [ToggleFavoriteComponent],
providers: [
ExtensionService,
{ provide: Store, useValue: mockStore },
{ provide: Router, useValue: mockRouter }
]
providers: [ExtensionService, { provide: Store, useValue: mockStore }, { provide: Router, useValue: mockRouter }]
});
fixture = TestBed.createComponent(ToggleFavoriteComponent);

View File

@@ -27,30 +27,16 @@ import { Component, ViewEncapsulation, OnInit, Input } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { SelectionState } from '@alfresco/adf-extensions';
import {
AppStore,
ReloadDocumentListAction,
getAppSelection
} from '@alfresco/aca-shared/store';
import { AppStore, ReloadDocumentListAction, getAppSelection } from '@alfresco/aca-shared/store';
import { Router } from '@angular/router';
@Component({
selector: 'app-toggle-favorite',
template: `
<button
mat-menu-item
#favorites="adfFavorite"
(toggle)="onToggleEvent()"
[adf-node-favorite]="(selection$ | async).nodes"
>
<button mat-menu-item #favorites="adfFavorite" (toggle)="onToggleEvent()" [adf-node-favorite]="(selection$ | async).nodes">
<mat-icon *ngIf="favorites.hasFavorites()">star</mat-icon>
<mat-icon *ngIf="!favorites.hasFavorites()">star_border</mat-icon>
<span>{{
(favorites.hasFavorites()
? 'APP.ACTIONS.REMOVE_FAVORITE'
: 'APP.ACTIONS.FAVORITE'
) | translate
}}</span>
<span>{{ (favorites.hasFavorites() ? 'APP.ACTIONS.REMOVE_FAVORITE' : 'APP.ACTIONS.FAVORITE') | translate }}</span>
</button>
`,
encapsulation: ViewEncapsulation.None,

View File

@@ -26,10 +26,7 @@
import { Component, ViewEncapsulation } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import {
ToggleInfoDrawerAction,
isInfoDrawerOpened
} from '@alfresco/aca-shared/store';
import { ToggleInfoDrawerAction, isInfoDrawerOpened } from '@alfresco/aca-shared/store';
@Component({
selector: 'app-toggle-info-drawer',

View File

@@ -23,21 +23,12 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import {
AppStore,
SetSelectedNodesAction,
SnackbarErrorAction,
SnackbarInfoAction,
getAppSelection
} from '@alfresco/aca-shared/store';
import { AppStore, SetSelectedNodesAction, SnackbarErrorAction, SnackbarInfoAction, getAppSelection } from '@alfresco/aca-shared/store';
import { SelectionState } from '@alfresco/adf-extensions';
import { Component, ViewEncapsulation } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import {
LibraryMembershipErrorEvent,
LibraryMembershipToggleEvent
} from '../../../directives/library-membership.directive';
import { LibraryMembershipErrorEvent, LibraryMembershipToggleEvent } from '../../../directives/library-membership.directive';
import { ContentManagementService } from '../../../services/content-management.service';
@Component({
@@ -50,17 +41,10 @@ import { ContentManagementService } from '../../../services/content-management.s
(toggle)="onToggleEvent($event)"
(error)="onErrorEvent($event)"
[acaLibraryMembership]="(selection$ | async).library"
[attr.title]="
(membership.isJoinRequested | async)
? ('APP.ACTIONS.CANCEL_JOIN' | translate)
: ('APP.ACTIONS.JOIN' | translate)
"
[attr.title]="(membership.isJoinRequested | async) ? ('APP.ACTIONS.CANCEL_JOIN' | translate) : ('APP.ACTIONS.JOIN' | translate)"
>
<mat-icon *ngIf="membership.isJoinRequested | async">cancel</mat-icon>
<mat-icon
*ngIf="!(membership.isJoinRequested | async)"
svgIcon="adf:join_library"
></mat-icon>
<mat-icon *ngIf="!(membership.isJoinRequested | async)" svgIcon="adf:join_library"></mat-icon>
</button>
`,
encapsulation: ViewEncapsulation.None,
@@ -69,10 +53,7 @@ import { ContentManagementService } from '../../../services/content-management.s
export class ToggleJoinLibraryButtonComponent {
selection$: Observable<SelectionState>;
constructor(
private store: Store<AppStore>,
private content: ContentManagementService
) {
constructor(private store: Store<AppStore>, private content: ContentManagementService) {
this.selection$ = this.store.select(getAppSelection);
}
@@ -83,11 +64,7 @@ export class ToggleJoinLibraryButtonComponent {
this.content.libraryJoined.next();
} else {
if (event.updatedEntry) {
this.store.dispatch(
new SetSelectedNodesAction([
{ entry: event.updatedEntry, isLibrary: true } as any
])
);
this.store.dispatch(new SetSelectedNodesAction([{ entry: event.updatedEntry, isLibrary: true } as any]));
}
this.content.joinLibraryToggle.next();
}

View File

@@ -38,22 +38,11 @@ import { ToggleJoinLibraryButtonComponent } from './toggle-join-library-button.c
(toggle)="onToggleEvent($event)"
(error)="onErrorEvent($event)"
[acaLibraryMembership]="(selection$ | async).library"
[attr.title]="
(membership.isJoinRequested | async)
? ('APP.ACTIONS.CANCEL_JOIN' | translate)
: ('APP.ACTIONS.JOIN' | translate)
"
[attr.title]="(membership.isJoinRequested | async) ? ('APP.ACTIONS.CANCEL_JOIN' | translate) : ('APP.ACTIONS.JOIN' | translate)"
>
<mat-icon *ngIf="membership.isJoinRequested | async">cancel</mat-icon>
<mat-icon
*ngIf="!(membership.isJoinRequested | async)"
svgIcon="adf:join_library"
></mat-icon>
<span>{{
(membership.isJoinRequested | async)
? ('APP.ACTIONS.CANCEL_JOIN' | translate)
: ('APP.ACTIONS.JOIN' | translate)
}}</span>
<mat-icon *ngIf="!(membership.isJoinRequested | async)" svgIcon="adf:join_library"></mat-icon>
<span>{{ (membership.isJoinRequested | async) ? ('APP.ACTIONS.CANCEL_JOIN' | translate) : ('APP.ACTIONS.JOIN' | translate) }}</span>
</button>
`,
encapsulation: ViewEncapsulation.None,

Some files were not shown because too many files have changed in this diff Show More