From 51b9b5862397088b0ffc7fecf137d1a291af9848 Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Mon, 5 Feb 2024 11:02:10 +0100 Subject: [PATCH 01/10] [ACA-4728] fix file order in viewer --- .../lib/components/preview.component.spec.ts | 26 ++- .../src/lib/components/preview.component.ts | 6 +- .../lib/components/files/files.component.ts | 30 ++- .../viewer/viewer.component.spec.ts | 196 ++++++++++++++++-- .../lib/components/viewer/viewer.component.ts | 7 +- 5 files changed, 231 insertions(+), 34 deletions(-) diff --git a/projects/aca-content/preview/src/lib/components/preview.component.spec.ts b/projects/aca-content/preview/src/lib/components/preview.component.spec.ts index 2a8b6447ef..fd41746425 100644 --- a/projects/aca-content/preview/src/lib/components/preview.component.spec.ts +++ b/projects/aca-content/preview/src/lib/components/preview.component.spec.ts @@ -468,8 +468,7 @@ describe('PreviewComponent', () => { }); it('should fetch and sort file ids for personal-files', async () => { - preferences.set('personal-files.sorting.key', 'name'); - preferences.set('personal-files.sorting.direction', 'desc'); + spyOn(preferences, 'get').and.returnValues('name', 'desc', 'client'); spyOn(contentApi, 'getNodeChildren').and.returnValue( of({ @@ -484,8 +483,7 @@ describe('PreviewComponent', () => { }); it('should fetch file ids for personal-files with default sorting for missing key', async () => { - preferences.set('personal-files.sorting.key', 'missing'); - preferences.set('personal-files.sorting.direction', 'desc'); + spyOn(preferences, 'get').and.returnValues('missing', 'desc', 'client'); spyOn(contentApi, 'getNodeChildren').and.returnValue( of({ @@ -500,7 +498,7 @@ describe('PreviewComponent', () => { }); it('should sort file ids for personal-files with [modifiedAt desc]', async () => { - spyOn(preferences, 'get').and.returnValue(null); + spyOn(preferences, 'get').and.returnValues(null, null, 'client'); spyOn(contentApi, 'getNodeChildren').and.returnValue( of({ @@ -752,6 +750,24 @@ describe('PreviewComponent', () => { expect(component.navigateToFileLocation).toHaveBeenCalled(); }); + it('should not sort personal files when server-side sorting is set', async () => { + spyOn(preferences, 'get').and.returnValues('name', 'desc', 'server'); + + spyOn(contentApi, 'getNodeChildren').and.returnValue( + of({ + list: { + entries: [ + { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } }, + { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } } + ] + } + } as NodePaging) + ); + + const ids = await component.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node1', 'node2']); + }); + describe('Keyboard navigation', () => { beforeEach(() => { component.nextNodeId = 'nextNodeId'; diff --git a/projects/aca-content/preview/src/lib/components/preview.component.ts b/projects/aca-content/preview/src/lib/components/preview.component.ts index fc7cf7d0b8..f345db7bfe 100644 --- a/projects/aca-content/preview/src/lib/components/preview.component.ts +++ b/projects/aca-content/preview/src/lib/components/preview.component.ts @@ -317,14 +317,16 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy const sortDirection = this.preferences.get('personal-files.sorting.direction') || 'desc'; const nodes = await this.contentApi .getNodeChildren(folderId, { - // orderBy: `${sortKey} ${sortDirection}`, + orderBy: ['isFolder desc', `${sortKey} ${sortDirection}`], fields: ['id', this.getRootField(sortKey)], where: '(isFile=true)' }) .toPromise(); const entries = nodes.list.entries.map((obj) => obj.entry); - this.sort(entries, sortKey, sortDirection); + if (this.preferences.get('filesPageSortingMode') === 'client' || source === 'libraries') { + this.sort(entries, sortKey, sortDirection); + } return entries.map((obj) => obj.id); } diff --git a/projects/aca-content/src/lib/components/files/files.component.ts b/projects/aca-content/src/lib/components/files/files.component.ts index f07c198970..1733904ee3 100644 --- a/projects/aca-content/src/lib/components/files/files.component.ts +++ b/projects/aca-content/src/lib/components/files/files.component.ts @@ -22,8 +22,8 @@ * from Hyland Software. If not, see . */ -import { DataTableModule, PaginationComponent, ShowHeaderMode } from '@alfresco/adf-core'; -import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; +import { DataTableModule, PaginationComponent, ShowHeaderMode, UserPreferencesService } from '@alfresco/adf-core'; +import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { NodeEntry, Node, PathElement } from '@alfresco/js-api'; import { NodeActionsService } from '../../services/node-actions.service'; @@ -39,7 +39,15 @@ import { } from '@alfresco/aca-shared'; import { SetCurrentFolderAction, isAdmin, UploadFileVersionAction, showLoaderSelector } from '@alfresco/aca-shared/store'; import { debounceTime, takeUntil } from 'rxjs/operators'; -import { FilterSearch, ShareDataRow, FileUploadEvent, BreadcrumbModule, UploadModule, DocumentListModule } from '@alfresco/adf-content-services'; +import { + BreadcrumbModule, + DocumentListComponent, + DocumentListModule, + FilterSearch, + FileUploadEvent, + UploadModule, + ShareDataRow +} from '@alfresco/adf-content-services'; import { DocumentListPresetRef, ExtensionsModule } from '@alfresco/adf-extensions'; import { CommonModule } from '@angular/common'; import { TranslateModule } from '@ngx-translate/core'; @@ -69,7 +77,7 @@ import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; templateUrl: './files.component.html', encapsulation: ViewEncapsulation.None }) -export class FilesComponent extends PageComponent implements OnInit, OnDestroy { +export class FilesComponent extends PageComponent implements OnInit, OnDestroy, AfterViewInit { isValidPath = true; isAdmin = false; selectedNode: NodeEntry; @@ -81,7 +89,15 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy { columns: DocumentListPresetRef[] = []; isFilterHeaderActive = false; - constructor(private route: ActivatedRoute, private contentApi: ContentApiService, private nodeActionsService: NodeActionsService) { + @ViewChild('documentList', { static: true }) + documentList: DocumentListComponent; + + constructor( + private route: ActivatedRoute, + private contentApi: ContentApiService, + private nodeActionsService: NodeActionsService, + private preferences: UserPreferencesService + ) { super(); } @@ -136,6 +152,10 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy { } } + ngAfterViewInit() { + this.preferences.set('filesPageSortingMode', this.documentList.sortingMode); + } + ngOnDestroy() { this.store.dispatch(new SetCurrentFolderAction(null)); super.ngOnDestroy(); diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts index 2d5d644960..c35f55264d 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts @@ -22,41 +22,199 @@ * from Hyland Software. If not, see . */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { AcaViewerComponent } from '@alfresco/aca-content/viewer'; -import { NodesApiService } from '@alfresco/adf-content-services'; -import { RefreshPreviewAction } from '@alfresco/aca-shared/store'; -import { Node } from '@alfresco/js-api'; -import { EMPTY } from 'rxjs'; -import { CoreTestingModule } from '@alfresco/adf-core'; +import { TestBed, ComponentFixture } from '@angular/core/testing'; +import { + UserPreferencesService, + AlfrescoApiService, + AlfrescoApiServiceMock, + AuthenticationService, + TranslationMock, + TranslationService, + PipeModule +} from '@alfresco/adf-core'; +import { DiscoveryApiService, NodesApiService } from '@alfresco/adf-content-services'; +import { AppState, RefreshPreviewAction } from '@alfresco/aca-shared/store'; +import { AcaViewerComponent } from './viewer.component'; +import { BehaviorSubject, Observable, of } from 'rxjs'; +import { ContentApiService, DocumentBasePageService } from '@alfresco/aca-shared'; import { Store, StoreModule } from '@ngrx/store'; +import { NodePaging, RepositoryInfo, VersionInfo, Node } from '@alfresco/js-api'; +import { AcaViewerModule } from '../../viewer.module'; +import { TranslateModule } from '@ngx-translate/core'; +import { RouterTestingModule } from '@angular/router/testing'; +import { HttpClientModule } from '@angular/common/http'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; +import { EffectsModule } from '@ngrx/effects'; -describe('AcaViewerComponent', () => { +class DocumentBasePageServiceMock extends DocumentBasePageService { + canUpdateNode(): boolean { + return true; + } + canUploadContent(): boolean { + return true; + } +} + +export const INITIAL_APP_STATE: AppState = { + appName: 'Alfresco Content Application', + logoPath: 'assets/images/alfresco-logo-white.svg', + customCssPath: '', + webFontPath: '', + sharedUrl: '', + user: { + isAdmin: null, + id: null, + firstName: '', + lastName: '' + }, + selection: { + nodes: [], + libraries: [], + isEmpty: true, + count: 0 + }, + navigation: { + currentFolder: null + }, + currentNodeVersion: null, + infoDrawerOpened: false, + infoDrawerPreview: false, + infoDrawerMetadataAspect: '', + showFacetFilter: true, + fileUploadingDialog: true, + showLoader: false, + repository: { + status: { + isQuickShareEnabled: true + } + } as any +}; + +describe('ViewerComponent', () => { let fixture: ComponentFixture; let component: AcaViewerComponent; + let preferences: UserPreferencesService; + let contentApi: ContentApiService; let nodesApiService: NodesApiService; let store: Store; beforeEach(() => { TestBed.configureTestingModule({ - imports: [CoreTestingModule, StoreModule.forRoot({})] + imports: [ + AcaViewerModule, + NoopAnimationsModule, + HttpClientModule, + RouterTestingModule, + TranslateModule.forRoot(), + StoreModule.forRoot( + { app: (state) => state }, + { + initialState: { + app: INITIAL_APP_STATE + }, + runtimeChecks: { + strictStateImmutability: false, + strictActionImmutability: false + } + } + ), + EffectsModule.forRoot([]), + PipeModule + ], + providers: [ + { provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }, + { provide: TranslationService, useClass: TranslationMock }, + { provide: DocumentBasePageService, useVale: new DocumentBasePageServiceMock() }, + { + provide: DiscoveryApiService, + useValue: { + ecmProductInfo$: new BehaviorSubject(null), + getEcmProductInfo: (): Observable => + of( + new RepositoryInfo({ + version: { + major: '10.0.0' + } as VersionInfo + }) + ) + } + }, + { + provide: AuthenticationService, + useValue: { + isEcmLoggedIn: (): boolean => true, + getRedirect: (): string | null => null, + setRedirect() {}, + isOauth: (): boolean => false, + isOAuthWithoutSilentLogin: (): boolean => false + } + } + ] }); - store = TestBed.inject(Store); - spyOn(store, 'select').and.returnValue(EMPTY); fixture = TestBed.createComponent(AcaViewerComponent); component = fixture.componentInstance; + + preferences = TestBed.inject(UserPreferencesService); + contentApi = TestBed.inject(ContentApiService); nodesApiService = TestBed.inject(NodesApiService); + store = TestBed.inject(Store); }); - describe('Load content', () => { - it('should call node update after RefreshPreviewAction is triggered', () => { - spyOn(nodesApiService.nodeUpdated, 'next'); - component.ngOnInit(); - const node = new Node(); + it('should fetch and sort file ids for personal-files', async () => { + spyOn(preferences, 'get').and.returnValues('name', 'desc', 'client'); - store.dispatch(new RefreshPreviewAction(node)); - expect(nodesApiService.nodeUpdated.next).toHaveBeenCalledWith(node); - }); + spyOn(contentApi, 'getNodeChildren').and.returnValue( + of({ + list: { + entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }] + } + } as NodePaging) + ); + + const ids = await component.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node2', 'node1']); + }); + + it('should fetch file ids for personal-files with default sorting for missing key', async () => { + spyOn(preferences, 'get').and.returnValues('missing', 'desc', 'client'); + + spyOn(contentApi, 'getNodeChildren').and.returnValue( + of({ + list: { + entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }] + } + } as NodePaging) + ); + + const ids = await component.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node1', 'node2']); + }); + + it('should not sort personal files when server-side sorting is set', async () => { + spyOn(preferences, 'get').and.returnValues('name', 'desc', 'server'); + + spyOn(contentApi, 'getNodeChildren').and.returnValue( + of({ + list: { + entries: [ + { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } }, + { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } } + ] + } + } as NodePaging) + ); + + const ids = await component.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node1', 'node2']); + }); + + it('should call node update after RefreshPreviewAction is triggered', () => { + spyOn(nodesApiService.nodeUpdated, 'next'); + component.ngOnInit(); + const node = new Node(); + + store.dispatch(new RefreshPreviewAction(node)); + expect(nodesApiService.nodeUpdated.next).toHaveBeenCalledWith(node); }); }); diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts index 373726d2a5..0de6680c0a 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts @@ -323,14 +323,15 @@ export class AcaViewerComponent implements OnInit, OnDestroy { const sortDirection = this.preferences.get('personal-files.sorting.direction') || 'desc'; const nodes = await this.contentApi .getNodeChildren(folderId, { - // orderBy: `${sortKey} ${sortDirection}`, + orderBy: ['isFolder desc', `${sortKey} ${sortDirection}`], fields: ['id', this.getRootField(sortKey)], where: '(isFile=true)' }) .toPromise(); - const entries = nodes.list.entries.map((obj) => obj.entry); - this.sort(entries, sortKey, sortDirection); + if (this.preferences.get('filesPageSortingMode') === 'client' || source === 'libraries') { + this.sort(entries, sortKey, sortDirection); + } return entries.map((obj) => obj.id); } From 508e6a2ddab1568eecabe8effa94c6de5df4a14f Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Thu, 14 Mar 2024 11:45:37 +0100 Subject: [PATCH 02/10] [ACA-4728] refactor viewer and preview, save and restore previous sorting in viewer and document pages when client sorting, add viewer unit tests --- projects/aca-content/preview/ng-package.json | 5 - .../preview/src/lib/preview.module.ts | 32 -- .../aca-content/preview/src/public-api.ts | 30 -- projects/aca-content/preview/src/test.ts | 49 --- .../aca-content/src/lib/aca-content.module.ts | 2 +- .../favorite-libraries.component.html | 2 + .../favorites/favorites.component.html | 2 + .../lib/components/files/files.component.html | 3 +- .../lib/components/files/files.component.ts | 41 +- .../libraries/libraries.component.html | 2 + .../recent-files/recent-files.component.html | 2 + .../shared-files/shared-files.component.html | 2 + .../trashcan/trashcan.component.html | 2 + .../lib/directives/document-list.directive.ts | 50 ++- .../preview}/preview.component.html | 0 .../preview}/preview.component.scss | 0 .../preview}/preview.component.spec.ts | 377 ++---------------- .../components/preview}/preview.component.ts | 228 +---------- .../viewer/viewer.component.spec.ts | 251 +++++++++--- .../lib/components/viewer/viewer.component.ts | 234 ++--------- .../src/lib/services/viewer.service.spec.ts | 222 +++++++++++ .../viewer/src/lib/services/viewer.service.ts | 266 ++++++++++++ .../viewer/src/lib/viewer.module.ts | 5 +- projects/aca-content/viewer/src/public-api.ts | 1 + .../document-base-page.component.ts | 3 +- 25 files changed, 840 insertions(+), 971 deletions(-) delete mode 100644 projects/aca-content/preview/ng-package.json delete mode 100644 projects/aca-content/preview/src/lib/preview.module.ts delete mode 100644 projects/aca-content/preview/src/public-api.ts delete mode 100644 projects/aca-content/preview/src/test.ts rename projects/aca-content/{preview/src/lib/components => viewer/src/lib/components/preview}/preview.component.html (100%) rename projects/aca-content/{preview/src/lib/components => viewer/src/lib/components/preview}/preview.component.scss (100%) rename projects/aca-content/{preview/src/lib/components => viewer/src/lib/components/preview}/preview.component.spec.ts (60%) rename projects/aca-content/{preview/src/lib/components => viewer/src/lib/components/preview}/preview.component.ts (55%) create mode 100644 projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts create mode 100644 projects/aca-content/viewer/src/lib/services/viewer.service.ts diff --git a/projects/aca-content/preview/ng-package.json b/projects/aca-content/preview/ng-package.json deleted file mode 100644 index fbafcc4448..0000000000 --- a/projects/aca-content/preview/ng-package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "lib": { - "entryFile": "src/public-api.ts" - } -} diff --git a/projects/aca-content/preview/src/lib/preview.module.ts b/projects/aca-content/preview/src/lib/preview.module.ts deleted file mode 100644 index 73d49d48de..0000000000 --- a/projects/aca-content/preview/src/lib/preview.module.ts +++ /dev/null @@ -1,32 +0,0 @@ -/*! - * Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved. - * - * Alfresco Example Content Application - * - * This file is part of the Alfresco Example Content Application. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * The Alfresco Example Content Application is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * The Alfresco Example Content Application is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * from Hyland Software. If not, see . - */ - -import { NgModule } from '@angular/core'; -import { PreviewComponent } from './components/preview.component'; - -@NgModule({ - imports: [PreviewComponent], - exports: [PreviewComponent] -}) -export class PreviewModule {} diff --git a/projects/aca-content/preview/src/public-api.ts b/projects/aca-content/preview/src/public-api.ts deleted file mode 100644 index 3bde405133..0000000000 --- a/projects/aca-content/preview/src/public-api.ts +++ /dev/null @@ -1,30 +0,0 @@ -/*! - * Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved. - * - * Alfresco Example Content Application - * - * This file is part of the Alfresco Example Content Application. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * The Alfresco Example Content Application is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * The Alfresco Example Content Application is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * from Hyland Software. If not, see . - */ - -/* - * Public API Surface of aca-preview - */ - -export * from './lib/components/preview.component'; -export * from './lib/preview.module'; diff --git a/projects/aca-content/preview/src/test.ts b/projects/aca-content/preview/src/test.ts deleted file mode 100644 index f47f30d432..0000000000 --- a/projects/aca-content/preview/src/test.ts +++ /dev/null @@ -1,49 +0,0 @@ -/*! - * Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved. - * - * Alfresco Example Content Application - * - * This file is part of the Alfresco Example Content Application. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * The Alfresco Example Content Application is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * The Alfresco Example Content Application is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * from Hyland Software. If not, see . - */ - -// This file is required by karma.conf.js and loads recursively all the .spec and framework files - -import 'zone.js'; -import 'zone.js/testing'; -import { getTestBed } from '@angular/core/testing'; -import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; - -declare const require: { - context( - path: string, - deep?: boolean, - filter?: RegExp - ): { - (id: string): T; - keys(): string[]; - }; -}; - -// First, initialize the Angular testing environment. -getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); - -// Then we find all the tests. -const context = require.context('./', true, /\.spec\.ts$/); -// And load the modules. -context.keys().forEach(context); diff --git a/projects/aca-content/src/lib/aca-content.module.ts b/projects/aca-content/src/lib/aca-content.module.ts index 3345fdf871..346738866d 100644 --- a/projects/aca-content/src/lib/aca-content.module.ts +++ b/projects/aca-content/src/lib/aca-content.module.ts @@ -63,7 +63,7 @@ import { CommentsTabComponent } from './components/info-drawer/comments-tab/comm import { LibraryMetadataTabComponent } from './components/info-drawer/library-metadata-tab/library-metadata-tab.component'; import { MetadataTabComponent } from './components/info-drawer/metadata-tab/metadata-tab.component'; import { VersionsTabComponent } from './components/info-drawer/versions-tab/versions-tab.component'; -import { PreviewComponent } from '@alfresco/aca-content/preview'; +import { PreviewComponent } from '@alfresco/aca-content/viewer'; import { ToggleEditOfflineComponent } from './components/toolbar/toggle-edit-offline/toggle-edit-offline.component'; import { ToggleFavoriteLibraryComponent } from './components/toolbar/toggle-favorite-library/toggle-favorite-library.component'; import { ToggleFavoriteComponent } from './components/toolbar/toggle-favorite/toggle-favorite.component'; diff --git a/projects/aca-content/src/lib/components/favorite-libraries/favorite-libraries.component.html b/projects/aca-content/src/lib/components/favorite-libraries/favorite-libraries.component.html index cd89b7fed9..a5145fe998 100644 --- a/projects/aca-content/src/lib/components/favorite-libraries/favorite-libraries.component.html +++ b/projects/aca-content/src/lib/components/favorite-libraries/favorite-libraries.component.html @@ -45,6 +45,7 @@

{{ 'APP.BROWSE.LIBRARIES.MENU.FAVORITE_LIBRARIES.TITL [class]="column.class" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > @@ -64,6 +65,7 @@

{{ 'APP.BROWSE.LIBRARIES.MENU.FAVORITE_LIBRARIES.TITL [class]="column.class" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > diff --git a/projects/aca-content/src/lib/components/favorites/favorites.component.html b/projects/aca-content/src/lib/components/favorites/favorites.component.html index 7a48f7507a..12530b4239 100644 --- a/projects/aca-content/src/lib/components/favorites/favorites.component.html +++ b/projects/aca-content/src/lib/components/favorites/favorites.component.html @@ -40,6 +40,7 @@

{{ 'APP.BROWSE.FAVORITES.TITLE' | translate }}

[class]="column.class" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > @@ -59,6 +60,7 @@

{{ 'APP.BROWSE.FAVORITES.TITLE' | translate }}

[class]="column.class" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > diff --git a/projects/aca-content/src/lib/components/files/files.component.html b/projects/aca-content/src/lib/components/files/files.component.html index a5e10cbcc5..bcee7562e2 100644 --- a/projects/aca-content/src/lib/components/files/files.component.html +++ b/projects/aca-content/src/lib/components/files/files.component.html @@ -23,7 +23,7 @@ [node]="nodeResult" [allowDropFiles]="true" [navigate]="false" - [sorting]="['name', 'ASC']" + [sorting]="['name', 'asc']" [imageResolver]="imageResolver" [headerFilters]="true" [filterValue]="queryParams" @@ -31,7 +31,6 @@ [blurOnResize]="false" (node-dblclick)="handleNodeClick($event)" (name-click)="handleNodeClick($event)" - (sorting-changed)="onSortingChanged($event)" (filterSelection)="onFilterSelected($event)" (error)="onError()" > diff --git a/projects/aca-content/src/lib/components/files/files.component.ts b/projects/aca-content/src/lib/components/files/files.component.ts index 1733904ee3..e4e083183a 100644 --- a/projects/aca-content/src/lib/components/files/files.component.ts +++ b/projects/aca-content/src/lib/components/files/files.component.ts @@ -22,8 +22,8 @@ * from Hyland Software. If not, see . */ -import { DataTableModule, PaginationComponent, ShowHeaderMode, UserPreferencesService } from '@alfresco/adf-core'; -import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; +import { DataTableModule, PaginationComponent, ShowHeaderMode } from '@alfresco/adf-core'; +import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { NodeEntry, Node, PathElement } from '@alfresco/js-api'; import { NodeActionsService } from '../../services/node-actions.service'; @@ -39,15 +39,7 @@ import { } from '@alfresco/aca-shared'; import { SetCurrentFolderAction, isAdmin, UploadFileVersionAction, showLoaderSelector } from '@alfresco/aca-shared/store'; import { debounceTime, takeUntil } from 'rxjs/operators'; -import { - BreadcrumbModule, - DocumentListComponent, - DocumentListModule, - FilterSearch, - FileUploadEvent, - UploadModule, - ShareDataRow -} from '@alfresco/adf-content-services'; +import { BreadcrumbModule, DocumentListModule, FileUploadEvent, FilterSearch, ShareDataRow, UploadModule } from '@alfresco/adf-content-services'; import { DocumentListPresetRef, ExtensionsModule } from '@alfresco/adf-extensions'; import { CommonModule } from '@angular/common'; import { TranslateModule } from '@ngx-translate/core'; @@ -77,27 +69,18 @@ import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; templateUrl: './files.component.html', encapsulation: ViewEncapsulation.None }) -export class FilesComponent extends PageComponent implements OnInit, OnDestroy, AfterViewInit { +export class FilesComponent extends PageComponent implements OnInit, OnDestroy { isValidPath = true; isAdmin = false; selectedNode: NodeEntry; queryParams = null; - showLoader$ = this.store.select(showLoaderSelector); private nodePath: PathElement[]; columns: DocumentListPresetRef[] = []; isFilterHeaderActive = false; - @ViewChild('documentList', { static: true }) - documentList: DocumentListComponent; - - constructor( - private route: ActivatedRoute, - private contentApi: ContentApiService, - private nodeActionsService: NodeActionsService, - private preferences: UserPreferencesService - ) { + constructor(private contentApi: ContentApiService, private nodeActionsService: NodeActionsService, private route: ActivatedRoute) { super(); } @@ -119,9 +102,9 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy, this.isValidPath = true; if (node?.entry?.isFolder) { - this.updateCurrentNode(node.entry); + void this.updateCurrentNode(node.entry); } else { - this.router.navigate(['/personal-files', node.entry.parentId], { + void this.router.navigate(['/personal-files', node.entry.parentId], { replaceUrl: true }); } @@ -152,10 +135,6 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy, } } - ngAfterViewInit() { - this.preferences.set('filesPageSortingMode', this.documentList.sortingMode); - } - ngOnDestroy() { this.store.dispatch(new SetCurrentFolderAction(null)); super.ngOnDestroy(); @@ -165,7 +144,7 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy, const currentNodeId = this.route.snapshot.paramMap.get('folderId'); const urlWithoutParams = decodeURIComponent(this.router.url).split('?')[0]; const urlToNavigate: string[] = this.getUrlToNavigate(urlWithoutParams, currentNodeId, nodeId); - this.router.navigate(urlToNavigate); + void this.router.navigate(urlToNavigate); } private getUrlToNavigate(currentURL: string, currentNodeId: string, nextNodeId: string): string[] { @@ -370,7 +349,7 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy, this.isFilterHeaderActive = true; this.navigateToFilter(activeFilters); } else { - this.router.navigate(['.'], { relativeTo: this.route }); + void this.router.navigate(['.'], { relativeTo: this.route }); this.isFilterHeaderActive = false; this.showHeader = ShowHeaderMode.Data; this.onAllFilterCleared(); @@ -389,7 +368,7 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy, objectFromMap[filter.key] = paramValue; }); - this.router.navigate([], { relativeTo: this.route, queryParams: objectFromMap }); + void this.router.navigate([], { relativeTo: this.route, queryParams: objectFromMap }); } onError() { diff --git a/projects/aca-content/src/lib/components/libraries/libraries.component.html b/projects/aca-content/src/lib/components/libraries/libraries.component.html index 8c2f6ffcaf..7621c605a1 100644 --- a/projects/aca-content/src/lib/components/libraries/libraries.component.html +++ b/projects/aca-content/src/lib/components/libraries/libraries.component.html @@ -44,6 +44,7 @@

{{ 'APP.BROWSE.LIBRARIES.MENU.MY_LIBRARIES.TITLE' | t [class]="column.class" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > @@ -63,6 +64,7 @@

{{ 'APP.BROWSE.LIBRARIES.MENU.MY_LIBRARIES.TITLE' | t [resizable]="column.resizable" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > diff --git a/projects/aca-content/src/lib/components/recent-files/recent-files.component.html b/projects/aca-content/src/lib/components/recent-files/recent-files.component.html index 36117a33e7..85ca8aa7ed 100644 --- a/projects/aca-content/src/lib/components/recent-files/recent-files.component.html +++ b/projects/aca-content/src/lib/components/recent-files/recent-files.component.html @@ -40,6 +40,7 @@

{{ 'APP.BROWSE.RECENT.TITLE' | translate }}

[draggable]="column.draggable" [resizable]="column.resizable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > @@ -59,6 +60,7 @@

{{ 'APP.BROWSE.RECENT.TITLE' | translate }}

[isHidden]="column.isHidden" [draggable]="column.draggable" [resizable]="column.resizable" + [sortingKey]="column.sortingKey || column.key" > diff --git a/projects/aca-content/src/lib/components/shared-files/shared-files.component.html b/projects/aca-content/src/lib/components/shared-files/shared-files.component.html index 9b6c182efd..5eb363f3fb 100644 --- a/projects/aca-content/src/lib/components/shared-files/shared-files.component.html +++ b/projects/aca-content/src/lib/components/shared-files/shared-files.component.html @@ -39,6 +39,7 @@

{{ 'APP.BROWSE.SHARED.TITLE' | translate }}

[isHidden]="column.isHidden" [draggable]="column.draggable" [resizable]="column.resizable" + [sortingKey]="column.sortingKey || column.key" > @@ -58,6 +59,7 @@

{{ 'APP.BROWSE.SHARED.TITLE' | translate }}

[class]="column.class" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > diff --git a/projects/aca-content/src/lib/components/trashcan/trashcan.component.html b/projects/aca-content/src/lib/components/trashcan/trashcan.component.html index bc263a8ca6..db1c41b173 100644 --- a/projects/aca-content/src/lib/components/trashcan/trashcan.component.html +++ b/projects/aca-content/src/lib/components/trashcan/trashcan.component.html @@ -45,6 +45,7 @@

{{ 'APP.BROWSE.TRASHCAN.TITLE' | translate }}

[class]="column.class" [sortable]="column.sortable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > @@ -64,6 +65,7 @@

{{ 'APP.BROWSE.TRASHCAN.TITLE' | translate }}

[draggable]="column.draggable" [resizable]="column.resizable" [isHidden]="column.isHidden" + [sortingKey]="column.sortingKey || column.key" > diff --git a/projects/aca-content/src/lib/directives/document-list.directive.ts b/projects/aca-content/src/lib/directives/document-list.directive.ts index 63590bb1fa..3012114ce3 100644 --- a/projects/aca-content/src/lib/directives/document-list.directive.ts +++ b/projects/aca-content/src/lib/directives/document-list.directive.ts @@ -66,11 +66,6 @@ export class DocumentListDirective implements OnInit, OnDestroy { this.router.url.startsWith('/search-libraries'); if (this.sortingPreferenceKey) { - const current = this.documentList.sorting; - - const key = this.preferences.get(`${this.sortingPreferenceKey}.sorting.sortingKey`, current[0]); - const direction = this.preferences.get(`${this.sortingPreferenceKey}.sorting.direction`, current[1]); - if (this.preferences.hasItem(`${this.sortingPreferenceKey}.columns.width`)) { this.documentList.setColumnsWidths = JSON.parse(this.preferences.get(`${this.sortingPreferenceKey}.columns.width`)); } @@ -83,9 +78,12 @@ export class DocumentListDirective implements OnInit, OnDestroy { this.documentList.setColumnsOrder = JSON.parse(this.preferences.get(`${this.sortingPreferenceKey}.columns.order`)); } - this.documentList.sorting = [key, direction]; - // TODO: bug in ADF, the `sorting` binding is not updated when changed from code - this.documentList.data.setSorting({ key, direction }); + this.preferences.set(`${this.sortingPreferenceKey}.sorting.mode`, this.documentList.sortingMode); + + const current = this.documentList.sorting; + const key = this.preferences.get(`${this.sortingPreferenceKey}.sorting.key`, current[0]); + const direction = this.preferences.get(`${this.sortingPreferenceKey}.sorting.direction`, current[1]); + this.setSorting(key, direction); } this.documentList.ready @@ -112,6 +110,9 @@ export class DocumentListDirective implements OnInit, OnDestroy { @HostListener('sorting-changed', ['$event']) onSortingChanged(event: CustomEvent) { if (this.sortingPreferenceKey) { + if (this.documentList.sortingMode === 'client') { + this.storePreviousSorting(); + } this.preferences.set(`${this.sortingPreferenceKey}.sorting.key`, event.detail.key); this.preferences.set(`${this.sortingPreferenceKey}.sorting.sortingKey`, event.detail.sortingKey); this.preferences.set(`${this.sortingPreferenceKey}.sorting.direction`, event.detail.direction); @@ -154,6 +155,9 @@ export class DocumentListDirective implements OnInit, OnDestroy { onReady() { this.updateSelection(); + if (this.documentList.sortingMode === 'client' && this.preferences.hasItem(`${this.sortingPreferenceKey}.sorting.previousKey`)) { + this.restoreSorting(); + } } private updateSelection() { @@ -180,4 +184,34 @@ export class DocumentListDirective implements OnInit, OnDestroy { this.documentList.resetSelection(); this.store.dispatch(new SetSelectedNodesAction([])); } + + private setSorting(key: string, direction: string) { + this.documentList.sorting = [key, direction]; + this.documentList.data.setSorting({ key, direction }); + } + + private storePreviousSorting() { + if (this.preferences.hasItem(`${this.sortingPreferenceKey}.sorting.key`)) { + const keyToSave = this.preferences.get(`${this.sortingPreferenceKey}.sorting.key`); + + if (!keyToSave.includes(this.documentList.sorting[0])) { + const dirToSave = this.preferences.get(`${this.sortingPreferenceKey}.sorting.direction`); + this.preferences.set(`${this.sortingPreferenceKey}.sorting.previousKey`, keyToSave); + this.preferences.set(`${this.sortingPreferenceKey}.sorting.previousDirection`, dirToSave); + } + } + } + + private restoreSorting() { + const [previousKey, previousDir] = [ + this.preferences.get(`${this.sortingPreferenceKey}.sorting.previousKey`), + this.preferences.get(`${this.sortingPreferenceKey}.sorting.previousDirection`) + ]; + const [currentKey, currentDir] = Array.isArray(this.documentList.sorting) + ? this.documentList.sorting + : [this.documentList.sorting.key, this.documentList.sorting.direction]; + + this.setSorting(previousKey, previousDir); + this.setSorting(currentKey, currentDir); + } } diff --git a/projects/aca-content/preview/src/lib/components/preview.component.html b/projects/aca-content/viewer/src/lib/components/preview/preview.component.html similarity index 100% rename from projects/aca-content/preview/src/lib/components/preview.component.html rename to projects/aca-content/viewer/src/lib/components/preview/preview.component.html diff --git a/projects/aca-content/preview/src/lib/components/preview.component.scss b/projects/aca-content/viewer/src/lib/components/preview/preview.component.scss similarity index 100% rename from projects/aca-content/preview/src/lib/components/preview.component.scss rename to projects/aca-content/viewer/src/lib/components/preview/preview.component.scss diff --git a/projects/aca-content/preview/src/lib/components/preview.component.spec.ts b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts similarity index 60% rename from projects/aca-content/preview/src/lib/components/preview.component.spec.ts rename to projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts index fd41746425..cfaaf75bd9 100644 --- a/projects/aca-content/preview/src/lib/components/preview.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts @@ -25,7 +25,6 @@ import { Router, ActivatedRoute } from '@angular/router'; import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing'; import { - UserPreferencesService, AlfrescoApiService, AlfrescoApiServiceMock, AuthenticationService, @@ -39,8 +38,8 @@ import { PreviewComponent } from './preview.component'; import { BehaviorSubject, Observable, of, throwError } from 'rxjs'; import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; import { Store, StoreModule } from '@ngrx/store'; -import { Node, NodePaging, FavoritePaging, SharedLinkPaging, PersonEntry, ResultSetPaging, RepositoryInfo, VersionInfo } from '@alfresco/js-api'; -import { PreviewModule } from '../preview.module'; +import { Node, RepositoryInfo, VersionInfo } from '@alfresco/js-api'; +import { AcaViewerModule } from '../../viewer.module'; import { TranslateModule } from '@ngx-translate/core'; import { RouterTestingModule } from '@angular/router/testing'; import { HttpClientModule } from '@angular/common/http'; @@ -96,7 +95,6 @@ describe('PreviewComponent', () => { let component: PreviewComponent; let router: Router; let route: ActivatedRoute; - let preferences: UserPreferencesService; let contentApi: ContentApiService; let uploadService: UploadService; let nodesApiService: NodesApiService; @@ -106,7 +104,7 @@ describe('PreviewComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [ - PreviewModule, + AcaViewerModule, NoopAnimationsModule, HttpClientModule, RouterTestingModule, @@ -162,7 +160,6 @@ describe('PreviewComponent', () => { router = TestBed.inject(Router); route = TestBed.inject(ActivatedRoute); - preferences = TestBed.inject(UserPreferencesService); contentApi = TestBed.inject(ContentApiService); uploadService = TestBed.inject(UploadService); nodesApiService = TestBed.inject(NodesApiService); @@ -170,13 +167,6 @@ describe('PreviewComponent', () => { store = TestBed.inject(Store); }); - it('should extract the property path root', () => { - expect(component.getRootField('some.property.path')).toBe('some'); - expect(component.getRootField('some')).toBe('some'); - expect(component.getRootField('')).toBe(''); - expect(component.getRootField(null)).toBe(null); - }); - it('should navigate to previous node in sub-folder', () => { spyOn(router, 'navigate').and.stub(); const clickEvent = new MouseEvent('click'); @@ -334,38 +324,6 @@ describe('PreviewComponent', () => { expect(component.navigateMultiple).toBeFalsy(); }); - it('should fetch navigation source from route', () => { - route.snapshot.data = { - navigateSource: 'personal-files' - }; - - component.ngOnInit(); - - expect(component.navigateSource).toBe('personal-files'); - }); - - it('should fetch case-insensitive source from route', () => { - route.snapshot.data = { - navigateSource: 'PERSONAL-FILES' - }; - - component.navigationSources = ['personal-files']; - component.ngOnInit(); - - expect(component.navigateSource).toBe('PERSONAL-FILES'); - }); - - it('should fetch only permitted navigation source from route', () => { - route.snapshot.data = { - navigateSource: 'personal-files' - }; - - component.navigationSources = ['shared']; - component.ngOnInit(); - - expect(component.navigateSource).toBeNull(); - }); - it('should display document upon init', () => { route.params = of({ folderId: 'folder1', @@ -380,46 +338,6 @@ describe('PreviewComponent', () => { expect(component.displayNode).toHaveBeenCalledWith('node1'); }); - it('should return empty nearest nodes for missing node id', async () => { - const nearest = await component.getNearestNodes(null, 'folder1'); - - expect(nearest).toEqual({ left: null, right: null }); - }); - - it('should return empty nearest nodes for missing folder id', async () => { - const nearest = await component.getNearestNodes('node1', null); - - expect(nearest).toEqual({ left: null, right: null }); - }); - - it('should return empty nearest nodes for crashed fields id request', async () => { - spyOn(component, 'getFileIds').and.returnValue(Promise.reject(new Error('err'))); - - const nearest = await component.getNearestNodes('node1', 'folder1'); - - expect(nearest).toEqual({ left: null, right: null }); - }); - - it('should return nearest nodes', async () => { - 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' }); - - nearest = await component.getNearestNodes('node3', 'folder1'); - expect(nearest).toEqual({ left: 'node2', right: 'node4' }); - - nearest = await component.getNearestNodes('node5', 'folder1'); - expect(nearest).toEqual({ left: 'node4', right: null }); - }); - - it('should return empty nearest nodes if node is already deleted', async () => { - 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 }); - }); - it('should not display node when id is missing', async () => { spyOn(router, 'navigate').and.stub(); spyOn(contentApi, 'getNodeInfo').and.returnValue(of(null)); @@ -467,254 +385,6 @@ describe('PreviewComponent', () => { expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1']); }); - it('should fetch and sort file ids for personal-files', async () => { - spyOn(preferences, 'get').and.returnValues('name', 'desc', 'client'); - - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }] - } - } as NodePaging) - ); - - const ids = await component.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node2', 'node1']); - }); - - it('should fetch file ids for personal-files with default sorting for missing key', async () => { - spyOn(preferences, 'get').and.returnValues('missing', 'desc', 'client'); - - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }] - } - } as NodePaging) - ); - - const ids = await component.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node1', 'node2']); - }); - - it('should sort file ids for personal-files with [modifiedAt desc]', async () => { - spyOn(preferences, 'get').and.returnValues(null, null, 'client'); - - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [ - { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } }, - { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } } - ] - } - } as NodePaging) - ); - - const ids = await component.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node2', 'node1']); - }); - - it('should fetch and sort file ids for libraries', async () => { - preferences.set('personal-files.sorting.key', 'name'); - preferences.set('personal-files.sorting.direction', 'desc'); - - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }] - } - } as NodePaging) - ); - - const ids = await component.getFileIds('libraries', 'site1'); - expect(ids).toEqual(['node2', 'node1']); - }); - - it('should require folder id to fetch ids for libraries', async () => { - const ids = await component.getFileIds('libraries', null); - expect(ids).toEqual([]); - }); - - it('should sort file ids for libraries with [modifiedAt desc]', async () => { - spyOn(preferences, 'get').and.returnValue(null); - - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [ - { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } }, - { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } } - ] - } - } as NodePaging) - ); - - const ids = await component.getFileIds('libraries', 'folder1'); - expect(ids).toEqual(['node2', 'node1']); - }); - - it('should fetch and sort ids for favorites', async () => { - preferences.set('favorites.sorting.key', 'name'); - preferences.set('favorites.sorting.direction', 'desc'); - - spyOn(contentApi, 'getFavorites').and.returnValue( - of({ - list: { - entries: [ - { entry: { target: { file: { id: 'file3', name: 'file 3' } } } }, - { entry: { target: { file: { id: 'file1', name: 'file 1' } } } }, - { entry: { target: { file: { id: 'file2', name: 'file 2' } } } } - ] - } - } as FavoritePaging) - ); - - const ids = await component.getFileIds('favorites'); - expect(ids).toEqual(['file3', 'file2', 'file1']); - }); - - it('should sort file ids for favorites with [modifiedAt desc]', async () => { - spyOn(preferences, 'get').and.returnValue(null); - - spyOn(contentApi, 'getFavorites').and.returnValue( - of({ - list: { - entries: [ - { - entry: { - target: { file: { id: 'file3', modifiedAt: new Date(3) } } - } - }, - { - entry: { - target: { file: { id: 'file1', modifiedAt: new Date(1) } } - } - }, - { - entry: { - target: { file: { id: 'file2', modifiedAt: new Date(2) } } - } - } - ] - } - } as FavoritePaging) - ); - - const ids = await component.getFileIds('favorites'); - expect(ids).toEqual(['file3', 'file2', 'file1']); - }); - - it('should fetch and sort file ids for shared files', async () => { - preferences.set('shared.sorting.key', 'name'); - preferences.set('shared.sorting.direction', 'asc'); - - spyOn(contentApi, 'findSharedLinks').and.returnValue( - of({ - list: { - entries: [ - { - entry: { - nodeId: 'node2', - name: 'node 2', - modifiedAt: new Date(2) - } - }, - { - entry: { - nodeId: 'node1', - name: 'node 1', - modifiedAt: new Date(1) - } - } - ] - } - } as SharedLinkPaging) - ); - - const ids = await component.getFileIds('shared'); - expect(ids).toEqual(['node1', 'node2']); - }); - - it('should sort file ids for favorites with [modifiedAt desc]', async () => { - spyOn(preferences, 'get').and.returnValue(null); - - spyOn(contentApi, 'findSharedLinks').and.returnValue( - of({ - list: { - entries: [ - { - entry: { - nodeId: 'node2', - name: 'node 2', - modifiedAt: new Date(2) - } - }, - { - entry: { - nodeId: 'node1', - name: 'node 1', - modifiedAt: new Date(1) - } - } - ] - } - } as SharedLinkPaging) - ); - - const ids = await component.getFileIds('shared'); - expect(ids).toEqual(['node2', 'node1']); - }); - - it('should fetch and sort ids for recent-files', async () => { - preferences.set('recent-files.sorting.key', 'name'); - preferences.set('recent-files.sorting.direction', 'asc'); - - spyOn(contentApi, 'getPerson').and.returnValue( - of({ - entry: { id: 'user' } - } as PersonEntry) - ); - - spyOn(contentApi, 'search').and.returnValue( - of({ - list: { - entries: [ - { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } }, - { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } } - ] - } - } as ResultSetPaging) - ); - - const ids = await component.getFileIds('recent-files'); - expect(ids).toEqual(['node1', 'node2']); - }); - - it('should sort file ids for favorites with [modifiedAt desc]', async () => { - spyOn(preferences, 'get').and.returnValue(null); - - spyOn(contentApi, 'getPerson').and.returnValue( - of({ - entry: { id: 'user' } - } as PersonEntry) - ); - - spyOn(contentApi, 'search').and.returnValue( - of({ - list: { - entries: [ - { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } }, - { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } } - ] - } - } as ResultSetPaging) - ); - - const ids = await component.getFileIds('recent-files'); - expect(ids).toEqual(['node2', 'node1']); - }); - it('should return to parent folder on nodesDeleted event', async () => { spyOn(component, 'navigateToFileLocation'); fixture.detectChanges(); @@ -749,23 +419,36 @@ describe('PreviewComponent', () => { store.dispatch(new ClosePreviewAction()); expect(component.navigateToFileLocation).toHaveBeenCalled(); }); + it('should fetch navigation source from route', () => { + route.snapshot.data = { + navigateSource: 'personal-files' + }; - it('should not sort personal files when server-side sorting is set', async () => { - spyOn(preferences, 'get').and.returnValues('name', 'desc', 'server'); + component.ngOnInit(); - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [ - { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } }, - { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } } - ] - } - } as NodePaging) - ); + expect(component.navigateSource).toBe('personal-files'); + }); + + it('should fetch case-insensitive source from route', () => { + route.snapshot.data = { + navigateSource: 'PERSONAL-FILES' + }; - const ids = await component.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node1', 'node2']); + component.navigationSources = ['personal-files']; + component.ngOnInit(); + + expect(component.navigateSource).toBe('PERSONAL-FILES'); + }); + + it('should fetch only permitted navigation source from route', () => { + route.snapshot.data = { + navigateSource: 'personal-files' + }; + + component.navigationSources = ['shared']; + component.ngOnInit(); + + expect(component.navigateSource).toBeNull(); }); describe('Keyboard navigation', () => { diff --git a/projects/aca-content/preview/src/lib/components/preview.component.ts b/projects/aca-content/viewer/src/lib/components/preview/preview.component.ts similarity index 55% rename from projects/aca-content/preview/src/lib/components/preview.component.ts rename to projects/aca-content/viewer/src/lib/components/preview/preview.component.ts index f345db7bfe..6478a7b514 100644 --- a/projects/aca-content/preview/src/lib/components/preview.component.ts +++ b/projects/aca-content/viewer/src/lib/components/preview/preview.component.ts @@ -24,9 +24,9 @@ import { Component, OnInit, OnDestroy, ViewEncapsulation, HostListener } from '@angular/core'; import { CommonModule, Location } from '@angular/common'; -import { ActivatedRoute, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET } from '@angular/router'; +import { UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET, ActivatedRoute } from '@angular/router'; import { debounceTime, map, takeUntil } from 'rxjs/operators'; -import { UserPreferencesService, ObjectUtils, ViewerModule } from '@alfresco/adf-core'; +import { ViewerModule } from '@alfresco/adf-core'; import { ClosePreviewAction, ViewerActionTypes, SetSelectedNodesAction } from '@alfresco/aca-shared/store'; import { PageComponent, @@ -37,10 +37,10 @@ import { ToolbarComponent } from '@alfresco/aca-shared'; import { ContentActionRef, ViewerExtensionRef } from '@alfresco/adf-extensions'; -import { SearchRequest } from '@alfresco/js-api'; import { from } from 'rxjs'; import { Actions, ofType } from '@ngrx/effects'; import { AlfrescoViewerModule, NodesApiService } from '@alfresco/adf-content-services'; +import { ViewerService } from '../../services/viewer.service'; @Component({ standalone: true, @@ -52,55 +52,31 @@ import { AlfrescoViewerModule, NodesApiService } from '@alfresco/adf-content-ser host: { class: 'app-preview' } }) export class PreviewComponent extends PageComponent implements OnInit, OnDestroy { - previewLocation: string = null; - routesSkipNavigation = ['shared', 'recent-files', 'favorites']; + contentExtensions: Array = []; + folderId: string = null; + navigateBackAsClose = false; + navigateMultiple = false; navigateSource: string = null; navigationSources = ['favorites', 'libraries', 'personal-files', 'recent-files', 'shared']; - folderId: string = null; - nodeId: string = null; - previousNodeId: string; nextNodeId: string; - navigateMultiple = false; + nodeId: string = null; openWith: Array = []; - contentExtensions: Array = []; + previewLocation: string = null; + previousNodeId: string; + routesSkipNavigation = ['favorites', 'recent-files', 'shared']; showRightSide = false; - navigateBackAsClose = false; simplestMode = false; - recentFileFilters = [ - 'TYPE:"content"', - '-PATH:"//cm:wiki/*"', - '-TYPE:"app:filelink"', - '-TYPE:"fm:post"', - '-TYPE:"cm:thumbnail"', - '-TYPE:"cm:failedThumbnail"', - '-TYPE:"cm:rating"', - '-TYPE:"dl:dataList"', - '-TYPE:"dl:todoList"', - '-TYPE:"dl:issue"', - '-TYPE:"dl:contact"', - '-TYPE:"dl:eventAgenda"', - '-TYPE:"dl:event"', - '-TYPE:"dl:task"', - '-TYPE:"dl:simpletask"', - '-TYPE:"dl:meetingAgenda"', - '-TYPE:"dl:location"', - '-TYPE:"fm:topic"', - '-TYPE:"fm:post"', - '-TYPE:"ia:calendarEvent"', - '-TYPE:"lnk:link"' - ]; - private containersSkipNavigation = ['adf-viewer__sidebar', 'cdk-overlay-container', 'adf-image-viewer']; constructor( - private contentApi: ContentApiService, - private preferences: UserPreferencesService, - private route: ActivatedRoute, - private nodesApiService: NodesApiService, private actions$: Actions, + private appHookService: AppHookService, + private contentApi: ContentApiService, private location: Location, - private appHookService: AppHookService + private nodesApiService: NodesApiService, + private route: ActivatedRoute, + private viewerService: ViewerService ) { super(); } @@ -135,7 +111,7 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy this.folderId = params.folderId; const id = params.nodeId; if (id) { - this.displayNode(id); + void this.displayNode(id); } }); @@ -178,8 +154,7 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy this.store.dispatch(new SetSelectedNodesAction([{ entry: this.node }])); if (this.node?.isFile) { - const nearest = await this.getNearestNodes(this.node.id, this.node.parentId); - + const nearest = await this.viewerService.getNearestNodes(this.node.id, this.node.parentId, this.navigateSource); this.previousNodeId = nearest.left; this.nextNodeId = nearest.right; this.nodeId = this.node.id; @@ -225,7 +200,7 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy if (!shouldSkipNavigation && this.folderId) { route.push(this.folderId); } - this.router.navigate(route); + void this.router.navigate(route); } } } @@ -237,7 +212,7 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy } if (this.previousNodeId) { - this.router.navigate(this.getPreviewPath(this.folderId, this.previousNodeId)); + void this.router.navigate(this.getPreviewPath(this.folderId, this.previousNodeId)); } } @@ -248,7 +223,7 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy } if (this.nextNodeId) { - this.router.navigate(this.getPreviewPath(this.folderId, this.nextNodeId)); + void this.router.navigate(this.getPreviewPath(this.folderId, this.nextNodeId)); } } @@ -272,167 +247,6 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy return route; } - /** - * Retrieves nearest node information for the given node and folder. - * - * @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 }> { - const empty = { - left: null, - right: null - }; - - if (nodeId && folderId) { - try { - const ids = await this.getFileIds(this.navigateSource, folderId); - const idx = ids.indexOf(nodeId); - - if (idx >= 0) { - return { - left: ids[idx - 1] || null, - right: ids[idx + 1] || null - }; - } else { - return empty; - } - } catch { - return empty; - } - } else { - return empty; - } - } - - /** - * Retrieves a list of node identifiers for the folder and data source. - * - * @param source Data source name. Allowed values are: personal-files, libraries, favorites, shared, recent-files. - * @param folderId Containing folder node identifier for 'personal-files' and 'libraries' sources. - */ - async getFileIds(source: string, folderId?: string): Promise { - 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 nodes = await this.contentApi - .getNodeChildren(folderId, { - orderBy: ['isFolder desc', `${sortKey} ${sortDirection}`], - fields: ['id', this.getRootField(sortKey)], - where: '(isFile=true)' - }) - .toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - if (this.preferences.get('filesPageSortingMode') === 'client' || source === 'libraries') { - this.sort(entries, sortKey, sortDirection); - } - - return entries.map((obj) => obj.id); - } - - if (source === 'favorites') { - const nodes = await this.contentApi - .getFavorites('-me-', { - where: '(EXISTS(target/file))', - fields: ['target'] - }) - .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); - this.sort(files, sortKey, sortDirection); - - 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 nodes = await this.contentApi - .findSharedLinks({ - fields: ['nodeId', this.getRootField(sortingKey)] - }) - .toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - this.sort(entries, sortingKey, sortingDirection); - - 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 query: SearchRequest = { - query: { - query: '*', - language: 'afts' - }, - filterQueries: [ - { query: `cm:modified:[NOW/DAY-30DAYS TO NOW/DAY+1DAY]` }, - { query: `cm:modifier:${username} OR cm:creator:${username}` }, - { - query: this.recentFileFilters.join(' AND ') - } - ], - fields: ['id', this.getRootField(sortingKey)], - include: ['path', 'properties', 'allowableOperations'], - sort: [ - { - type: 'FIELD', - field: 'cm:modified', - ascending: false - } - ] - }; - const nodes = await this.contentApi.search(query).toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - this.sort(entries, sortingKey, sortingDirection); - - return entries.map((obj) => obj.id); - } - - return []; - } - - private sort(items: any[], key: string, direction: string) { - const options: Intl.CollatorOptions = {}; - - if (key.includes('sizeInBytes') || key === 'name') { - options.numeric = true; - } - - items.sort((a: any, b: any) => { - let left = ObjectUtils.getValue(a, key) ?? ''; - left = left instanceof Date ? left.valueOf().toString() : left.toString(); - - let right = ObjectUtils.getValue(b, key) ?? ''; - right = right instanceof Date ? right.valueOf().toString() : right.toString(); - - return direction === 'asc' ? left.localeCompare(right, undefined, options) : right.localeCompare(left, undefined, options); - }); - } - - /** - * Get the root field name from the property path. - * Example: 'property1.some.child.property' => 'property1' - * - * @param path Property path - */ - getRootField(path: string) { - if (path) { - return path.split('.')[0]; - } - return path; - } - private getNavigationCommands(url: string): any[] { const urlTree: UrlTree = this.router.parseUrl(url); const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET]; diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts index c35f55264d..a3b1f3b4d3 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts @@ -22,9 +22,33 @@ * from Hyland Software. If not, see . */ -import { TestBed, ComponentFixture } from '@angular/core/testing'; +/*! + * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. + * + * Alfresco Example Content Application + * + * This file is part of the Alfresco Example Content Application. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * The Alfresco Example Content Application is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * The Alfresco Example Content Application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * from Hyland Software. If not, see . + */ + +import { Router, ActivatedRoute } from '@angular/router'; +import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing'; import { - UserPreferencesService, AlfrescoApiService, AlfrescoApiServiceMock, AuthenticationService, @@ -32,13 +56,13 @@ import { TranslationService, PipeModule } from '@alfresco/adf-core'; -import { DiscoveryApiService, NodesApiService } from '@alfresco/adf-content-services'; -import { AppState, RefreshPreviewAction } from '@alfresco/aca-shared/store'; +import { UploadService, NodesApiService, DiscoveryApiService } from '@alfresco/adf-content-services'; +import { AppState, ClosePreviewAction, ReloadDocumentListAction, ViewNodeAction } from '@alfresco/aca-shared/store'; import { AcaViewerComponent } from './viewer.component'; -import { BehaviorSubject, Observable, of } from 'rxjs'; -import { ContentApiService, DocumentBasePageService } from '@alfresco/aca-shared'; +import { BehaviorSubject, Observable, of, throwError } from 'rxjs'; +import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; import { Store, StoreModule } from '@ngrx/store'; -import { NodePaging, RepositoryInfo, VersionInfo, Node } from '@alfresco/js-api'; +import { RepositoryInfo, VersionInfo } from '@alfresco/js-api'; import { AcaViewerModule } from '../../viewer.module'; import { TranslateModule } from '@ngx-translate/core'; import { RouterTestingModule } from '@angular/router/testing'; @@ -90,12 +114,17 @@ export const INITIAL_APP_STATE: AppState = { } as any }; -describe('ViewerComponent', () => { +const fakeLocation = 'fakeLocation'; + +describe('AcaViewerComponent', () => { let fixture: ComponentFixture; let component: AcaViewerComponent; - let preferences: UserPreferencesService; + let router: Router; + let route: ActivatedRoute; let contentApi: ContentApiService; + let uploadService: UploadService; let nodesApiService: NodesApiService; + let appHookService: AppHookService; let store: Store; beforeEach(() => { @@ -104,7 +133,7 @@ describe('ViewerComponent', () => { AcaViewerModule, NoopAnimationsModule, HttpClientModule, - RouterTestingModule, + RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), StoreModule.forRoot( { app: (state) => state }, @@ -155,58 +184,186 @@ describe('ViewerComponent', () => { fixture = TestBed.createComponent(AcaViewerComponent); component = fixture.componentInstance; - preferences = TestBed.inject(UserPreferencesService); + router = TestBed.inject(Router); + route = TestBed.inject(ActivatedRoute); contentApi = TestBed.inject(ContentApiService); + uploadService = TestBed.inject(UploadService); nodesApiService = TestBed.inject(NodesApiService); + appHookService = TestBed.inject(AppHookService); store = TestBed.inject(Store); }); - it('should fetch and sort file ids for personal-files', async () => { - spyOn(preferences, 'get').and.returnValues('name', 'desc', 'client'); + it('should display document upon init', () => { + route.params = of({ + folderId: 'folder1', + nodeId: 'node1' + }); + spyOn(component, 'displayNode').and.stub(); - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }] - } - } as NodePaging) - ); + component.ngOnInit(); - const ids = await component.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node2', 'node1']); + expect(component.folderId).toBe('folder1'); + expect(component.displayNode).toHaveBeenCalledWith('node1'); }); - it('should fetch file ids for personal-files with default sorting for missing key', async () => { - spyOn(preferences, 'get').and.returnValues('missing', 'desc', 'client'); + it('should not display node when id is missing', async () => { + spyOn(router, 'navigate').and.stub(); + spyOn(contentApi, 'getNodeInfo').and.returnValue(of(null)); - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2' } }] - } - } as NodePaging) - ); + await component.displayNode(null); - const ids = await component.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node1', 'node2']); + expect(contentApi.getNodeInfo).not.toHaveBeenCalled(); + expect(router.navigate).not.toHaveBeenCalled(); }); - it('should not sort personal files when server-side sorting is set', async () => { - spyOn(preferences, 'get').and.returnValues('name', 'desc', 'server'); + it('should navigate to next and previous nodes', () => { + spyOn(store, 'dispatch'); + spyOn(component, 'getFileLocation').and.returnValue(fakeLocation); + const clickEvent = new MouseEvent('click'); - spyOn(contentApi, 'getNodeChildren').and.returnValue( - of({ - list: { - entries: [ - { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } }, - { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(2) } } - ] - } - } as NodePaging) - ); + component.previousNodeId = 'previous'; + component.onNavigateBefore(clickEvent); + expect(store.dispatch).toHaveBeenCalledWith(new ViewNodeAction('previous', { location: fakeLocation })); + + component.nextNodeId = 'next'; + component.onNavigateNext(clickEvent); + expect(store.dispatch).toHaveBeenCalledWith(new ViewNodeAction('next', { location: fakeLocation })); + }); + + it('should reload document list and navigate to correct location upon close', async () => { + spyOn(store, 'dispatch'); + spyOn(component, 'navigateToFileLocation').and.callThrough(); + spyOn(component, 'getFileLocation').and.returnValue(fakeLocation); + spyOn(router, 'navigateByUrl').and.returnValue(Promise.resolve(true)); + + component.onViewerVisibilityChanged(); + + expect(store.dispatch).toHaveBeenCalledWith(new ReloadDocumentListAction()); + expect(component['navigateToFileLocation']).toHaveBeenCalled(); + expect(router.navigateByUrl).toHaveBeenCalledWith(fakeLocation); + }); + + it('should navigate to original location in case of Alfresco API errors', async () => { + component['previewLocation'] = 'personal-files'; + spyOn(contentApi, 'getNodeInfo').and.returnValue(throwError('error')); + spyOn(JSON, 'parse').and.returnValue({ error: { statusCode: '123' } }); + spyOn(router, 'navigate').and.returnValue(Promise.resolve(true)); + + await component.displayNode('folder1'); + + expect(contentApi.getNodeInfo).toHaveBeenCalledWith('folder1'); + expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1']); + }); + + it('should emit nodeUpdated event on fileUploadComplete event', fakeAsync(() => { + spyOn(nodesApiService.nodeUpdated, 'next'); + fixture.detectChanges(); + uploadService.fileUploadComplete.next({ data: { entry: {} } } as any); + tick(300); - const ids = await component.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node1', 'node2']); + expect(nodesApiService.nodeUpdated.next).toHaveBeenCalled(); + })); + + describe('return on event', () => { + beforeEach(async () => { + spyOn(component, 'navigateToFileLocation'); + fixture.detectChanges(); + await fixture.whenStable(); + }); + + it('should return to parent folder on fileUploadDeleted event', async () => { + uploadService.fileUploadDeleted.next(); + + expect(component['navigateToFileLocation']).toHaveBeenCalled(); + }); + + it('should return to parent folder when event emitted from extension', async () => { + store.dispatch(new ClosePreviewAction()); + + expect(component['navigateToFileLocation']).toHaveBeenCalled(); + }); + + it('should return to parent folder on nodesDeleted event', async () => { + appHookService.nodesDeleted.next(); + + expect(component['navigateToFileLocation']).toHaveBeenCalled(); + }); + }); + + it('should fetch navigation source from route', () => { + route.snapshot.data = { + navigateSource: 'personal-files' + }; + + component.ngOnInit(); + + expect(component.navigateSource).toBe('personal-files'); + }); + + it('should fetch only permitted navigation source from route', () => { + route.snapshot.data = { + navigateSource: 'personal-files' + }; + + component.navigationSources = ['shared']; + component.ngOnInit(); + + expect(component.navigateSource).toBeNull(); + }); + + it('should fetch case-insensitive source from route', () => { + route.snapshot.data = { + navigateSource: 'PERSONAL-FILES' + }; + + component.navigationSources = ['personal-files']; + component.ngOnInit(); + + expect(component.navigateSource).toBe('PERSONAL-FILES'); + }); + + describe('Keyboard navigation', () => { + beforeEach(() => { + component.nextNodeId = 'nextNodeId'; + component.previousNodeId = 'previousNodeId'; + spyOn(router, 'navigate').and.stub(); + }); + + afterEach(() => { + fixture.destroy(); + }); + + it('should not navigate on keyboard event if target is child of sidebar container', () => { + const parent = document.createElement('div'); + parent.className = 'adf-viewer__sidebar'; + + const child = document.createElement('button'); + child.addEventListener('keyup', function (e) { + component.onNavigateNext(e); + }); + parent.appendChild(child); + document.body.appendChild(parent); + + child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowLeft' })); + + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('should not navigate on keyboard event if target is child of cdk overlay', () => { + const parent = document.createElement('div'); + parent.className = 'cdk-overlay-container'; + + const child = document.createElement('button'); + child.addEventListener('keyup', function (e) { + component.onNavigateNext(e); + }); + parent.appendChild(child); + document.body.appendChild(parent); + + child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowLeft' })); + + expect(router.navigate).not.toHaveBeenCalled(); + }); }); it('should call node update after RefreshPreviewAction is triggered', () => { diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts index 0de6680c0a..6bfe1a3194 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts @@ -43,16 +43,17 @@ import { ViewNodeAction } from '@alfresco/aca-shared/store'; import { ContentActionRef, SelectionState } from '@alfresco/adf-extensions'; -import { Node, SearchRequest, VersionEntry, VersionsApi } from '@alfresco/js-api'; +import { Node, VersionEntry, VersionsApi } from '@alfresco/js-api'; import { Component, HostListener, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; import { ActivatedRoute, PRIMARY_OUTLET, Router } from '@angular/router'; -import { AlfrescoApiService, AppConfigModule, ObjectUtils, UserPreferencesService, ViewerModule } from '@alfresco/adf-core'; +import { AlfrescoApiService, AppConfigModule, ViewerModule } from '@alfresco/adf-core'; import { Store } from '@ngrx/store'; import { from, Observable, Subject } from 'rxjs'; import { debounceTime, takeUntil } from 'rxjs/operators'; import { Actions, ofType } from '@ngrx/effects'; import { AlfrescoViewerModule, NodesApiService, UploadService } from '@alfresco/adf-content-services'; import { CommonModule } from '@angular/common'; +import { ViewerService } from '../../services/viewer.service'; @Component({ standalone: true, @@ -74,62 +75,37 @@ export class AcaViewerComponent implements OnInit, OnDestroy { fileName: string; folderId: string = null; - nodeId: string = null; - versionId: string = null; - node: Node; - selection: SelectionState; infoDrawerOpened$: Observable; - - showRightSide = false; - openWith: ContentActionRef[] = []; - toolbarActions: ContentActionRef[] = []; - + navigateMultiple = true; navigateSource: string = null; - previousNodeId: string; + navigationSources = ['favorites', 'libraries', 'personal-files', 'recent-files', 'shared']; nextNodeId: string; - navigateMultiple = true; + node: Node; + nodeId: string = null; + openWith: ContentActionRef[] = []; + previousNodeId: string; routesSkipNavigation = ['shared', 'recent-files', 'favorites']; - navigationSources = ['favorites', 'libraries', 'personal-files', 'recent-files', 'shared']; - recentFileFilters = [ - 'TYPE:"content"', - '-PATH:"//cm:wiki/*"', - '-TYPE:"app:filelink"', - '-TYPE:"fm:post"', - '-TYPE:"cm:thumbnail"', - '-TYPE:"cm:failedThumbnail"', - '-TYPE:"cm:rating"', - '-TYPE:"dl:dataList"', - '-TYPE:"dl:todoList"', - '-TYPE:"dl:issue"', - '-TYPE:"dl:contact"', - '-TYPE:"dl:eventAgenda"', - '-TYPE:"dl:event"', - '-TYPE:"dl:task"', - '-TYPE:"dl:simpletask"', - '-TYPE:"dl:meetingAgenda"', - '-TYPE:"dl:location"', - '-TYPE:"fm:topic"', - '-TYPE:"fm:post"', - '-TYPE:"ia:calendarEvent"', - '-TYPE:"lnk:link"' - ]; + selection: SelectionState; + showRightSide = false; + toolbarActions: ContentActionRef[] = []; + versionId: string = null; private navigationPath: string; private previewLocation: string; private containersSkipNavigation = ['adf-viewer__sidebar', 'cdk-overlay-container', 'adf-image-viewer']; constructor( - private router: Router, - private route: ActivatedRoute, - private store: Store, - private extensions: AppExtensionService, - private contentApi: ContentApiService, private actions$: Actions, - private preferences: UserPreferencesService, private apiService: AlfrescoApiService, + private appHookService: AppHookService, + private contentApi: ContentApiService, + private extensions: AppExtensionService, private nodesApiService: NodesApiService, + private route: ActivatedRoute, + private router: Router, + private store: Store, private uploadService: UploadService, - private appHookService: AppHookService + private viewerService: ViewerService ) {} ngOnInit() { @@ -167,7 +143,7 @@ export class AcaViewerComponent implements OnInit, OnDestroy { const { nodeId } = params; this.versionId = params.versionId; if (this.versionId) { - this.versionsApi.getVersion(nodeId, this.versionId).then((version: VersionEntry) => { + void this.versionsApi.getVersion(nodeId, this.versionId).then((version: VersionEntry) => { if (version) { this.store.dispatch(new SetCurrentNodeVersionAction(version)); } @@ -241,7 +217,7 @@ export class AcaViewerComponent implements OnInit, OnDestroy { } if (this.node?.isFile) { - const nearest = await this.getNearestNodes(this.node.id, this.node.parentId); + const nearest = await this.viewerService.getNearestNodes(this.node.id, this.node.parentId, this.navigateSource); this.nodeId = this.node.id; this.previousNodeId = nearest.left; this.nextNodeId = nearest.right; @@ -252,8 +228,8 @@ export class AcaViewerComponent implements OnInit, OnDestroy { const statusCode = JSON.parse(error.message).error.statusCode; if (statusCode !== 401) { - this.router.navigate([this.previewLocation, { outlets: { viewer: null } }]).then(() => { - this.router.navigate([this.previewLocation, nodeId]); + await this.router.navigate([this.previewLocation, { outlets: { viewer: null } }]).then(() => { + void this.router.navigate([this.previewLocation, nodeId]); }); } } @@ -278,148 +254,6 @@ export class AcaViewerComponent implements OnInit, OnDestroy { this.store.dispatch(new ViewNodeAction(this.nextNodeId, { location })); } - /** - * Retrieves nearest node information for the given node and folder. - * - * @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 }> { - const empty = { - left: null, - right: null - }; - - if (nodeId && folderId) { - try { - const ids = await this.getFileIds(this.navigateSource, folderId); - const idx = ids.indexOf(nodeId); - - if (idx >= 0) { - return { - left: ids[idx - 1] || null, - right: ids[idx + 1] || null - }; - } else { - return empty; - } - } catch { - return empty; - } - } else { - return empty; - } - } - - /** - * Retrieves a list of node identifiers for the folder and data source. - * - * @param source Data source name. Allowed values are: personal-files, libraries, favorites, shared, recent-files. - * @param folderId Containing folder node identifier for 'personal-files' and 'libraries' sources. - */ - async getFileIds(source: string, folderId?: string): Promise { - 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 nodes = await this.contentApi - .getNodeChildren(folderId, { - orderBy: ['isFolder desc', `${sortKey} ${sortDirection}`], - fields: ['id', this.getRootField(sortKey)], - where: '(isFile=true)' - }) - .toPromise(); - const entries = nodes.list.entries.map((obj) => obj.entry); - if (this.preferences.get('filesPageSortingMode') === 'client' || source === 'libraries') { - this.sort(entries, sortKey, sortDirection); - } - - return entries.map((obj) => obj.id); - } - - if (source === 'favorites') { - const nodes = await this.contentApi - .getFavorites('-me-', { - where: '(EXISTS(target/file))', - fields: ['target'] - }) - .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); - this.sort(files, sortKey, sortDirection); - - 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 nodes = await this.contentApi - .findSharedLinks({ - fields: ['nodeId', this.getRootField(sortingKey)] - }) - .toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - this.sort(entries, sortingKey, sortingDirection); - - 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 query: SearchRequest = { - query: { - query: '*', - language: 'afts' - }, - filterQueries: [ - { query: `cm:modified:[NOW/DAY-30DAYS TO NOW/DAY+1DAY]` }, - { query: `cm:modifier:${username} OR cm:creator:${username}` }, - { - query: this.recentFileFilters.join(' AND ') - } - ], - fields: ['id', this.getRootField(sortingKey)], - include: ['path', 'properties', 'allowableOperations'], - sort: [ - { - type: 'FIELD', - field: 'cm:modified', - ascending: false - } - ] - }; - const nodes = await this.contentApi.search(query).toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - this.sort(entries, sortingKey, sortingDirection); - - return entries.map((obj) => obj.id); - } - - return []; - } - - /** - * Get the root field name from the property path. - * Example: 'property1.some.child.property' => 'property1' - * - * @param path Property path - */ - getRootField(path: string) { - if (path) { - return path.split('.')[0]; - } - return path; - } - @HostListener('document:keydown', ['$event']) handleKeyboardEvent(event: KeyboardEvent) { const key = event.key; @@ -430,27 +264,9 @@ export class AcaViewerComponent implements OnInit, OnDestroy { } } - private sort(items: any[], key: string, direction: string) { - const options: Intl.CollatorOptions = {}; - - if (key.includes('sizeInBytes') || key === 'name') { - options.numeric = true; - } - - items.sort((a: any, b: any) => { - let left = ObjectUtils.getValue(a, key) ?? ''; - left = left instanceof Date ? left.valueOf().toString() : left.toString(); - - let right = ObjectUtils.getValue(b, key) ?? ''; - right = right instanceof Date ? right.valueOf().toString() : right.toString(); - - return direction === 'asc' ? left.localeCompare(right, undefined, options) : right.localeCompare(left, undefined, options); - }); - } - private navigateToFileLocation() { const location = this.getFileLocation(); - this.router.navigateByUrl(location); + void this.router.navigateByUrl(location); } private getFileLocation(): string { diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts new file mode 100644 index 0000000000..dd86e22db7 --- /dev/null +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts @@ -0,0 +1,222 @@ +/*! + * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. + * + * Alfresco Example Content Application + * + * This file is part of the Alfresco Example Content Application. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * The Alfresco Example Content Application is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * The Alfresco Example Content Application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * from Hyland Software. If not, see . + */ + +import { TestBed } from '@angular/core/testing'; +import { TranslationMock, TranslationService, UserPreferencesService } from '@alfresco/adf-core'; +import { ContentApiService } from '@alfresco/aca-shared'; +import { FavoritePaging, NodePaging, SharedLinkPaging } from '@alfresco/js-api'; +import { ViewerService } from '../services/viewer.service'; +import { of } from 'rxjs'; +import { TranslateModule } from '@ngx-translate/core'; +import { HttpClientModule } from '@angular/common/http'; + +const list = { + list: { + entries: [ + { entry: { id: 'node1', name: 'node 1', title: 'node 1', modifiedAt: new Date(1) } }, + { entry: { id: 'node3', name: 'node 3', title: 'node 3', modifiedAt: new Date(2) } }, + { entry: { id: 'node2', name: 'node 2', title: 'node 2', modifiedAt: new Date(1) } } + ] + } +}; + +const favoritesList = { + list: { + entries: [ + { entry: { target: { file: { id: 'node1', name: 'node 1' } } } }, + { entry: { target: { file: { id: 'node2', name: 'node 2' } } } }, + { entry: { target: { file: { id: 'node3', name: 'node 3' } } } } + ] + } +}; + +const preferencesNoPrevSortValues = ['client', '', '']; +const preferencesCurSortValues = [...preferencesNoPrevSortValues, 'name', 'desc']; +const preferencesNoCurSortValues = [...preferencesNoPrevSortValues, '', '']; + +describe('ViewerService', () => { + let preferences: UserPreferencesService; + let contentApi: ContentApiService; + let viewerService: ViewerService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [TranslateModule.forRoot(), HttpClientModule], + providers: [{ provide: TranslationService, useClass: TranslationMock }, ViewerService, UserPreferencesService, ContentApiService] + }); + + preferences = TestBed.inject(UserPreferencesService); + contentApi = TestBed.inject(ContentApiService); + viewerService = TestBed.inject(ViewerService); + }); + + describe('Sorting for different sources', () => { + beforeEach(() => { + spyOn(preferences, 'get').and.returnValues(...preferencesCurSortValues); + }); + + it('should fetch and sort file ids for personal files', async () => { + spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); + const ids = await viewerService.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node3', 'node2', 'node1']); + }); + + it('should fetch and sort file ids for libraries', async () => { + spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); + const ids = await viewerService.getFileIds('libraries', 'folder1'); + expect(ids).toEqual(['node3', 'node2', 'node1']); + }); + + it('should fetch and sort file ids for favorites', async () => { + spyOn(contentApi, 'getFavorites').and.returnValue(of(favoritesList as FavoritePaging)); + const ids = await viewerService.getFileIds('favorites'); + expect(ids).toEqual(['node3', 'node2', 'node1']); + }); + + it('should fetch and sort file ids for shared', async () => { + spyOn(contentApi, 'findSharedLinks').and.returnValue( + of({ + list: { + entries: [ + { + entry: { + nodeId: 'node1', + name: 'node 1' + } + }, + { + entry: { + nodeId: 'node2', + name: 'node 2' + } + }, + { + entry: { + nodeId: 'node3', + name: 'node 3' + } + } + ] + } + } as SharedLinkPaging) + ); + const ids = await viewerService.getFileIds('shared'); + expect(ids).toEqual(['node3', 'node2', 'node1']); + }); + }); + + describe('default sorting for different sources', () => { + beforeEach(() => { + spyOn(preferences, 'get').and.returnValues(...preferencesNoCurSortValues); + }); + + it('should use default with no sorting for personal-files', async () => { + spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); + const ids = await viewerService.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node1', 'node2', 'node3']); + }); + + it('should use default with no sorting for libraries', async () => { + spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); + const ids = await viewerService.getFileIds('libraries', 'folder1'); + expect(ids).toEqual(['node1', 'node2', 'node3']); + }); + + it('should use default with no sorting for other sources', async () => { + spyOn(contentApi, 'getFavorites').and.returnValue(of(favoritesList as FavoritePaging)); + const ids = await viewerService.getFileIds('favorites'); + expect(ids).toEqual(['node1', 'node2', 'node3']); + }); + }); + + describe('Other sorting scenarios', () => { + beforeEach(() => { + spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); + }); + + it('should not sort when server-side sorting is set', async () => { + spyOn(preferences, 'get').and.returnValues('server', '', '', 'name', 'desc'); + const ids = await viewerService.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node1', 'node3', 'node2']); + }); + + it('should sort with previous and current sorting', async () => { + spyOn(preferences, 'get').and.returnValues('client', 'name', 'asc', 'modifiedAt', 'desc'); + const ids = await viewerService.getFileIds('personal-files', 'folder1'); + expect(ids).toEqual(['node3', 'node1', 'node2']); + }); + }); + + it('should extract the property path root', () => { + expect(viewerService.getRootField('some.property.path')).toBe('some'); + expect(viewerService.getRootField('some')).toBe('some'); + expect(viewerService.getRootField('')).toBe(''); + expect(viewerService.getRootField(null)).toBe(null); + }); + + it('should return empty nearest nodes for missing node id', async () => { + const nearest = await viewerService.getNearestNodes(null, 'folder1', 'source'); + + expect(nearest).toEqual({ left: null, right: null }); + }); + + it('should return empty nearest nodes for missing folder id', async () => { + const nearest = await viewerService.getNearestNodes('node1', null, 'source'); + + expect(nearest).toEqual({ left: null, right: null }); + }); + + it('should return empty nearest nodes for crashed fields id request', async () => { + spyOn(viewerService, 'getFileIds').and.returnValue(Promise.reject(new Error('err'))); + + const nearest = await viewerService.getNearestNodes('node1', 'folder1', 'source'); + + expect(nearest).toEqual({ left: null, right: null }); + }); + + it('should return nearest nodes', async () => { + spyOn(viewerService, 'getFileIds').and.returnValue(Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5'])); + + let nearest = await viewerService.getNearestNodes('node1', 'folder1', 'source'); + expect(nearest).toEqual({ left: null, right: 'node2' }); + + nearest = await viewerService.getNearestNodes('node3', 'folder1', 'source'); + expect(nearest).toEqual({ left: 'node2', right: 'node4' }); + + nearest = await viewerService.getNearestNodes('node5', 'folder1', 'source'); + expect(nearest).toEqual({ left: 'node4', right: null }); + }); + + it('should return empty nearest nodes if node is already deleted', async () => { + spyOn(viewerService, 'getFileIds').and.returnValue(Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5'])); + + const nearest = await viewerService.getNearestNodes('node9', 'folder1', 'source'); + expect(nearest).toEqual({ left: null, right: null }); + }); + + it('should require folder id to fetch ids for libraries', async () => { + const ids = await viewerService.getFileIds('libraries', null); + expect(ids).toEqual([]); + }); +}); diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.ts new file mode 100644 index 0000000000..890fffca40 --- /dev/null +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.ts @@ -0,0 +1,266 @@ +/*! + * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. + * + * Alfresco Example Content Application + * + * This file is part of the Alfresco Example Content Application. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * The Alfresco Example Content Application is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * The Alfresco Example Content Application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * from Hyland Software. If not, see . + */ + +import { ObjectUtils, UserPreferencesService } from '@alfresco/adf-core'; +import { SearchRequest } from '@alfresco/js-api'; +import { Injectable } from '@angular/core'; +import { ContentApiService } from '@alfresco/aca-shared'; + +@Injectable({ + providedIn: 'root' +}) +export class ViewerService { + constructor(private preferences: UserPreferencesService, private contentApi: ContentApiService) {} + + recentFileFilters = [ + 'TYPE:"content"', + '-PATH:"//cm:wiki/*"', + '-TYPE:"app:filelink"', + '-TYPE:"fm:post"', + '-TYPE:"cm:thumbnail"', + '-TYPE:"cm:failedThumbnail"', + '-TYPE:"cm:rating"', + '-TYPE:"dl:dataList"', + '-TYPE:"dl:todoList"', + '-TYPE:"dl:issue"', + '-TYPE:"dl:contact"', + '-TYPE:"dl:eventAgenda"', + '-TYPE:"dl:event"', + '-TYPE:"dl:task"', + '-TYPE:"dl:simpletask"', + '-TYPE:"dl:meetingAgenda"', + '-TYPE:"dl:location"', + '-TYPE:"fm:topic"', + '-TYPE:"fm:post"', + '-TYPE:"ia:calendarEvent"', + '-TYPE:"lnk:link"' + ]; + + /** + * Retrieves nearest node information for the given node and folder. + * + * @param nodeId Unique identifier of the document node + * @param folderId Unique identifier of the containing folder node. + */ + async getNearestNodes(nodeId: string, folderId: string, source: string): Promise<{ left: string; right: string }> { + const empty = { + left: null, + right: null + }; + + if (nodeId && folderId) { + try { + const ids = await this.getFileIds(source, folderId); + const idx = ids.indexOf(nodeId); + + if (idx >= 0) { + return { + left: ids[idx - 1] || null, + right: ids[idx + 1] || null + }; + } else { + return empty; + } + } catch { + return empty; + } + } else { + return empty; + } + } + + /** + * Retrieves a list of node identifiers for the folder and data source. + * + * @param folderId Optional parameter containing folder node identifier for 'personal-files' and 'libraries' sources. + */ + async getFileIds(source: string, folderId?: string): Promise { + const isClient = this.preferences.get(`${source}.sorting.mode`) === 'client'; + const [sortKey, sortDirection, previousSortKey, previousSortDir] = this.getSortKeyDir(source); + + if (source === 'personal-files' && folderId) { + const orderBy = isClient ? null : ['isFolder desc', `${sortKey} ${sortDirection}`]; + const nodes = await this.contentApi + .getNodeChildren(folderId, { + orderBy: orderBy, + fields: this.getFields(sortKey, previousSortKey), + where: '(isFile=true)' + }) + .toPromise(); + + const entries = nodes.list.entries.map((obj) => obj.entry); + if (isClient) { + if (previousSortKey) { + this.sort(entries, previousSortKey, previousSortDir); + } + this.sort(entries, sortKey, sortDirection); + } + return entries.map((entry) => entry.id); + } + + if (source === 'libraries' && folderId) { + const nodes = await this.contentApi + .getNodeChildren(folderId, { + fields: this.getFields(sortKey, previousSortKey), + where: '(isFile=true)' + }) + .toPromise(); + + const entries = nodes.list.entries.map((obj) => obj.entry); + if (isClient) { + if (previousSortKey) { + this.sort(entries, previousSortKey, previousSortDir); + } + this.sort(entries, sortKey, sortDirection); + } + return entries.map((entry) => entry.id); + } + + if (source === 'favorites') { + const nodes = await this.contentApi + .getFavorites('-me-', { + where: '(EXISTS(target/file))', + fields: ['target'] + }) + .toPromise(); + + const entries = nodes.list.entries.map((obj) => obj.entry.target.file); + if (isClient) { + if (previousSortKey) { + this.sort(entries, previousSortKey, previousSortDir); + } + this.sort(entries, sortKey, sortDirection); + } + return entries.map((entry) => entry.id); + } + + if (source === 'shared') { + const nodes = await this.contentApi + .findSharedLinks({ + fields: ['nodeId', this.getRootField(sortKey)] + }) + .toPromise(); + + const entries = nodes.list.entries.map((obj) => obj.entry); + if (isClient) { + if (previousSortKey) { + this.sort(entries, previousSortKey, previousSortDir); + } + this.sort(entries, sortKey, sortDirection); + } + return entries.map((entry) => entry.nodeId); + } + + if (source === 'recent-files') { + const person = await this.contentApi.getPerson('-me-').toPromise(); + const username = person.entry.id; + const query: SearchRequest = { + query: { + query: '*', + language: 'afts' + }, + filterQueries: [ + { query: `cm:modified:[NOW/DAY-30DAYS TO NOW/DAY+1DAY]` }, + { query: `cm:modifier:${username} OR cm:creator:${username}` }, + { + query: this.recentFileFilters.join(' AND ') + } + ], + fields: this.getFields(sortKey, previousSortKey), + include: ['path', 'properties', 'allowableOperations'], + sort: [ + { + type: 'FIELD', + field: 'cm:modified', + ascending: false + } + ] + }; + const nodes = await this.contentApi.search(query).toPromise(); + const entries = nodes.list.entries.map((obj) => obj.entry); + if (isClient) { + if (previousSortKey) { + this.sort(entries, previousSortKey, previousSortDir); + } + this.sort(entries, sortKey, sortDirection); + } + return entries.map((entry) => entry.id); + } + return []; + } + + /** + * Get the root field name from the property path. + * Example: 'property1.some.child.property' => 'property1' + * + * @param path Property path + */ + getRootField(path: string) { + if (path) { + return path.split('.')[0]; + } + return path; + } + + private sort(items: any[], key: string, direction: string) { + const options: Intl.CollatorOptions = {}; + if (key.includes('sizeInBytes') || key === 'name') { + options.numeric = true; + } + + items.sort((a: any, b: any) => { + let left = ObjectUtils.getValue(a, key) ?? ''; + left = left instanceof Date ? left.valueOf().toString() : left.toString(); + + let right = ObjectUtils.getValue(b, key) ?? ''; + right = right instanceof Date ? right.valueOf().toString() : right.toString(); + + return direction === 'asc' || direction === 'ASC' + ? left.localeCompare(right, undefined, options) + : right.localeCompare(left, undefined, options); + }); + } + + private getFields(sortKey: string, previousSortKey?: string) { + return ['id', this.getRootField(sortKey), this.getRootField(previousSortKey)]; + } + + private getSortKeyDir(source: string) { + const previousSortKey = this.preferences.get(`${source}.sorting.previousKey`); + const previousSortDir = this.preferences.get(`${source}.sorting.previousDirection`); + const sortKey = this.preferences.get(`${source}.sorting.key`) || this.getDefaults(source)[0]; + const sortDirection = this.preferences.get(`${source}.sorting.direction`) || this.getDefaults(source)[1]; + return [sortKey, sortDirection, previousSortKey, previousSortDir]; + } + + private getDefaults(source: string) { + if (source === 'personal-files') { + return ['name', 'asc']; + } else if (source === 'libraries') { + return ['title', 'asc']; + } else { + return ['modifiedAt', 'desc']; + } + } +} diff --git a/projects/aca-content/viewer/src/lib/viewer.module.ts b/projects/aca-content/viewer/src/lib/viewer.module.ts index c954bfd5a4..48948367bb 100644 --- a/projects/aca-content/viewer/src/lib/viewer.module.ts +++ b/projects/aca-content/viewer/src/lib/viewer.module.ts @@ -24,6 +24,7 @@ import { NgModule } from '@angular/core'; import { AcaViewerComponent } from './components/viewer/viewer.component'; +import { PreviewComponent } from './components/preview/preview.component'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ @@ -38,7 +39,7 @@ const routes: Routes = [ ]; @NgModule({ - imports: [RouterModule.forChild(routes), AcaViewerComponent], - exports: [AcaViewerComponent] + imports: [RouterModule.forChild(routes), AcaViewerComponent, PreviewComponent], + exports: [AcaViewerComponent, PreviewComponent] }) export class AcaViewerModule {} diff --git a/projects/aca-content/viewer/src/public-api.ts b/projects/aca-content/viewer/src/public-api.ts index 79d7449f98..21c3826582 100644 --- a/projects/aca-content/viewer/src/public-api.ts +++ b/projects/aca-content/viewer/src/public-api.ts @@ -27,4 +27,5 @@ */ export * from './lib/components/viewer/viewer.component'; +export * from './lib/components/preview/preview.component'; export * from './lib/viewer.module'; diff --git a/projects/aca-shared/src/lib/components/document-base-page/document-base-page.component.ts b/projects/aca-shared/src/lib/components/document-base-page/document-base-page.component.ts index 660a6afa7c..fe17f45c29 100644 --- a/projects/aca-shared/src/lib/components/document-base-page/document-base-page.component.ts +++ b/projects/aca-shared/src/lib/components/document-base-page/document-base-page.component.ts @@ -25,7 +25,7 @@ import { DocumentListComponent, ShareDataRow, UploadService } from '@alfresco/adf-content-services'; import { ShowHeaderMode } from '@alfresco/adf-core'; import { ContentActionRef, DocumentListPresetRef, SelectionState } from '@alfresco/adf-extensions'; -import { OnDestroy, OnInit, OnChanges, ViewChild, SimpleChanges, Directive, inject } from '@angular/core'; +import { OnDestroy, OnInit, OnChanges, ViewChild, SimpleChanges, Directive, inject, HostListener } from '@angular/core'; import { Store } from '@ngrx/store'; import { NodeEntry, Node, NodePaging } from '@alfresco/js-api'; import { Observable, Subject, Subscription } from 'rxjs'; @@ -207,6 +207,7 @@ export abstract class PageComponent implements OnInit, OnDestroy, OnChanges { return location.href.includes('viewer:view'); } + @HostListener('sorting-changed', ['$event']) onSortingChanged(event: any) { this.filterSorting = event.detail.key + '-' + event.detail.direction; } From 5a547c7d1784fcd2d6581d3b492b54dab6f5e73b Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Thu, 14 Mar 2024 12:49:57 +0100 Subject: [PATCH 03/10] [ACA-4728] remove duplicated license --- .../viewer/viewer.component.spec.ts | 24 ------------------- 1 file changed, 24 deletions(-) diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts index a3b1f3b4d3..0526016563 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts @@ -22,30 +22,6 @@ * from Hyland Software. If not, see . */ -/*! - * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. - * - * Alfresco Example Content Application - * - * This file is part of the Alfresco Example Content Application. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * The Alfresco Example Content Application is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * The Alfresco Example Content Application is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * from Hyland Software. If not, see . - */ - import { Router, ActivatedRoute } from '@angular/router'; import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing'; import { From f87500c8f08c59f88f67b9add56ebc4b8f78d4cf Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Thu, 14 Mar 2024 18:52:05 +0100 Subject: [PATCH 04/10] [ACA-4728] add missing imports --- .../viewer/src/lib/components/viewer/viewer.component.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts index 0526016563..09833bc9ee 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts @@ -33,12 +33,12 @@ import { PipeModule } from '@alfresco/adf-core'; import { UploadService, NodesApiService, DiscoveryApiService } from '@alfresco/adf-content-services'; -import { AppState, ClosePreviewAction, ReloadDocumentListAction, ViewNodeAction } from '@alfresco/aca-shared/store'; +import { AppState, ClosePreviewAction, RefreshPreviewAction, ReloadDocumentListAction, ViewNodeAction } from '@alfresco/aca-shared/store'; import { AcaViewerComponent } from './viewer.component'; import { BehaviorSubject, Observable, of, throwError } from 'rxjs'; import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; import { Store, StoreModule } from '@ngrx/store'; -import { RepositoryInfo, VersionInfo } from '@alfresco/js-api'; +import { RepositoryInfo, VersionInfo, Node } from '@alfresco/js-api'; import { AcaViewerModule } from '../../viewer.module'; import { TranslateModule } from '@ngx-translate/core'; import { RouterTestingModule } from '@angular/router/testing'; From 4b53dfd748a738a1f1d98b965636fc1a9a5db06a Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Mon, 18 Mar 2024 20:12:51 +0100 Subject: [PATCH 05/10] [ACA-4728] address comments, improve initial sorting setting, improve tests, reduce duplication --- .../lib/directives/document-list.directive.ts | 35 ++-- .../preview/preview.component.spec.ts | 190 ++++++++---------- .../components/preview/preview.component.ts | 11 +- .../viewer/viewer.component.spec.ts | 90 ++++----- .../lib/components/viewer/viewer.component.ts | 15 +- .../src/lib/services/viewer.service.spec.ts | 27 +-- .../viewer/src/lib/services/viewer.service.ts | 117 ++++------- 7 files changed, 212 insertions(+), 273 deletions(-) diff --git a/projects/aca-content/src/lib/directives/document-list.directive.ts b/projects/aca-content/src/lib/directives/document-list.directive.ts index 3012114ce3..521c838ebd 100644 --- a/projects/aca-content/src/lib/directives/document-list.directive.ts +++ b/projects/aca-content/src/lib/directives/document-list.directive.ts @@ -78,12 +78,11 @@ export class DocumentListDirective implements OnInit, OnDestroy { this.documentList.setColumnsOrder = JSON.parse(this.preferences.get(`${this.sortingPreferenceKey}.columns.order`)); } - this.preferences.set(`${this.sortingPreferenceKey}.sorting.mode`, this.documentList.sortingMode); - - const current = this.documentList.sorting; - const key = this.preferences.get(`${this.sortingPreferenceKey}.sorting.key`, current[0]); - const direction = this.preferences.get(`${this.sortingPreferenceKey}.sorting.direction`, current[1]); - this.setSorting(key, direction); + const mode = this.documentList.sortingMode; + this.preferences.set(`${this.sortingPreferenceKey}.sorting.mode`, mode); + if (mode === 'server') { + this.restoreSorting(); + } } this.documentList.ready @@ -155,9 +154,7 @@ export class DocumentListDirective implements OnInit, OnDestroy { onReady() { this.updateSelection(); - if (this.documentList.sortingMode === 'client' && this.preferences.hasItem(`${this.sortingPreferenceKey}.sorting.previousKey`)) { - this.restoreSorting(); - } + this.restoreSorting(); } private updateSelection() { @@ -204,14 +201,20 @@ export class DocumentListDirective implements OnInit, OnDestroy { private restoreSorting() { const [previousKey, previousDir] = [ - this.preferences.get(`${this.sortingPreferenceKey}.sorting.previousKey`), - this.preferences.get(`${this.sortingPreferenceKey}.sorting.previousDirection`) + this.preferences.get(`${this.sortingPreferenceKey}.sorting.previousKey`, null), + this.preferences.get(`${this.sortingPreferenceKey}.sorting.previousDirection`, null) ]; - const [currentKey, currentDir] = Array.isArray(this.documentList.sorting) - ? this.documentList.sorting - : [this.documentList.sorting.key, this.documentList.sorting.direction]; - this.setSorting(previousKey, previousDir); - this.setSorting(currentKey, currentDir); + const [currentKey, currentDir] = [ + this.preferences.get(`${this.sortingPreferenceKey}.sorting.key`, null), + this.preferences.get(`${this.sortingPreferenceKey}.sorting.direction`, null) + ]; + + if (previousKey) { + this.setSorting(previousKey, previousDir); + } + if (currentKey) { + this.setSorting(currentKey, currentDir); + } } } diff --git a/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts index cfaaf75bd9..19807262c8 100644 --- a/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts @@ -90,6 +90,8 @@ export const INITIAL_APP_STATE: AppState = { } as any }; +const clickEvent = new MouseEvent('click'); + describe('PreviewComponent', () => { let fixture: ComponentFixture; let component: PreviewComponent; @@ -167,143 +169,121 @@ describe('PreviewComponent', () => { store = TestBed.inject(Store); }); - it('should navigate to previous node in sub-folder', () => { - spyOn(router, 'navigate').and.stub(); - const clickEvent = new MouseEvent('click'); - - component.previewLocation = 'personal-files'; - component.folderId = 'folder1'; - component.previousNodeId = 'previous1'; - component.onNavigateBefore(clickEvent); - - expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1', 'preview', 'previous1']); - }); - - it('should navigate back to previous node in the root path', () => { - spyOn(router, 'navigate').and.stub(); - const clickEvent = new MouseEvent('click'); - - component.previewLocation = 'personal-files'; - component.folderId = null; - component.previousNodeId = 'previous1'; - component.onNavigateBefore(clickEvent); - - expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'previous1']); - }); - - it('should not navigate back if node unset', () => { - spyOn(router, 'navigate').and.stub(); - const clickEvent = new MouseEvent('click'); - - component.previousNodeId = null; - component.onNavigateBefore(clickEvent); + describe('Navigation', () => { + beforeEach(() => { + spyOn(router, 'navigate').and.stub(); + }); - expect(router.navigate).not.toHaveBeenCalled(); - }); + describe('From personal-files', () => { + beforeEach(() => { + component.previewLocation = 'personal-files'; + }); - it('should navigate to next node in sub-folder', () => { - spyOn(router, 'navigate').and.stub(); - const clickEvent = new MouseEvent('click'); + it('should navigate to previous node in sub-folder', () => { + component.folderId = 'folder1'; + component.previousNodeId = 'previous1'; + component.onNavigateBefore(clickEvent); - component.previewLocation = 'personal-files'; - component.folderId = 'folder1'; - component.nextNodeId = 'next1'; - component.onNavigateNext(clickEvent); + expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1', 'preview', 'previous1']); + }); - expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1', 'preview', 'next1']); - }); + it('should navigate back to previous node in the root path', () => { + component.folderId = null; + component.previousNodeId = 'previous1'; + component.onNavigateBefore(clickEvent); - it('should navigate to next node in the root path', () => { - spyOn(router, 'navigate').and.stub(); - const clickEvent = new MouseEvent('click'); + expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'previous1']); + }); - component.previewLocation = 'personal-files'; - component.folderId = null; - component.nextNodeId = 'next1'; - component.onNavigateNext(clickEvent); + it('should navigate to next node in sub-folder', () => { + component.folderId = 'folder1'; + component.nextNodeId = 'next1'; - expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'next1']); - }); + component.onNavigateNext(clickEvent); - it('should not navigate back if node unset', () => { - spyOn(router, 'navigate').and.stub(); - const clickEvent = new MouseEvent('click'); + expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1', 'preview', 'next1']); + }); - component.nextNodeId = null; - component.onNavigateNext(clickEvent); + it('should navigate to next node in the root path', () => { + component.folderId = null; + component.nextNodeId = 'next1'; - expect(router.navigate).not.toHaveBeenCalled(); - }); + component.onNavigateNext(clickEvent); - it('should generate preview path for a folder only', () => { - component.previewLocation = 'personal-files'; + expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'next1']); + }); + }); - expect(component.getPreviewPath('folder1', null)).toEqual(['personal-files', 'folder1']); - }); + it('should not navigate to nearest nodes if node unset', () => { + component.previousNodeId = null; + component.nextNodeId = null; - it('should generate preview path for a folder and a node', () => { - component.previewLocation = 'personal-files'; + component.onNavigateBefore(clickEvent); + component.onNavigateNext(clickEvent); - expect(component.getPreviewPath('folder1', 'node1')).toEqual(['personal-files', 'folder1', 'preview', 'node1']); - }); + expect(router.navigate).not.toHaveBeenCalled(); + }); - it('should generate preview path for a node only', () => { - component.previewLocation = 'personal-files'; + it('should navigate back to root path upon close', () => { + component.routesSkipNavigation = []; + component.previewLocation = 'libraries'; + component.folderId = null; - expect(component.getPreviewPath(null, 'node1')).toEqual(['personal-files', 'preview', 'node1']); - }); + component.onVisibilityChanged(false); - it('should generate preview for the location only', () => { - component.previewLocation = 'personal-files'; + expect(router.navigate).toHaveBeenCalledWith(['libraries', {}]); + }); - expect(component.getPreviewPath(null, null)).toEqual(['personal-files']); - }); + it('should navigate back to folder path upon close', () => { + component.routesSkipNavigation = []; + component.previewLocation = 'libraries'; + component.folderId = 'site1'; - it('should navigate back to root path upon close', () => { - spyOn(router, 'navigate').and.stub(); + component.onVisibilityChanged(false); - component.routesSkipNavigation = []; - component.previewLocation = 'libraries'; - component.folderId = null; + expect(router.navigate).toHaveBeenCalledWith(['libraries', {}, 'site1']); + }); - component.onVisibilityChanged(false); + it('should not navigate to root path for certain routes upon close', () => { + component.routesSkipNavigation = ['shared']; + component.previewLocation = 'shared'; + component.folderId = 'folder1'; - expect(router.navigate).toHaveBeenCalledWith(['libraries', {}]); - }); + component.onVisibilityChanged(false); - it('should navigate back to folder path upon close', () => { - spyOn(router, 'navigate').and.stub(); + expect(router.navigate).toHaveBeenCalledWith(['shared', {}]); + }); - component.routesSkipNavigation = []; - component.previewLocation = 'libraries'; - component.folderId = 'site1'; + it('should not navigate back if viewer is still visible', () => { + component.routesSkipNavigation = []; + component.previewLocation = 'shared'; - component.onVisibilityChanged(false); + component.onVisibilityChanged(true); - expect(router.navigate).toHaveBeenCalledWith(['libraries', {}, 'site1']); + expect(router.navigate).not.toHaveBeenCalled(); + }); }); - it('should not navigate to root path for certain routes upon close', () => { - spyOn(router, 'navigate').and.stub(); - - component.routesSkipNavigation = ['shared']; - component.previewLocation = 'shared'; - component.folderId = 'folder1'; - - component.onVisibilityChanged(false); - - expect(router.navigate).toHaveBeenCalledWith(['shared', {}]); - }); + describe('Generate paths', () => { + beforeEach(() => { + component.previewLocation = 'personal-files'; + }); - it('should not navigate back if viewer is still visible', () => { - spyOn(router, 'navigate').and.stub(); + it('should generate preview path for a folder only', () => { + expect(component.getPreviewPath('folder1', null)).toEqual(['personal-files', 'folder1']); + }); - component.routesSkipNavigation = []; - component.previewLocation = 'shared'; + it('should generate preview path for a folder and a node', () => { + expect(component.getPreviewPath('folder1', 'node1')).toEqual(['personal-files', 'folder1', 'preview', 'node1']); + }); - component.onVisibilityChanged(true); + it('should generate preview path for a node only', () => { + expect(component.getPreviewPath(null, 'node1')).toEqual(['personal-files', 'preview', 'node1']); + }); - expect(router.navigate).not.toHaveBeenCalled(); + it('should generate preview for the location only', () => { + expect(component.getPreviewPath(null, null)).toEqual(['personal-files']); + }); }); it('should enable multiple document navigation from route data', () => { diff --git a/projects/aca-content/viewer/src/lib/components/preview/preview.component.ts b/projects/aca-content/viewer/src/lib/components/preview/preview.component.ts index 6478a7b514..47025703a4 100644 --- a/projects/aca-content/viewer/src/lib/components/preview/preview.component.ts +++ b/projects/aca-content/viewer/src/lib/components/preview/preview.component.ts @@ -36,7 +36,7 @@ import { ToolbarMenuItemComponent, ToolbarComponent } from '@alfresco/aca-shared'; -import { ContentActionRef, ViewerExtensionRef } from '@alfresco/adf-extensions'; +import { ContentActionRef } from '@alfresco/adf-extensions'; import { from } from 'rxjs'; import { Actions, ofType } from '@ngrx/effects'; import { AlfrescoViewerModule, NodesApiService } from '@alfresco/adf-content-services'; @@ -52,7 +52,6 @@ import { ViewerService } from '../../services/viewer.service'; host: { class: 'app-preview' } }) export class PreviewComponent extends PageComponent implements OnInit, OnDestroy { - contentExtensions: Array = []; folderId: string = null; navigateBackAsClose = false; navigateMultiple = false; @@ -154,10 +153,12 @@ export class PreviewComponent extends PageComponent implements OnInit, OnDestroy this.store.dispatch(new SetSelectedNodesAction([{ entry: this.node }])); if (this.node?.isFile) { - const nearest = await this.viewerService.getNearestNodes(this.node.id, this.node.parentId, this.navigateSource); - this.previousNodeId = nearest.left; - this.nextNodeId = nearest.right; this.nodeId = this.node.id; + if (this.navigateMultiple) { + const nearest = await this.viewerService.getNearestNodes(this.node.id, this.node.parentId, this.navigateSource); + this.previousNodeId = nearest.left; + this.nextNodeId = nearest.right; + } return; } await this.router.navigate([this.previewLocation, id]); diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts index 09833bc9ee..e72c8f6cc2 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts @@ -33,9 +33,9 @@ import { PipeModule } from '@alfresco/adf-core'; import { UploadService, NodesApiService, DiscoveryApiService } from '@alfresco/adf-content-services'; -import { AppState, ClosePreviewAction, RefreshPreviewAction, ReloadDocumentListAction, ViewNodeAction } from '@alfresco/aca-shared/store'; +import { ClosePreviewAction, RefreshPreviewAction, ReloadDocumentListAction, ViewNodeAction } from '@alfresco/aca-shared/store'; import { AcaViewerComponent } from './viewer.component'; -import { BehaviorSubject, Observable, of, throwError } from 'rxjs'; +import { BehaviorSubject, Observable, of } from 'rxjs'; import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; import { Store, StoreModule } from '@ngrx/store'; import { RepositoryInfo, VersionInfo, Node } from '@alfresco/js-api'; @@ -45,6 +45,7 @@ import { RouterTestingModule } from '@angular/router/testing'; import { HttpClientModule } from '@angular/common/http'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { EffectsModule } from '@ngrx/effects'; +import { INITIAL_APP_STATE } from '../preview/preview.component.spec'; class DocumentBasePageServiceMock extends DocumentBasePageService { canUpdateNode(): boolean { @@ -55,40 +56,16 @@ class DocumentBasePageServiceMock extends DocumentBasePageService { } } -export const INITIAL_APP_STATE: AppState = { - appName: 'Alfresco Content Application', - logoPath: 'assets/images/alfresco-logo-white.svg', - customCssPath: '', - webFontPath: '', - sharedUrl: '', - user: { - isAdmin: null, - id: null, - firstName: '', - lastName: '' - }, - selection: { - nodes: [], - libraries: [], - isEmpty: true, - count: 0 - }, - navigation: { - currentFolder: null - }, - currentNodeVersion: null, - infoDrawerOpened: false, - infoDrawerPreview: false, - infoDrawerMetadataAspect: '', - showFacetFilter: true, - fileUploadingDialog: true, - showLoader: false, - repository: { - status: { - isQuickShareEnabled: true - } - } as any -}; +const apiError = `{ +"error": { + "errorKey":"EntityNotFound", + "statusCode":404, + "briefSummary":"The entity with id: someId was not found", + "stackTrace":"not displayed", + "descriptionURL":"some url", + "logId":"some logId" + } +}`; const fakeLocation = 'fakeLocation'; @@ -182,7 +159,7 @@ describe('AcaViewerComponent', () => { expect(component.displayNode).toHaveBeenCalledWith('node1'); }); - it('should not display node when id is missing', async () => { + it('should not navigate to preview location when id is missing', async () => { spyOn(router, 'navigate').and.stub(); spyOn(contentApi, 'getNodeInfo').and.returnValue(of(null)); @@ -206,23 +183,40 @@ describe('AcaViewerComponent', () => { expect(store.dispatch).toHaveBeenCalledWith(new ViewNodeAction('next', { location: fakeLocation })); }); - it('should reload document list and navigate to correct location upon close', async () => { - spyOn(store, 'dispatch'); - spyOn(component, 'navigateToFileLocation').and.callThrough(); - spyOn(component, 'getFileLocation').and.returnValue(fakeLocation); - spyOn(router, 'navigateByUrl').and.returnValue(Promise.resolve(true)); + describe('Navigate back to file location', () => { + beforeEach(async () => { + spyOn(component, 'navigateToFileLocation').and.callThrough(); + component['navigationPath'] = fakeLocation; + spyOn(router, 'navigateByUrl'); + }); + it('should reload document list and navigate to correct location upon close', async () => { + spyOn(store, 'dispatch'); + + component.onViewerVisibilityChanged(); - component.onViewerVisibilityChanged(); + expect(store.dispatch).toHaveBeenCalledWith(new ReloadDocumentListAction()); + expect(component['navigateToFileLocation']).toHaveBeenCalled(); + expect(router.navigateByUrl).toHaveBeenCalledWith(fakeLocation); + }); + + it('should navigate to node location if it is not a file', async () => { + spyOn(contentApi, 'getNodeInfo').and.returnValue( + of({ + isFile: false + } as Node) + ); - expect(store.dispatch).toHaveBeenCalledWith(new ReloadDocumentListAction()); - expect(component['navigateToFileLocation']).toHaveBeenCalled(); - expect(router.navigateByUrl).toHaveBeenCalledWith(fakeLocation); + await component.displayNode('folder1'); + + expect(contentApi.getNodeInfo).toHaveBeenCalledWith('folder1'); + expect(component['navigateToFileLocation']).toHaveBeenCalled(); + expect(router.navigateByUrl).toHaveBeenCalledWith(fakeLocation); + }); }); it('should navigate to original location in case of Alfresco API errors', async () => { component['previewLocation'] = 'personal-files'; - spyOn(contentApi, 'getNodeInfo').and.returnValue(throwError('error')); - spyOn(JSON, 'parse').and.returnValue({ error: { statusCode: '123' } }); + spyOn(contentApi, 'getNodeInfo').and.throwError(apiError); spyOn(router, 'navigate').and.returnValue(Promise.resolve(true)); await component.displayNode('folder1'); diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts index 6bfe1a3194..558b59278f 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.ts @@ -84,7 +84,6 @@ export class AcaViewerComponent implements OnInit, OnDestroy { nodeId: string = null; openWith: ContentActionRef[] = []; previousNodeId: string; - routesSkipNavigation = ['shared', 'recent-files', 'favorites']; selection: SelectionState; showRightSide = false; toolbarActions: ContentActionRef[] = []; @@ -210,20 +209,18 @@ export class AcaViewerComponent implements OnInit, OnDestroy { this.node = await this.contentApi.getNodeInfo(nodeId).toPromise(); this.store.dispatch(new SetSelectedNodesAction([{ entry: this.node }])); this.navigateMultiple = this.extensions.canShowViewerNavigation({ entry: this.node }); - if (!this.navigateMultiple) { - this.nodeId = this.node.id; - this.fileName = this.node.name + this.node?.properties?.['cm:versionLabel']; - return; - } if (this.node?.isFile) { - const nearest = await this.viewerService.getNearestNodes(this.node.id, this.node.parentId, this.navigateSource); this.nodeId = this.node.id; - this.previousNodeId = nearest.left; - this.nextNodeId = nearest.right; this.fileName = this.node.name + this.node?.properties?.['cm:versionLabel']; + if (this.navigateMultiple) { + const nearest = await this.viewerService.getNearestNodes(this.node.id, this.node.parentId, this.navigateSource); + this.previousNodeId = nearest.left; + this.nextNodeId = nearest.right; + } return; } + this.navigateToFileLocation(); } catch (error) { const statusCode = JSON.parse(error.message).error.statusCode; diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts index dd86e22db7..f5303dea13 100644 --- a/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts @@ -34,9 +34,9 @@ import { HttpClientModule } from '@angular/common/http'; const list = { list: { entries: [ - { entry: { id: 'node1', name: 'node 1', title: 'node 1', modifiedAt: new Date(1) } }, - { entry: { id: 'node3', name: 'node 3', title: 'node 3', modifiedAt: new Date(2) } }, - { entry: { id: 'node2', name: 'node 2', title: 'node 2', modifiedAt: new Date(1) } } + { entry: { id: 'node1', name: 'node 1', modifiedAt: new Date(1) } }, + { entry: { id: 'node3', name: 'node 3', modifiedAt: new Date(2) } }, + { entry: { id: 'node2', name: 'node 2', modifiedAt: new Date(1) } } ] } }; @@ -51,6 +51,11 @@ const favoritesList = { } }; +const emptyAdjacent = { + left: null, + right: null +}; + const preferencesNoPrevSortValues = ['client', '', '']; const preferencesCurSortValues = [...preferencesNoPrevSortValues, 'name', 'desc']; const preferencesNoCurSortValues = [...preferencesNoPrevSortValues, '', '']; @@ -137,12 +142,6 @@ describe('ViewerService', () => { expect(ids).toEqual(['node1', 'node2', 'node3']); }); - it('should use default with no sorting for libraries', async () => { - spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); - const ids = await viewerService.getFileIds('libraries', 'folder1'); - expect(ids).toEqual(['node1', 'node2', 'node3']); - }); - it('should use default with no sorting for other sources', async () => { spyOn(contentApi, 'getFavorites').and.returnValue(of(favoritesList as FavoritePaging)); const ids = await viewerService.getFileIds('favorites'); @@ -175,10 +174,12 @@ describe('ViewerService', () => { expect(viewerService.getRootField(null)).toBe(null); }); - it('should return empty nearest nodes for missing node id', async () => { - const nearest = await viewerService.getNearestNodes(null, 'folder1', 'source'); + it('should return empty adjacent nodes for missing node id or wrong source', async () => { + const noNodeId = await viewerService.getNearestNodes(null, 'folder1', 'source'); + const wrongSource = await viewerService.getNearestNodes('id', 'folder1', 'source'); - expect(nearest).toEqual({ left: null, right: null }); + expect(noNodeId).toEqual(emptyAdjacent); + expect(wrongSource).toEqual(emptyAdjacent); }); it('should return empty nearest nodes for missing folder id', async () => { @@ -215,7 +216,7 @@ describe('ViewerService', () => { expect(nearest).toEqual({ left: null, right: null }); }); - it('should require folder id to fetch ids for libraries', async () => { + it('should require folder id to fetch ids for personal-files and libraries', async () => { const ids = await viewerService.getFileIds('libraries', null); expect(ids).toEqual([]); }); diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.ts index 890fffca40..dd127bec82 100644 --- a/projects/aca-content/viewer/src/lib/services/viewer.service.ts +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.ts @@ -23,10 +23,15 @@ */ import { ObjectUtils, UserPreferencesService } from '@alfresco/adf-core'; -import { SearchRequest } from '@alfresco/js-api'; +import { FavoritePaging, Node, NodePaging, SearchRequest, ResultSetPaging, SharedLink, SharedLinkPaging } from '@alfresco/js-api'; import { Injectable } from '@angular/core'; import { ContentApiService } from '@alfresco/aca-shared'; +interface adjacentFiles { + left: string; + right: string; +} + @Injectable({ providedIn: 'root' }) @@ -62,9 +67,10 @@ export class ViewerService { * * @param nodeId Unique identifier of the document node * @param folderId Unique identifier of the containing folder node. + * @param source Data source name. Allowed values are: personal-files, libraries, favorites, shared, recent-files. */ - async getNearestNodes(nodeId: string, folderId: string, source: string): Promise<{ left: string; right: string }> { - const empty = { + async getNearestNodes(nodeId: string, folderId: string, source: string): Promise { + const empty: adjacentFiles = { left: null, right: null }; @@ -79,97 +85,56 @@ export class ViewerService { left: ids[idx - 1] || null, right: ids[idx + 1] || null }; - } else { - return empty; } - } catch { - return empty; - } - } else { - return empty; + } catch {} } + return empty; } /** * Retrieves a list of node identifiers for the folder and data source. * + * @param source Data source name. Allowed values are: personal-files, libraries, favorites, shared, recent-files. * @param folderId Optional parameter containing folder node identifier for 'personal-files' and 'libraries' sources. */ async getFileIds(source: string, folderId?: string): Promise { + if (source === 'libraries') { + source = 'libraries-files'; + } const isClient = this.preferences.get(`${source}.sorting.mode`) === 'client'; const [sortKey, sortDirection, previousSortKey, previousSortDir] = this.getSortKeyDir(source); + let entries: Node[] | SharedLink[] = []; + let nodes: NodePaging | FavoritePaging | SharedLinkPaging | ResultSetPaging; - if (source === 'personal-files' && folderId) { + if (source === 'personal-files' || source === 'libraries-files') { + if (!folderId) { + return []; + } const orderBy = isClient ? null : ['isFolder desc', `${sortKey} ${sortDirection}`]; - const nodes = await this.contentApi + nodes = await this.contentApi .getNodeChildren(folderId, { orderBy: orderBy, fields: this.getFields(sortKey, previousSortKey), where: '(isFile=true)' }) .toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - if (isClient) { - if (previousSortKey) { - this.sort(entries, previousSortKey, previousSortDir); - } - this.sort(entries, sortKey, sortDirection); - } - return entries.map((entry) => entry.id); - } - - if (source === 'libraries' && folderId) { - const nodes = await this.contentApi - .getNodeChildren(folderId, { - fields: this.getFields(sortKey, previousSortKey), - where: '(isFile=true)' - }) - .toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - if (isClient) { - if (previousSortKey) { - this.sort(entries, previousSortKey, previousSortDir); - } - this.sort(entries, sortKey, sortDirection); - } - return entries.map((entry) => entry.id); } if (source === 'favorites') { - const nodes = await this.contentApi + nodes = await this.contentApi .getFavorites('-me-', { where: '(EXISTS(target/file))', fields: ['target'] }) .toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry.target.file); - if (isClient) { - if (previousSortKey) { - this.sort(entries, previousSortKey, previousSortDir); - } - this.sort(entries, sortKey, sortDirection); - } - return entries.map((entry) => entry.id); } if (source === 'shared') { - const nodes = await this.contentApi + nodes = await this.contentApi .findSharedLinks({ fields: ['nodeId', this.getRootField(sortKey)] }) .toPromise(); - - const entries = nodes.list.entries.map((obj) => obj.entry); - if (isClient) { - if (previousSortKey) { - this.sort(entries, previousSortKey, previousSortDir); - } - this.sort(entries, sortKey, sortDirection); - } - return entries.map((entry) => entry.nodeId); } if (source === 'recent-files') { @@ -197,17 +162,17 @@ export class ViewerService { } ] }; - const nodes = await this.contentApi.search(query).toPromise(); - const entries = nodes.list.entries.map((obj) => obj.entry); - if (isClient) { - if (previousSortKey) { - this.sort(entries, previousSortKey, previousSortDir); - } - this.sort(entries, sortKey, sortDirection); + nodes = await this.contentApi.search(query).toPromise(); + } + + entries = nodes.list.entries.map((obj) => obj.entry.target?.file ?? obj.entry); + if (isClient) { + if (previousSortKey) { + this.sort(entries, previousSortKey, previousSortDir); } - return entries.map((entry) => entry.id); + this.sort(entries, sortKey, sortDirection); } - return []; + return entries.map((entry) => entry.id ?? entry.nodeId); } /** @@ -216,20 +181,20 @@ export class ViewerService { * * @param path Property path */ - getRootField(path: string) { + getRootField(path: string): string { if (path) { return path.split('.')[0]; } return path; } - private sort(items: any[], key: string, direction: string) { + private sort(items: Node[] | SharedLink[], key: string, direction: string) { const options: Intl.CollatorOptions = {}; if (key.includes('sizeInBytes') || key === 'name') { options.numeric = true; } - items.sort((a: any, b: any) => { + items.sort((a: Node | SharedLink, b: Node | SharedLink) => { let left = ObjectUtils.getValue(a, key) ?? ''; left = left instanceof Date ? left.valueOf().toString() : left.toString(); @@ -242,11 +207,11 @@ export class ViewerService { }); } - private getFields(sortKey: string, previousSortKey?: string) { + private getFields(sortKey: string, previousSortKey?: string): string[] { return ['id', this.getRootField(sortKey), this.getRootField(previousSortKey)]; } - private getSortKeyDir(source: string) { + private getSortKeyDir(source: string): string[] { const previousSortKey = this.preferences.get(`${source}.sorting.previousKey`); const previousSortDir = this.preferences.get(`${source}.sorting.previousDirection`); const sortKey = this.preferences.get(`${source}.sorting.key`) || this.getDefaults(source)[0]; @@ -254,11 +219,9 @@ export class ViewerService { return [sortKey, sortDirection, previousSortKey, previousSortDir]; } - private getDefaults(source: string) { - if (source === 'personal-files') { + private getDefaults(source: string): string[] { + if (source === 'personal-files' || source === 'libraries-files') { return ['name', 'asc']; - } else if (source === 'libraries') { - return ['title', 'asc']; } else { return ['modifiedAt', 'desc']; } From b0d308c4bc0fd45d60f99d1911660a1e7653b200 Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Tue, 19 Mar 2024 10:32:03 +0100 Subject: [PATCH 06/10] [ACA-4728] further reduce code duplication, remove/replace faulty unit tests --- .../preview/preview.component.spec.ts | 143 +++--------------- .../viewer/viewer.component.spec.ts | 115 ++++---------- .../viewer/src/lib/mock/viewer.mock.ts | 92 +++++++++++ .../src/lib/services/viewer.service.spec.ts | 51 +++---- 4 files changed, 164 insertions(+), 237 deletions(-) create mode 100644 projects/aca-content/viewer/src/lib/mock/viewer.mock.ts diff --git a/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts index 19807262c8..36cbe6736d 100644 --- a/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts @@ -33,62 +33,19 @@ import { PipeModule } from '@alfresco/adf-core'; import { UploadService, NodesApiService, DiscoveryApiService } from '@alfresco/adf-content-services'; -import { AppState, ClosePreviewAction } from '@alfresco/aca-shared/store'; +import { ClosePreviewAction } from '@alfresco/aca-shared/store'; import { PreviewComponent } from './preview.component'; -import { BehaviorSubject, Observable, of, throwError } from 'rxjs'; +import { of, throwError } from 'rxjs'; import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; import { Store, StoreModule } from '@ngrx/store'; -import { Node, RepositoryInfo, VersionInfo } from '@alfresco/js-api'; +import { Node } from '@alfresco/js-api'; import { AcaViewerModule } from '../../viewer.module'; import { TranslateModule } from '@ngx-translate/core'; import { RouterTestingModule } from '@angular/router/testing'; import { HttpClientModule } from '@angular/common/http'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { EffectsModule } from '@ngrx/effects'; - -class DocumentBasePageServiceMock extends DocumentBasePageService { - canUpdateNode(): boolean { - return true; - } - canUploadContent(): boolean { - return true; - } -} - -export const INITIAL_APP_STATE: AppState = { - appName: 'Alfresco Content Application', - logoPath: 'assets/images/alfresco-logo-white.svg', - customCssPath: '', - webFontPath: '', - sharedUrl: '', - user: { - isAdmin: null, - id: null, - firstName: '', - lastName: '' - }, - selection: { - nodes: [], - libraries: [], - isEmpty: true, - count: 0 - }, - navigation: { - currentFolder: null - }, - currentNodeVersion: null, - infoDrawerOpened: false, - infoDrawerPreview: false, - infoDrawerMetadataAspect: '', - showFacetFilter: true, - fileUploadingDialog: true, - showLoader: false, - repository: { - status: { - isQuickShareEnabled: true - } - } as any -}; +import { authenticationServiceMock, discoveryApiServiceMock, DocumentBasePageServiceMock, INITIAL_APP_STATE } from '../../mock/viewer.mock'; const clickEvent = new MouseEvent('click'); @@ -130,30 +87,8 @@ describe('PreviewComponent', () => { { provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }, { provide: TranslationService, useClass: TranslationMock }, { provide: DocumentBasePageService, useVale: new DocumentBasePageServiceMock() }, - { - provide: DiscoveryApiService, - useValue: { - ecmProductInfo$: new BehaviorSubject(null), - getEcmProductInfo: (): Observable => - of( - new RepositoryInfo({ - version: { - major: '10.0.0' - } as VersionInfo - }) - ) - } - }, - { - provide: AuthenticationService, - useValue: { - isEcmLoggedIn: (): boolean => true, - getRedirect: (): string | null => null, - setRedirect() {}, - isOauth: (): boolean => false, - isOAuthWithoutSilentLogin: (): boolean => false - } - } + { provide: DiscoveryApiService, useValue: discoveryApiServiceMock }, + { provide: AuthenticationService, useValue: authenticationServiceMock } ] }); @@ -304,7 +239,7 @@ describe('PreviewComponent', () => { expect(component.navigateMultiple).toBeFalsy(); }); - it('should display document upon init', () => { + it('should set folderId and call displayNode with nodeId upon init', () => { route.params = of({ folderId: 'folder1', nodeId: 'node1' @@ -318,16 +253,6 @@ describe('PreviewComponent', () => { expect(component.displayNode).toHaveBeenCalledWith('node1'); }); - it('should not display node when id is missing', async () => { - spyOn(router, 'navigate').and.stub(); - spyOn(contentApi, 'getNodeInfo').and.returnValue(of(null)); - - await component.displayNode(null); - - expect(contentApi.getNodeInfo).not.toHaveBeenCalled(); - expect(router.navigate).not.toHaveBeenCalled(); - }); - it('should navigate to original location if node not found', async () => { spyOn(router, 'navigate').and.stub(); spyOn(contentApi, 'getNodeInfo').and.returnValue(throwError('error')); @@ -399,6 +324,7 @@ describe('PreviewComponent', () => { store.dispatch(new ClosePreviewAction()); expect(component.navigateToFileLocation).toHaveBeenCalled(); }); + it('should fetch navigation source from route', () => { route.snapshot.data = { navigateSource: 'personal-files' @@ -431,47 +357,24 @@ describe('PreviewComponent', () => { expect(component.navigateSource).toBeNull(); }); - describe('Keyboard navigation', () => { - beforeEach(() => { - component.nextNodeId = 'nextNodeId'; - component.previousNodeId = 'previousNodeId'; - spyOn(router, 'navigate').and.stub(); - }); - - afterEach(() => { - fixture.destroy(); - }); - - it('should not navigate on keyboard event if target is child of sidebar container', () => { - const parent = document.createElement('div'); - parent.className = 'adf-viewer__sidebar'; - - const child = document.createElement('button'); - child.addEventListener('keyup', function (e) { - component.onNavigateNext(e); - }); - parent.appendChild(child); - document.body.appendChild(parent); - - child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowLeft' })); + it('should not navigate on keyboard event if target is child of sidebar container or cdk overlay', () => { + component.nextNodeId = 'node'; + spyOn(router, 'navigate').and.stub(); - expect(router.navigate).not.toHaveBeenCalled(); + const parent = document.createElement('div'); + const child = document.createElement('button'); + child.addEventListener('keyup', function (e) { + component.onNavigateNext(e); }); + parent.appendChild(child); + document.body.appendChild(parent); - it('should not navigate on keyboard event if target is child of cdk overlay', () => { - const parent = document.createElement('div'); - parent.className = 'cdk-overlay-container'; - - const child = document.createElement('button'); - child.addEventListener('keyup', function (e) { - component.onNavigateNext(e); - }); - parent.appendChild(child); - document.body.appendChild(parent); - - child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowLeft' })); + parent.className = 'adf-viewer__sidebar'; + child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' })); + expect(router.navigate).not.toHaveBeenCalled(); - expect(router.navigate).not.toHaveBeenCalled(); - }); + parent.className = 'cdk-overlay-container'; + child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' })); + expect(router.navigate).not.toHaveBeenCalled(); }); }); diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts index e72c8f6cc2..c7555aa709 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts @@ -35,26 +35,17 @@ import { import { UploadService, NodesApiService, DiscoveryApiService } from '@alfresco/adf-content-services'; import { ClosePreviewAction, RefreshPreviewAction, ReloadDocumentListAction, ViewNodeAction } from '@alfresco/aca-shared/store'; import { AcaViewerComponent } from './viewer.component'; -import { BehaviorSubject, Observable, of } from 'rxjs'; +import { of } from 'rxjs'; import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; import { Store, StoreModule } from '@ngrx/store'; -import { RepositoryInfo, VersionInfo, Node } from '@alfresco/js-api'; +import { Node } from '@alfresco/js-api'; import { AcaViewerModule } from '../../viewer.module'; import { TranslateModule } from '@ngx-translate/core'; import { RouterTestingModule } from '@angular/router/testing'; import { HttpClientModule } from '@angular/common/http'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { EffectsModule } from '@ngrx/effects'; -import { INITIAL_APP_STATE } from '../preview/preview.component.spec'; - -class DocumentBasePageServiceMock extends DocumentBasePageService { - canUpdateNode(): boolean { - return true; - } - canUploadContent(): boolean { - return true; - } -} +import { authenticationServiceMock, discoveryApiServiceMock, DocumentBasePageServiceMock, INITIAL_APP_STATE } from '../../mock/viewer.mock'; const apiError = `{ "error": { @@ -107,30 +98,8 @@ describe('AcaViewerComponent', () => { { provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }, { provide: TranslationService, useClass: TranslationMock }, { provide: DocumentBasePageService, useVale: new DocumentBasePageServiceMock() }, - { - provide: DiscoveryApiService, - useValue: { - ecmProductInfo$: new BehaviorSubject(null), - getEcmProductInfo: (): Observable => - of( - new RepositoryInfo({ - version: { - major: '10.0.0' - } as VersionInfo - }) - ) - } - }, - { - provide: AuthenticationService, - useValue: { - isEcmLoggedIn: (): boolean => true, - getRedirect: (): string | null => null, - setRedirect() {}, - isOauth: (): boolean => false, - isOAuthWithoutSilentLogin: (): boolean => false - } - } + { provide: DiscoveryApiService, useValue: discoveryApiServiceMock }, + { provide: AuthenticationService, useValue: authenticationServiceMock } ] }); @@ -146,7 +115,7 @@ describe('AcaViewerComponent', () => { store = TestBed.inject(Store); }); - it('should display document upon init', () => { + it('should set folderId and call displayNode with nodeId upon init', () => { route.params = of({ folderId: 'folder1', nodeId: 'node1' @@ -159,16 +128,6 @@ describe('AcaViewerComponent', () => { expect(component.displayNode).toHaveBeenCalledWith('node1'); }); - it('should not navigate to preview location when id is missing', async () => { - spyOn(router, 'navigate').and.stub(); - spyOn(contentApi, 'getNodeInfo').and.returnValue(of(null)); - - await component.displayNode(null); - - expect(contentApi.getNodeInfo).not.toHaveBeenCalled(); - expect(router.navigate).not.toHaveBeenCalled(); - }); - it('should navigate to next and previous nodes', () => { spyOn(store, 'dispatch'); spyOn(component, 'getFileLocation').and.returnValue(fakeLocation); @@ -183,13 +142,14 @@ describe('AcaViewerComponent', () => { expect(store.dispatch).toHaveBeenCalledWith(new ViewNodeAction('next', { location: fakeLocation })); }); - describe('Navigate back to file location', () => { + describe('Navigate back to node location', () => { beforeEach(async () => { spyOn(component, 'navigateToFileLocation').and.callThrough(); component['navigationPath'] = fakeLocation; - spyOn(router, 'navigateByUrl'); + spyOn(router, 'navigateByUrl').and.stub(); }); - it('should reload document list and navigate to correct location upon close', async () => { + + it('should reload document list and navigate to node location upon close', async () => { spyOn(store, 'dispatch'); component.onViewerVisibilityChanged(); @@ -214,7 +174,7 @@ describe('AcaViewerComponent', () => { }); }); - it('should navigate to original location in case of Alfresco API errors', async () => { + it('should navigate to node location in case of Alfresco API errors', async () => { component['previewLocation'] = 'personal-files'; spyOn(contentApi, 'getNodeInfo').and.throwError(apiError); spyOn(router, 'navigate').and.returnValue(Promise.resolve(true)); @@ -292,48 +252,25 @@ describe('AcaViewerComponent', () => { expect(component.navigateSource).toBe('PERSONAL-FILES'); }); - describe('Keyboard navigation', () => { - beforeEach(() => { - component.nextNodeId = 'nextNodeId'; - component.previousNodeId = 'previousNodeId'; - spyOn(router, 'navigate').and.stub(); - }); - - afterEach(() => { - fixture.destroy(); - }); - - it('should not navigate on keyboard event if target is child of sidebar container', () => { - const parent = document.createElement('div'); - parent.className = 'adf-viewer__sidebar'; - - const child = document.createElement('button'); - child.addEventListener('keyup', function (e) { - component.onNavigateNext(e); - }); - parent.appendChild(child); - document.body.appendChild(parent); - - child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowLeft' })); + it('should not navigate on keyboard event if target is child of sidebar container or cdk overlay', () => { + component.nextNodeId = 'node'; + spyOn(router, 'navigate').and.stub(); - expect(router.navigate).not.toHaveBeenCalled(); + const parent = document.createElement('div'); + const child = document.createElement('button'); + child.addEventListener('keyup', function (e) { + component.onNavigateNext(e); }); + parent.appendChild(child); + document.body.appendChild(parent); - it('should not navigate on keyboard event if target is child of cdk overlay', () => { - const parent = document.createElement('div'); - parent.className = 'cdk-overlay-container'; - - const child = document.createElement('button'); - child.addEventListener('keyup', function (e) { - component.onNavigateNext(e); - }); - parent.appendChild(child); - document.body.appendChild(parent); - - child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowLeft' })); + parent.className = 'adf-viewer__sidebar'; + child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' })); + expect(router.navigate).not.toHaveBeenCalled(); - expect(router.navigate).not.toHaveBeenCalled(); - }); + parent.className = 'cdk-overlay-container'; + child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' })); + expect(router.navigate).not.toHaveBeenCalled(); }); it('should call node update after RefreshPreviewAction is triggered', () => { diff --git a/projects/aca-content/viewer/src/lib/mock/viewer.mock.ts b/projects/aca-content/viewer/src/lib/mock/viewer.mock.ts new file mode 100644 index 0000000000..126b2c48e7 --- /dev/null +++ b/projects/aca-content/viewer/src/lib/mock/viewer.mock.ts @@ -0,0 +1,92 @@ +/*! + * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. + * + * Alfresco Example Content Application + * + * This file is part of the Alfresco Example Content Application. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * The Alfresco Example Content Application is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * The Alfresco Example Content Application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * from Hyland Software. If not, see . + */ + +import { RepositoryInfo, VersionInfo } from '@alfresco/js-api'; +import { BehaviorSubject, Observable, of } from 'rxjs'; +import { DocumentBasePageService } from '@alfresco/aca-shared'; +import { AppState } from '@alfresco/aca-shared/store'; + +export class DocumentBasePageServiceMock extends DocumentBasePageService { + canUpdateNode(): boolean { + return true; + } + canUploadContent(): boolean { + return true; + } +} + +export const INITIAL_APP_STATE: AppState = { + appName: 'Alfresco Content Application', + logoPath: 'assets/images/alfresco-logo-white.svg', + customCssPath: '', + webFontPath: '', + sharedUrl: '', + user: { + isAdmin: null, + id: null, + firstName: '', + lastName: '' + }, + selection: { + nodes: [], + libraries: [], + isEmpty: true, + count: 0 + }, + navigation: { + currentFolder: null + }, + currentNodeVersion: null, + infoDrawerOpened: false, + infoDrawerPreview: false, + infoDrawerMetadataAspect: '', + showFacetFilter: true, + fileUploadingDialog: true, + showLoader: false, + repository: { + status: { + isQuickShareEnabled: true + } + } as any +}; + +export const authenticationServiceMock = { + isEcmLoggedIn: (): boolean => true, + getRedirect: (): string | null => null, + setRedirect() {}, + isOauth: (): boolean => false, + isOAuthWithoutSilentLogin: (): boolean => false +}; + +export const discoveryApiServiceMock = { + ecmProductInfo$: new BehaviorSubject(null), + getEcmProductInfo: (): Observable => + of( + new RepositoryInfo({ + version: { + major: '10.0.0' + } as VersionInfo + }) + ) +}; diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts index f5303dea13..668a621ae8 100644 --- a/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts @@ -26,7 +26,7 @@ import { TestBed } from '@angular/core/testing'; import { TranslationMock, TranslationService, UserPreferencesService } from '@alfresco/adf-core'; import { ContentApiService } from '@alfresco/aca-shared'; import { FavoritePaging, NodePaging, SharedLinkPaging } from '@alfresco/js-api'; -import { ViewerService } from '../services/viewer.service'; +import { ViewerService } from './viewer.service'; import { of } from 'rxjs'; import { TranslateModule } from '@ngx-translate/core'; import { HttpClientModule } from '@angular/common/http'; @@ -59,6 +59,8 @@ const emptyAdjacent = { const preferencesNoPrevSortValues = ['client', '', '']; const preferencesCurSortValues = [...preferencesNoPrevSortValues, 'name', 'desc']; const preferencesNoCurSortValues = [...preferencesNoPrevSortValues, '', '']; +const resultDesc = ['node3', 'node2', 'node1']; +const resultAsc = ['node1', 'node2', 'node3']; describe('ViewerService', () => { let preferences: UserPreferencesService; @@ -78,25 +80,23 @@ describe('ViewerService', () => { describe('Sorting for different sources', () => { beforeEach(() => { - spyOn(preferences, 'get').and.returnValues(...preferencesCurSortValues); + spyOn(preferences, 'get').and.returnValues(...preferencesCurSortValues, ...preferencesCurSortValues); }); - it('should fetch and sort file ids for personal files', async () => { + it('should fetch and sort file ids for personal files and libraries', async () => { spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); - const ids = await viewerService.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node3', 'node2', 'node1']); - }); - it('should fetch and sort file ids for libraries', async () => { - spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); - const ids = await viewerService.getFileIds('libraries', 'folder1'); - expect(ids).toEqual(['node3', 'node2', 'node1']); + const idsPersonal = await viewerService.getFileIds('personal-files', 'folder1'); + const idsLibraries = await viewerService.getFileIds('libraries', 'folder1'); + + expect(idsPersonal).toEqual(resultDesc); + expect(idsLibraries).toEqual(resultDesc); }); it('should fetch and sort file ids for favorites', async () => { spyOn(contentApi, 'getFavorites').and.returnValue(of(favoritesList as FavoritePaging)); - const ids = await viewerService.getFileIds('favorites'); - expect(ids).toEqual(['node3', 'node2', 'node1']); + const idsFavorites = await viewerService.getFileIds('favorites'); + expect(idsFavorites).toEqual(resultDesc); }); it('should fetch and sort file ids for shared', async () => { @@ -126,27 +126,22 @@ describe('ViewerService', () => { } } as SharedLinkPaging) ); - const ids = await viewerService.getFileIds('shared'); - expect(ids).toEqual(['node3', 'node2', 'node1']); + const idsShared = await viewerService.getFileIds('shared'); + expect(idsShared).toEqual(resultDesc); }); }); - describe('default sorting for different sources', () => { - beforeEach(() => { - spyOn(preferences, 'get').and.returnValues(...preferencesNoCurSortValues); - }); + it('should use default with no sorting for personal-files and other sources', async () => { + spyOn(preferences, 'get').and.returnValues(...preferencesNoCurSortValues); - it('should use default with no sorting for personal-files', async () => { - spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); - const ids = await viewerService.getFileIds('personal-files', 'folder1'); - expect(ids).toEqual(['node1', 'node2', 'node3']); - }); + spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging)); + const idsFiles = await viewerService.getFileIds('personal-files', 'folder1'); - it('should use default with no sorting for other sources', async () => { - spyOn(contentApi, 'getFavorites').and.returnValue(of(favoritesList as FavoritePaging)); - const ids = await viewerService.getFileIds('favorites'); - expect(ids).toEqual(['node1', 'node2', 'node3']); - }); + spyOn(contentApi, 'getFavorites').and.returnValue(of(favoritesList as FavoritePaging)); + const idsOther = await viewerService.getFileIds('favorites'); + + expect(idsFiles).toEqual(resultAsc); + expect(idsOther).toEqual(resultAsc); }); describe('Other sorting scenarios', () => { From f86f0ff685562c37c9b6af1317ca587eb611cdae Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Tue, 19 Mar 2024 14:18:30 +0100 Subject: [PATCH 07/10] [ACA-4728] move reusable unit test config to testing module --- .../preview/preview.component.spec.ts | 56 +++------ .../viewer/viewer.component.spec.ts | 56 +++------ .../viewer/src/lib/mock/viewer.mock.ts | 92 -------------- .../document-base-page.spec.ts | 119 ++---------------- .../src/lib/testing/lib-testing-module.ts | 27 +++- 5 files changed, 66 insertions(+), 284 deletions(-) delete mode 100644 projects/aca-content/viewer/src/lib/mock/viewer.mock.ts diff --git a/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts index 36cbe6736d..4c6dfc1f91 100644 --- a/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/preview/preview.component.spec.ts @@ -24,28 +24,22 @@ import { Router, ActivatedRoute } from '@angular/router'; import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing'; -import { - AlfrescoApiService, - AlfrescoApiServiceMock, - AuthenticationService, - TranslationMock, - TranslationService, - PipeModule -} from '@alfresco/adf-core'; +import { AuthenticationService } from '@alfresco/adf-core'; import { UploadService, NodesApiService, DiscoveryApiService } from '@alfresco/adf-content-services'; import { ClosePreviewAction } from '@alfresco/aca-shared/store'; import { PreviewComponent } from './preview.component'; import { of, throwError } from 'rxjs'; -import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; -import { Store, StoreModule } from '@ngrx/store'; +import { + ContentApiService, + AppHookService, + DocumentBasePageService, + LibTestingModule, + discoveryApiServiceMockValue, + DocumentBasePageServiceMock +} from '@alfresco/aca-shared'; +import { Store } from '@ngrx/store'; import { Node } from '@alfresco/js-api'; import { AcaViewerModule } from '../../viewer.module'; -import { TranslateModule } from '@ngx-translate/core'; -import { RouterTestingModule } from '@angular/router/testing'; -import { HttpClientModule } from '@angular/common/http'; -import { NoopAnimationsModule } from '@angular/platform-browser/animations'; -import { EffectsModule } from '@ngrx/effects'; -import { authenticationServiceMock, discoveryApiServiceMock, DocumentBasePageServiceMock, INITIAL_APP_STATE } from '../../mock/viewer.mock'; const clickEvent = new MouseEvent('click'); @@ -62,33 +56,11 @@ describe('PreviewComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ - AcaViewerModule, - NoopAnimationsModule, - HttpClientModule, - RouterTestingModule, - TranslateModule.forRoot(), - StoreModule.forRoot( - { app: (state) => state }, - { - initialState: { - app: INITIAL_APP_STATE - }, - runtimeChecks: { - strictStateImmutability: false, - strictActionImmutability: false - } - } - ), - EffectsModule.forRoot([]), - PipeModule - ], + imports: [LibTestingModule, AcaViewerModule], providers: [ - { provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }, - { provide: TranslationService, useClass: TranslationMock }, - { provide: DocumentBasePageService, useVale: new DocumentBasePageServiceMock() }, - { provide: DiscoveryApiService, useValue: discoveryApiServiceMock }, - { provide: AuthenticationService, useValue: authenticationServiceMock } + { provide: DocumentBasePageService, useValue: DocumentBasePageServiceMock }, + { provide: DiscoveryApiService, useValue: discoveryApiServiceMockValue }, + { provide: AuthenticationService, useValue: {} } ] }); diff --git a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts index c7555aa709..816086e36e 100644 --- a/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts +++ b/projects/aca-content/viewer/src/lib/components/viewer/viewer.component.spec.ts @@ -24,28 +24,22 @@ import { Router, ActivatedRoute } from '@angular/router'; import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing'; -import { - AlfrescoApiService, - AlfrescoApiServiceMock, - AuthenticationService, - TranslationMock, - TranslationService, - PipeModule -} from '@alfresco/adf-core'; +import { AuthenticationService } from '@alfresco/adf-core'; import { UploadService, NodesApiService, DiscoveryApiService } from '@alfresco/adf-content-services'; import { ClosePreviewAction, RefreshPreviewAction, ReloadDocumentListAction, ViewNodeAction } from '@alfresco/aca-shared/store'; import { AcaViewerComponent } from './viewer.component'; import { of } from 'rxjs'; -import { ContentApiService, AppHookService, DocumentBasePageService } from '@alfresco/aca-shared'; -import { Store, StoreModule } from '@ngrx/store'; +import { + ContentApiService, + AppHookService, + DocumentBasePageService, + LibTestingModule, + discoveryApiServiceMockValue, + DocumentBasePageServiceMock +} from '@alfresco/aca-shared'; +import { Store } from '@ngrx/store'; import { Node } from '@alfresco/js-api'; import { AcaViewerModule } from '../../viewer.module'; -import { TranslateModule } from '@ngx-translate/core'; -import { RouterTestingModule } from '@angular/router/testing'; -import { HttpClientModule } from '@angular/common/http'; -import { NoopAnimationsModule } from '@angular/platform-browser/animations'; -import { EffectsModule } from '@ngrx/effects'; -import { authenticationServiceMock, discoveryApiServiceMock, DocumentBasePageServiceMock, INITIAL_APP_STATE } from '../../mock/viewer.mock'; const apiError = `{ "error": { @@ -73,33 +67,11 @@ describe('AcaViewerComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ - AcaViewerModule, - NoopAnimationsModule, - HttpClientModule, - RouterTestingModule.withRoutes([]), - TranslateModule.forRoot(), - StoreModule.forRoot( - { app: (state) => state }, - { - initialState: { - app: INITIAL_APP_STATE - }, - runtimeChecks: { - strictStateImmutability: false, - strictActionImmutability: false - } - } - ), - EffectsModule.forRoot([]), - PipeModule - ], + imports: [LibTestingModule, AcaViewerModule], providers: [ - { provide: AlfrescoApiService, useClass: AlfrescoApiServiceMock }, - { provide: TranslationService, useClass: TranslationMock }, - { provide: DocumentBasePageService, useVale: new DocumentBasePageServiceMock() }, - { provide: DiscoveryApiService, useValue: discoveryApiServiceMock }, - { provide: AuthenticationService, useValue: authenticationServiceMock } + { provide: DocumentBasePageService, useValue: DocumentBasePageServiceMock }, + { provide: DiscoveryApiService, useValue: discoveryApiServiceMockValue }, + { provide: AuthenticationService, useValue: {} } ] }); diff --git a/projects/aca-content/viewer/src/lib/mock/viewer.mock.ts b/projects/aca-content/viewer/src/lib/mock/viewer.mock.ts deleted file mode 100644 index 126b2c48e7..0000000000 --- a/projects/aca-content/viewer/src/lib/mock/viewer.mock.ts +++ /dev/null @@ -1,92 +0,0 @@ -/*! - * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. - * - * Alfresco Example Content Application - * - * This file is part of the Alfresco Example Content Application. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * The Alfresco Example Content Application is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * The Alfresco Example Content Application is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * from Hyland Software. If not, see . - */ - -import { RepositoryInfo, VersionInfo } from '@alfresco/js-api'; -import { BehaviorSubject, Observable, of } from 'rxjs'; -import { DocumentBasePageService } from '@alfresco/aca-shared'; -import { AppState } from '@alfresco/aca-shared/store'; - -export class DocumentBasePageServiceMock extends DocumentBasePageService { - canUpdateNode(): boolean { - return true; - } - canUploadContent(): boolean { - return true; - } -} - -export const INITIAL_APP_STATE: AppState = { - appName: 'Alfresco Content Application', - logoPath: 'assets/images/alfresco-logo-white.svg', - customCssPath: '', - webFontPath: '', - sharedUrl: '', - user: { - isAdmin: null, - id: null, - firstName: '', - lastName: '' - }, - selection: { - nodes: [], - libraries: [], - isEmpty: true, - count: 0 - }, - navigation: { - currentFolder: null - }, - currentNodeVersion: null, - infoDrawerOpened: false, - infoDrawerPreview: false, - infoDrawerMetadataAspect: '', - showFacetFilter: true, - fileUploadingDialog: true, - showLoader: false, - repository: { - status: { - isQuickShareEnabled: true - } - } as any -}; - -export const authenticationServiceMock = { - isEcmLoggedIn: (): boolean => true, - getRedirect: (): string | null => null, - setRedirect() {}, - isOauth: (): boolean => false, - isOAuthWithoutSilentLogin: (): boolean => false -}; - -export const discoveryApiServiceMock = { - ecmProductInfo$: new BehaviorSubject(null), - getEcmProductInfo: (): Observable => - of( - new RepositoryInfo({ - version: { - major: '10.0.0' - } as VersionInfo - }) - ) -}; diff --git a/projects/aca-shared/src/lib/components/document-base-page/document-base-page.spec.ts b/projects/aca-shared/src/lib/components/document-base-page/document-base-page.spec.ts index 8e06938559..bf5742704b 100644 --- a/projects/aca-shared/src/lib/components/document-base-page/document-base-page.spec.ts +++ b/projects/aca-shared/src/lib/components/document-base-page/document-base-page.spec.ts @@ -25,64 +25,18 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { PageComponent } from './document-base-page.component'; import { AppState, ReloadDocumentListAction, SetSelectedNodesAction, ViewNodeAction } from '@alfresco/aca-shared/store'; -import { AppExtensionService } from '@alfresco/aca-shared'; -import { NodeEntry, NodePaging, RepositoryInfo, VersionInfo } from '@alfresco/js-api'; +import { AppExtensionService, LibTestingModule, discoveryApiServiceMockValue, DocumentBasePageServiceMock } from '@alfresco/aca-shared'; +import { NodeEntry, NodePaging } from '@alfresco/js-api'; import { DocumentBasePageService } from './document-base-page.service'; -import { Store, StoreModule } from '@ngrx/store'; -import { Component, Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Component } from '@angular/core'; import { DiscoveryApiService, DocumentListComponent } from '@alfresco/adf-content-services'; import { MockStore, provideMockStore } from '@ngrx/store/testing'; -import { AuthModule, MaterialModule, PipeModule } from '@alfresco/adf-core'; +import { AuthModule, MaterialModule } from '@alfresco/adf-core'; import { HttpClientModule } from '@angular/common/http'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; -import { EffectsModule } from '@ngrx/effects'; -import { BehaviorSubject, Observable, of, Subscription } from 'rxjs'; - -export const INITIAL_APP_STATE: AppState = { - appName: 'Alfresco Content Application', - logoPath: 'assets/images/alfresco-logo-white.svg', - customCssPath: '', - webFontPath: '', - sharedUrl: '', - user: { - isAdmin: null, - id: null, - firstName: '', - lastName: '' - }, - selection: { - nodes: [], - libraries: [], - isEmpty: true, - count: 0 - }, - navigation: { - currentFolder: null - }, - currentNodeVersion: null, - infoDrawerOpened: false, - infoDrawerPreview: false, - infoDrawerMetadataAspect: '', - showFacetFilter: true, - fileUploadingDialog: true, - showLoader: false, - repository: { - status: { - isQuickShareEnabled: true - } - } as any -}; - -@Injectable() -class DocumentBasePageServiceMock extends DocumentBasePageService { - canUpdateNode(): boolean { - return true; - } - canUploadContent(): boolean { - return true; - } -} +import { Subscription } from 'rxjs'; @Component({ selector: 'aca-test', @@ -107,47 +61,11 @@ describe('PageComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ - NoopAnimationsModule, - HttpClientModule, - RouterTestingModule, - MaterialModule, - AuthModule.forRoot(), - StoreModule.forRoot( - { app: (state) => state }, - { - initialState: { - app: INITIAL_APP_STATE - }, - runtimeChecks: { - strictStateImmutability: false, - strictActionImmutability: false - } - } - ), - EffectsModule.forRoot([]), - PipeModule - ], + imports: [LibTestingModule, MaterialModule, AuthModule.forRoot()], declarations: [TestComponent], providers: [ - { - provide: DocumentBasePageService, - useClass: DocumentBasePageServiceMock - }, - { - provide: DiscoveryApiService, - useValue: { - ecmProductInfo$: new BehaviorSubject(null), - getEcmProductInfo: (): Observable => - of( - new RepositoryInfo({ - version: { - major: '10.0.0' - } as VersionInfo - }) - ) - } - }, + { provide: DocumentBasePageService, useClass: DocumentBasePageServiceMock }, + { provide: DiscoveryApiService, useValue: discoveryApiServiceMockValue }, AppExtensionService ] }); @@ -298,20 +216,7 @@ describe('Info Drawer state', () => { providers: [ { provide: DocumentBasePageService, useClass: DocumentBasePageServiceMock }, AppExtensionService, - { - provide: DiscoveryApiService, - useValue: { - ecmProductInfo$: new BehaviorSubject(null), - getEcmProductInfo: (): Observable => - of( - new RepositoryInfo({ - version: { - major: '10.0.0' - } as VersionInfo - }) - ) - } - }, + { provide: DiscoveryApiService, useValue: discoveryApiServiceMockValue }, provideMockStore({ initialState: { app: appState } }) @@ -337,7 +242,7 @@ describe('Info Drawer state', () => { window.history.pushState({}, null, `${locationHref}#test`); fixture.detectChanges(); - fixture.whenStable().then(() => { + void fixture.whenStable().then(() => { component.infoDrawerOpened$.subscribe((state) => { expect(state).toBe(true); done(); @@ -356,7 +261,7 @@ describe('Info Drawer state', () => { window.history.pushState({}, null, `${locationHref}#test(viewer:view)`); fixture.detectChanges(); - fixture.whenStable().then(() => { + void fixture.whenStable().then(() => { component.infoDrawerOpened$.subscribe((state) => { expect(state).toBe(true); done(); diff --git a/projects/aca-shared/src/lib/testing/lib-testing-module.ts b/projects/aca-shared/src/lib/testing/lib-testing-module.ts index d7cc526f37..3f083024c8 100644 --- a/projects/aca-shared/src/lib/testing/lib-testing-module.ts +++ b/projects/aca-shared/src/lib/testing/lib-testing-module.ts @@ -22,7 +22,7 @@ * from Hyland Software. If not, see . */ -import { NgModule } from '@angular/core'; +import { Injectable, NgModule } from '@angular/core'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { @@ -40,6 +40,9 @@ import { StoreModule } from '@ngrx/store'; import { CommonModule } from '@angular/common'; import { MatIconTestingModule } from '@angular/material/icon/testing'; import { OverlayModule } from '@angular/cdk/overlay'; +import { RepositoryInfo, VersionInfo } from '@alfresco/js-api'; +import { BehaviorSubject, Observable, of } from 'rxjs'; +import { DocumentBasePageService } from '../../public-api'; export const initialState = { app: { @@ -72,6 +75,28 @@ export const initialState = { } }; +export const discoveryApiServiceMockValue = { + ecmProductInfo$: new BehaviorSubject(null), + getEcmProductInfo: (): Observable => + of( + new RepositoryInfo({ + version: { + major: '10.0.0' + } as VersionInfo + }) + ) +}; + +@Injectable() +export class DocumentBasePageServiceMock extends DocumentBasePageService { + canUpdateNode(): boolean { + return true; + } + canUploadContent(): boolean { + return true; + } +} + @NgModule({ imports: [ NoopAnimationsModule, From 4a91aa6441e119d09aa1634d2ec0e26a080ff983 Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Tue, 26 Mar 2024 17:16:05 +0100 Subject: [PATCH 08/10] [ACA-4728] address comments --- .../viewer/src/lib/services/viewer.service.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.ts index dd127bec82..2d6cce1a74 100644 --- a/projects/aca-content/viewer/src/lib/services/viewer.service.ts +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.ts @@ -27,7 +27,7 @@ import { FavoritePaging, Node, NodePaging, SearchRequest, ResultSetPaging, Share import { Injectable } from '@angular/core'; import { ContentApiService } from '@alfresco/aca-shared'; -interface adjacentFiles { +interface AdjacentFiles { left: string; right: string; } @@ -67,10 +67,10 @@ export class ViewerService { * * @param nodeId Unique identifier of the document node * @param folderId Unique identifier of the containing folder node. - * @param source Data source name. Allowed values are: personal-files, libraries, favorites, shared, recent-files. + * @param source Data source name. Returns file ids for personal-files, libraries, favorites, shared and recent-files, otherwise returns empty. */ - async getNearestNodes(nodeId: string, folderId: string, source: string): Promise { - const empty: adjacentFiles = { + async getNearestNodes(nodeId: string, folderId: string, source: string): Promise { + const empty: AdjacentFiles = { left: null, right: null }; @@ -94,7 +94,7 @@ export class ViewerService { /** * Retrieves a list of node identifiers for the folder and data source. * - * @param source Data source name. Allowed values are: personal-files, libraries, favorites, shared, recent-files. + * @param source Data source name. Returns file ids for personal-files, libraries, favorites, shared and recent-files, otherwise returns empty. * @param folderId Optional parameter containing folder node identifier for 'personal-files' and 'libraries' sources. */ async getFileIds(source: string, folderId?: string): Promise { @@ -172,7 +172,7 @@ export class ViewerService { } this.sort(entries, sortKey, sortDirection); } - return entries.map((entry) => entry.id ?? entry.nodeId); + return nodes === undefined ? [] : entries.map((entry) => entry.id ?? entry.nodeId); } /** @@ -201,9 +201,7 @@ export class ViewerService { let right = ObjectUtils.getValue(b, key) ?? ''; right = right instanceof Date ? right.valueOf().toString() : right.toString(); - return direction === 'asc' || 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); }); } From 0783b017a45730ce849c2255c074ed9be292550c Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Thu, 28 Mar 2024 14:08:15 +0100 Subject: [PATCH 09/10] [ACA-4728] address comment - remove reduntant if --- projects/aca-content/viewer/src/lib/services/viewer.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.ts index 2d6cce1a74..61da1a11b6 100644 --- a/projects/aca-content/viewer/src/lib/services/viewer.service.ts +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.ts @@ -172,7 +172,7 @@ export class ViewerService { } this.sort(entries, sortKey, sortDirection); } - return nodes === undefined ? [] : entries.map((entry) => entry.id ?? entry.nodeId); + return entries.map((entry) => entry.id ?? entry.nodeId); } /** From ea359c5e19b59b28c01d6fb56d219e72ac09eaed Mon Sep 17 00:00:00 2001 From: g-jaskowski Date: Thu, 4 Apr 2024 11:02:09 +0200 Subject: [PATCH 10/10] [ACA-4728] update headers in new files --- .../aca-content/viewer/src/lib/services/viewer.service.spec.ts | 2 +- projects/aca-content/viewer/src/lib/services/viewer.service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts index 668a621ae8..c3fd364e98 100644 --- a/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.spec.ts @@ -1,5 +1,5 @@ /*! - * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. + * Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved. * * Alfresco Example Content Application * diff --git a/projects/aca-content/viewer/src/lib/services/viewer.service.ts b/projects/aca-content/viewer/src/lib/services/viewer.service.ts index 61da1a11b6..3cf9a9aeed 100644 --- a/projects/aca-content/viewer/src/lib/services/viewer.service.ts +++ b/projects/aca-content/viewer/src/lib/services/viewer.service.ts @@ -1,5 +1,5 @@ /*! - * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. + * Copyright © 2005-2024 Hyland Software, Inc. and its affiliates. All rights reserved. * * Alfresco Example Content Application *