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 0233d90bd2..0000000000 --- a/projects/aca-content/preview/src/lib/preview.module.ts +++ /dev/null @@ -1,32 +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 { 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 108941e713..0000000000 --- a/projects/aca-content/preview/src/public-api.ts +++ /dev/null @@ -1,30 +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 . - */ - -/* - * 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 d4e12c097a..0000000000 --- a/projects/aca-content/preview/src/test.ts +++ /dev/null @@ -1,49 +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 . - */ - -// 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 bc4db85939..52f19c0a9e 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 bb533d47e3..cb6c7684c5 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, PaginationModule, ShowHeaderMode, UserPreferencesService } from '@alfresco/adf-core'; -import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; +import { DataTableModule, PaginationModule, 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 0994c82446..17fc3d704f 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 d251fe73fc..f0ab8cd96b 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 6f98dc8264..f773f938a3 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 fdfe0198af..51766f5a30 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 18f1300786..984667a685 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 5fd2327a4b..9d244bcee7 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 fcf280094c..aa72b94d7b 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 baf04f2522..b063e0d09b 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; }