[ACA-4728] fix file order in viewer (#3631)

* [ACA-4728] fix file order in viewer

* [ACA-4728] refactor viewer and preview, save and restore previous sorting in viewer and document pages when client sorting, add viewer unit tests

* [ACA-4728] remove duplicated license

* [ACA-4728] add missing imports

* [ACA-4728] address comments, improve initial sorting setting, improve tests, reduce duplication

* [ACA-4728] further reduce code duplication, remove/replace faulty unit tests

* [ACA-4728] move reusable unit test config to testing module

* [ACA-4728] address comments

* [ACA-4728] address comment - remove reduntant if

* [ACA-4728] update headers in new files
This commit is contained in:
Grzegorz Jaśkowski
2024-04-10 10:39:11 +02:00
committed by GitHub
parent 12c0b87c09
commit 92a1e25271
28 changed files with 1173 additions and 1485 deletions

View File

@@ -0,0 +1,34 @@
<ng-container *ngIf="nodeId">
<adf-alfresco-viewer
[ngClass]="{
'aca-right_side--hide': !showRightSide
}"
[nodeId]="nodeId"
[allowNavigate]="navigateMultiple"
[allowRightSidebar]="true"
[allowPrint]="false"
[showRightSidebar]="true"
[allowDownload]="false"
[allowFullScreen]="false"
[canNavigateBefore]="!!previousNodeId"
[canNavigateNext]="!!nextNodeId"
[overlayMode]="true"
(showViewerChange)="onVisibilityChanged($event)"
(navigateBefore)="onNavigateBefore($event)"
(navigateNext)="onNavigateNext($event)"
>
<adf-viewer-sidebar *ngIf="infoDrawerOpened$ | async">
<aca-info-drawer [node]="selection.file"></aca-info-drawer>
</adf-viewer-sidebar>
<adf-viewer-open-with *ngIf="openWith.length">
<ng-container *ngFor="let action of openWith; trackBy: trackByActionId">
<app-toolbar-menu-item [actionRef]="action"></app-toolbar-menu-item>
</ng-container>
</adf-viewer-open-with>
<adf-viewer-toolbar-actions *ngIf="!simplestMode">
<aca-toolbar [items]="viewerToolbarActions"></aca-toolbar>
</adf-viewer-toolbar-actions>
</adf-alfresco-viewer>
</ng-container>

View File

@@ -0,0 +1,27 @@
.app-preview {
width: 100%;
height: 100%;
}
.adf-viewer-toolbar .adf-toolbar-divider {
display: none;
}
.adf-viewer-toolbar-actions {
display: flex;
flex-direction: row;
align-items: center;
.adf-toolbar-divider {
display: inline;
}
}
// todo: remove this when viewer supports extensions
.adf-viewer-toolbar > * > button:last-child {
display: none;
}
.adf-alfresco-viewer.aca-right_side--hide .adf-viewer__sidebar__right {
width: 0;
}

View File

@@ -0,0 +1,352 @@
/*!
* 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 <http://www.gnu.org/licenses/>.
*/
import { Router, ActivatedRoute } from '@angular/router';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
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,
LibTestingModule,
discoveryApiServiceMockValue,
DocumentBasePageServiceMock
} from '@alfresco/aca-shared';
import { Store } from '@ngrx/store';
import { Node } from '@alfresco/js-api';
import { AcaViewerModule } from '../../viewer.module';
const clickEvent = new MouseEvent('click');
describe('PreviewComponent', () => {
let fixture: ComponentFixture<PreviewComponent>;
let component: PreviewComponent;
let router: Router;
let route: ActivatedRoute;
let contentApi: ContentApiService;
let uploadService: UploadService;
let nodesApiService: NodesApiService;
let appHookService: AppHookService;
let store: Store<any>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [LibTestingModule, AcaViewerModule],
providers: [
{ provide: DocumentBasePageService, useValue: DocumentBasePageServiceMock },
{ provide: DiscoveryApiService, useValue: discoveryApiServiceMockValue },
{ provide: AuthenticationService, useValue: {} }
]
});
fixture = TestBed.createComponent(PreviewComponent);
component = fixture.componentInstance;
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);
});
describe('Navigation', () => {
beforeEach(() => {
spyOn(router, 'navigate').and.stub();
});
describe('From personal-files', () => {
beforeEach(() => {
component.previewLocation = 'personal-files';
});
it('should navigate to previous node in sub-folder', () => {
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', () => {
component.folderId = null;
component.previousNodeId = 'previous1';
component.onNavigateBefore(clickEvent);
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'previous1']);
});
it('should navigate to next node in sub-folder', () => {
component.folderId = 'folder1';
component.nextNodeId = 'next1';
component.onNavigateNext(clickEvent);
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1', 'preview', 'next1']);
});
it('should navigate to next node in the root path', () => {
component.folderId = null;
component.nextNodeId = 'next1';
component.onNavigateNext(clickEvent);
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'preview', 'next1']);
});
});
it('should not navigate to nearest nodes if node unset', () => {
component.previousNodeId = null;
component.nextNodeId = null;
component.onNavigateBefore(clickEvent);
component.onNavigateNext(clickEvent);
expect(router.navigate).not.toHaveBeenCalled();
});
it('should navigate back to root path upon close', () => {
component.routesSkipNavigation = [];
component.previewLocation = 'libraries';
component.folderId = null;
component.onVisibilityChanged(false);
expect(router.navigate).toHaveBeenCalledWith(['libraries', {}]);
});
it('should navigate back to folder path upon close', () => {
component.routesSkipNavigation = [];
component.previewLocation = 'libraries';
component.folderId = 'site1';
component.onVisibilityChanged(false);
expect(router.navigate).toHaveBeenCalledWith(['libraries', {}, 'site1']);
});
it('should not navigate to root path for certain routes upon close', () => {
component.routesSkipNavigation = ['shared'];
component.previewLocation = 'shared';
component.folderId = 'folder1';
component.onVisibilityChanged(false);
expect(router.navigate).toHaveBeenCalledWith(['shared', {}]);
});
it('should not navigate back if viewer is still visible', () => {
component.routesSkipNavigation = [];
component.previewLocation = 'shared';
component.onVisibilityChanged(true);
expect(router.navigate).not.toHaveBeenCalled();
});
});
describe('Generate paths', () => {
beforeEach(() => {
component.previewLocation = 'personal-files';
});
it('should generate preview path for a folder only', () => {
expect(component.getPreviewPath('folder1', null)).toEqual(['personal-files', 'folder1']);
});
it('should generate preview path for a folder and a node', () => {
expect(component.getPreviewPath('folder1', 'node1')).toEqual(['personal-files', 'folder1', 'preview', 'node1']);
});
it('should generate preview path for a node only', () => {
expect(component.getPreviewPath(null, 'node1')).toEqual(['personal-files', 'preview', 'node1']);
});
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', () => {
route.snapshot.data = {
navigateMultiple: true
};
component.ngOnInit();
expect(component.navigateMultiple).toBeTruthy();
});
it('should not enable multiple document navigation from route data', () => {
route.snapshot.data = {};
component.ngOnInit();
expect(component.navigateMultiple).toBeFalsy();
});
it('should set folderId and call displayNode with nodeId upon init', () => {
route.params = of({
folderId: 'folder1',
nodeId: 'node1'
});
spyOn(component, 'displayNode').and.stub();
component.ngOnInit();
expect(component.folderId).toBe('folder1');
expect(component.displayNode).toHaveBeenCalledWith('node1');
});
it('should navigate to original location if node not found', async () => {
spyOn(router, 'navigate').and.stub();
spyOn(contentApi, 'getNodeInfo').and.returnValue(throwError('error'));
component.previewLocation = 'personal-files';
await component.displayNode('folder1');
expect(contentApi.getNodeInfo).toHaveBeenCalledWith('folder1');
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1']);
});
it('should navigate to original location if node is not a File', async () => {
spyOn(router, 'navigate').and.stub();
spyOn(contentApi, 'getNodeInfo').and.returnValue(
of({
isFile: false
} as Node)
);
component.previewLocation = 'personal-files';
await component.displayNode('folder1');
expect(contentApi.getNodeInfo).toHaveBeenCalledWith('folder1');
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1']);
});
it('should navigate to original location in case of Alfresco API errors', async () => {
spyOn(router, 'navigate').and.stub();
spyOn(contentApi, 'getNodeInfo').and.returnValue(throwError('error'));
component.previewLocation = 'personal-files';
await component.displayNode('folder1');
expect(contentApi.getNodeInfo).toHaveBeenCalledWith('folder1');
expect(router.navigate).toHaveBeenCalledWith(['personal-files', 'folder1']);
});
it('should return to parent folder on nodesDeleted event', async () => {
spyOn(component, 'navigateToFileLocation');
fixture.detectChanges();
await fixture.whenStable();
appHookService.nodesDeleted.next();
expect(component.navigateToFileLocation).toHaveBeenCalled();
});
it('should return to parent folder on fileUploadDeleted event', async () => {
spyOn(component, 'navigateToFileLocation');
fixture.detectChanges();
await fixture.whenStable();
uploadService.fileUploadDeleted.next();
expect(component.navigateToFileLocation).toHaveBeenCalled();
});
it('should emit nodeUpdated event on fileUploadComplete event', fakeAsync(() => {
spyOn(nodesApiService.nodeUpdated, 'next');
fixture.detectChanges();
uploadService.fileUploadComplete.next({ data: { entry: {} } } as any);
tick(300);
expect(nodesApiService.nodeUpdated.next).toHaveBeenCalled();
}));
it('should return to parent folder when event emitted from extension', async () => {
spyOn(component, 'navigateToFileLocation');
fixture.detectChanges();
await fixture.whenStable();
store.dispatch(new ClosePreviewAction());
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 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 not navigate on keyboard event if target is child of sidebar container or cdk overlay', () => {
component.nextNodeId = 'node';
spyOn(router, 'navigate').and.stub();
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);
parent.className = 'adf-viewer__sidebar';
child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' }));
expect(router.navigate).not.toHaveBeenCalled();
parent.className = 'cdk-overlay-container';
child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' }));
expect(router.navigate).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,280 @@
/*!
* 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 <http://www.gnu.org/licenses/>.
*/
import { Component, OnInit, OnDestroy, ViewEncapsulation, HostListener } from '@angular/core';
import { CommonModule, Location } from '@angular/common';
import { UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET, ActivatedRoute } from '@angular/router';
import { debounceTime, map, takeUntil } from 'rxjs/operators';
import { ViewerModule } from '@alfresco/adf-core';
import { ClosePreviewAction, ViewerActionTypes, SetSelectedNodesAction } from '@alfresco/aca-shared/store';
import {
PageComponent,
AppHookService,
ContentApiService,
InfoDrawerComponent,
ToolbarMenuItemComponent,
ToolbarComponent
} from '@alfresco/aca-shared';
import { ContentActionRef } from '@alfresco/adf-extensions';
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,
imports: [CommonModule, ViewerModule, AlfrescoViewerModule, InfoDrawerComponent, ToolbarMenuItemComponent, ToolbarComponent],
selector: 'app-preview',
templateUrl: './preview.component.html',
styleUrls: ['./preview.component.scss'],
encapsulation: ViewEncapsulation.None,
host: { class: 'app-preview' }
})
export class PreviewComponent extends PageComponent implements OnInit, OnDestroy {
folderId: string = null;
navigateBackAsClose = false;
navigateMultiple = false;
navigateSource: string = null;
navigationSources = ['favorites', 'libraries', 'personal-files', 'recent-files', 'shared'];
nextNodeId: string;
nodeId: string = null;
openWith: Array<ContentActionRef> = [];
previewLocation: string = null;
previousNodeId: string;
routesSkipNavigation = ['favorites', 'recent-files', 'shared'];
showRightSide = false;
simplestMode = false;
private containersSkipNavigation = ['adf-viewer__sidebar', 'cdk-overlay-container', 'adf-image-viewer'];
constructor(
private actions$: Actions,
private appHookService: AppHookService,
private contentApi: ContentApiService,
private location: Location,
private nodesApiService: NodesApiService,
private route: ActivatedRoute,
private viewerService: ViewerService
) {
super();
}
ngOnInit() {
super.ngOnInit();
from(this.infoDrawerOpened$)
.pipe(takeUntil(this.onDestroy$))
.subscribe((val) => {
this.showRightSide = val;
});
this.previewLocation = this.router.url.substr(0, this.router.url.indexOf('/', 1)).replace(/\//g, '');
const routeData = this.route.snapshot.data;
this.navigateBackAsClose = !!routeData.navigateBackAsClose;
this.simplestMode = !!routeData.simplestMode;
if (routeData.navigateMultiple) {
this.navigateMultiple = true;
}
if (routeData.navigateSource) {
const source = routeData.navigateSource.toLowerCase();
if (this.navigationSources.includes(source)) {
this.navigateSource = routeData.navigateSource;
}
}
this.route.params.subscribe((params) => {
this.folderId = params.folderId;
const id = params.nodeId;
if (id) {
void this.displayNode(id);
}
});
this.subscriptions = this.subscriptions.concat([
this.appHookService.nodesDeleted.subscribe(() => this.navigateToFileLocation(true)),
this.uploadService.fileUploadDeleted.subscribe(() => this.navigateToFileLocation(true)),
this.uploadService.fileUploadComplete.pipe(debounceTime(300)).subscribe((file) => this.nodesApiService.nodeUpdated.next(file.data.entry)),
this.actions$
.pipe(
ofType<ClosePreviewAction>(ViewerActionTypes.ClosePreview),
map(() => this.navigateToFileLocation(true))
)
.subscribe(() => {})
]);
this.extensions
.getOpenWithActions()
.pipe(takeUntil(this.onDestroy$))
.subscribe((actions) => {
this.openWith = actions;
});
}
ngOnDestroy() {
super.ngOnDestroy();
}
/**
* Loads the particular node into the Viewer
*
* @param id Unique identifier for the Node to display
*/
async displayNode(id: string) {
if (id) {
try {
this.node = await this.contentApi.getNodeInfo(id).toPromise();
this.store.dispatch(new SetSelectedNodesAction([{ entry: this.node }]));
if (this.node?.isFile) {
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]);
} catch (err) {
if (!err || err.status !== 401) {
await this.router.navigate([this.previewLocation, id]);
}
}
}
}
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
const key = event.key;
if (key === 'ArrowRight' || key === 'ArrowLeft') {
event.preventDefault();
event.stopImmediatePropagation();
}
}
/**
* Handles the visibility change of the Viewer component.
*
* @param isVisible Indicator whether Viewer is visible or hidden.
*/
onVisibilityChanged(isVisible: boolean): void {
const shouldNavigate = !isVisible;
this.navigateToFileLocation(shouldNavigate);
}
navigateToFileLocation(shouldNavigate: boolean) {
if (shouldNavigate) {
if (this.navigateBackAsClose) {
this.location.back();
} else {
const shouldSkipNavigation = this.routesSkipNavigation.includes(this.previewLocation);
const route = this.getNavigationCommands(this.previewLocation);
if (!shouldSkipNavigation && this.folderId) {
route.push(this.folderId);
}
void this.router.navigate(route);
}
}
}
/** Handles navigation to a previous document */
onNavigateBefore(event: MouseEvent | KeyboardEvent): void {
if (event.type !== 'click' && this.shouldNavigate(event.target as HTMLElement)) {
return;
}
if (this.previousNodeId) {
void this.router.navigate(this.getPreviewPath(this.folderId, this.previousNodeId));
}
}
/** Handles navigation to a next document */
onNavigateNext(event: MouseEvent | KeyboardEvent): void {
if (event.type !== 'click' && this.shouldNavigate(event.target as HTMLElement)) {
return;
}
if (this.nextNodeId) {
void this.router.navigate(this.getPreviewPath(this.folderId, this.nextNodeId));
}
}
/**
* Generates a node preview route based on folder and node IDs.
*
* @param folderId Folder ID
* @param nodeId Node ID
*/
getPreviewPath(folderId: string, nodeId: string): any[] {
const route = [this.previewLocation];
if (folderId) {
route.push(folderId);
}
if (nodeId) {
route.push('preview', nodeId);
}
return route;
}
private getNavigationCommands(url: string): any[] {
const urlTree: UrlTree = this.router.parseUrl(url);
const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
if (!urlSegmentGroup) {
return [url];
}
const urlSegments: UrlSegment[] = urlSegmentGroup.segments;
return urlSegments.reduce(function (acc, item) {
acc.push(item.path, item.parameters);
return acc;
}, []);
}
private shouldNavigate(element: HTMLElement): boolean {
let currentElement = element.parentElement;
while (currentElement && !this.isChild(currentElement.classList)) {
currentElement = currentElement.parentElement;
}
return !!currentElement;
}
private isChild(list: DOMTokenList): boolean {
return Array.from(list).some((className: string) => this.containersSkipNavigation.includes(className));
}
}

View File

@@ -22,41 +22,235 @@
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
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 { Router, ActivatedRoute } from '@angular/router';
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
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,
LibTestingModule,
discoveryApiServiceMockValue,
DocumentBasePageServiceMock
} from '@alfresco/aca-shared';
import { Store } from '@ngrx/store';
import { Node } from '@alfresco/js-api';
import { EMPTY } from 'rxjs';
import { CoreTestingModule } from '@alfresco/adf-core';
import { Store, StoreModule } from '@ngrx/store';
import { AcaViewerModule } from '../../viewer.module';
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';
describe('AcaViewerComponent', () => {
let fixture: ComponentFixture<AcaViewerComponent>;
let component: AcaViewerComponent;
let router: Router;
let route: ActivatedRoute;
let contentApi: ContentApiService;
let uploadService: UploadService;
let nodesApiService: NodesApiService;
let appHookService: AppHookService;
let store: Store<any>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [CoreTestingModule, StoreModule.forRoot({})]
imports: [LibTestingModule, AcaViewerModule],
providers: [
{ provide: DocumentBasePageService, useValue: DocumentBasePageServiceMock },
{ provide: DiscoveryApiService, useValue: discoveryApiServiceMockValue },
{ provide: AuthenticationService, useValue: {} }
]
});
store = TestBed.inject(Store);
spyOn(store, 'select').and.returnValue(EMPTY);
fixture = TestBed.createComponent(AcaViewerComponent);
component = fixture.componentInstance;
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);
});
describe('Load content', () => {
it('should call node update after RefreshPreviewAction is triggered', () => {
spyOn(nodesApiService.nodeUpdated, 'next');
component.ngOnInit();
const node = new Node();
it('should set folderId and call displayNode with nodeId upon init', () => {
route.params = of({
folderId: 'folder1',
nodeId: 'node1'
});
spyOn(component, 'displayNode').and.stub();
store.dispatch(new RefreshPreviewAction(node));
expect(nodesApiService.nodeUpdated.next).toHaveBeenCalledWith(node);
component.ngOnInit();
expect(component.folderId).toBe('folder1');
expect(component.displayNode).toHaveBeenCalledWith('node1');
});
it('should navigate to next and previous nodes', () => {
spyOn(store, 'dispatch');
spyOn<any>(component, 'getFileLocation').and.returnValue(fakeLocation);
const clickEvent = new MouseEvent('click');
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 }));
});
describe('Navigate back to node location', () => {
beforeEach(async () => {
spyOn<any>(component, 'navigateToFileLocation').and.callThrough();
component['navigationPath'] = fakeLocation;
spyOn(router, 'navigateByUrl').and.stub();
});
it('should reload document list and navigate to node location upon close', async () => {
spyOn(store, 'dispatch');
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)
);
await component.displayNode('folder1');
expect(contentApi.getNodeInfo).toHaveBeenCalledWith('folder1');
expect(component['navigateToFileLocation']).toHaveBeenCalled();
expect(router.navigateByUrl).toHaveBeenCalledWith(fakeLocation);
});
});
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));
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);
expect(nodesApiService.nodeUpdated.next).toHaveBeenCalled();
}));
describe('return on event', () => {
beforeEach(async () => {
spyOn<any>(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');
});
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();
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);
parent.className = 'adf-viewer__sidebar';
child.dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowRight' }));
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', () => {
spyOn(nodesApiService.nodeUpdated, 'next');
component.ngOnInit();
const node = new Node();
store.dispatch(new RefreshPreviewAction(node));
expect(nodesApiService.nodeUpdated.next).toHaveBeenCalledWith(node);
});
});

View File

@@ -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,36 @@ export class AcaViewerComponent implements OnInit, OnDestroy {
fileName: string;
folderId: string = null;
nodeId: string = null;
versionId: string = null;
node: Node;
selection: SelectionState;
infoDrawerOpened$: Observable<boolean>;
showRightSide = false;
openWith: ContentActionRef[] = [];
toolbarActions: ContentActionRef[] = [];
navigateSource: string = null;
previousNodeId: string;
nextNodeId: string;
navigateMultiple = true;
routesSkipNavigation = ['shared', 'recent-files', 'favorites'];
navigateSource: string = null;
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"'
];
nextNodeId: string;
node: Node;
nodeId: string = null;
openWith: ContentActionRef[] = [];
previousNodeId: string;
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<AppStore>,
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<AppStore>,
private uploadService: UploadService,
private appHookService: AppHookService
private viewerService: ViewerService
) {}
ngOnInit() {
@@ -167,7 +142,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));
}
@@ -234,26 +209,24 @@ 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.getNearestNodes(this.node.id, this.node.parentId);
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;
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,147 +251,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<string[]> {
if ((source === 'personal-files' || source === 'libraries') && folderId) {
const sortKey = this.preferences.get('personal-files.sorting.key') || 'modifiedAt';
const sortDirection = this.preferences.get('personal-files.sorting.direction') || 'desc';
const nodes = await this.contentApi
.getNodeChildren(folderId, {
// orderBy: `${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);
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;
@@ -429,27 +261,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 {

View File

@@ -0,0 +1,218 @@
/*!
* 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 <http://www.gnu.org/licenses/>.
*/
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 './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', modifiedAt: new Date(1) } },
{ entry: { id: 'node3', name: 'node 3', modifiedAt: new Date(2) } },
{ entry: { id: 'node2', name: '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 emptyAdjacent = {
left: null,
right: null
};
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;
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, ...preferencesCurSortValues);
});
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 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 idsFavorites = await viewerService.getFileIds('favorites');
expect(idsFavorites).toEqual(resultDesc);
});
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 idsShared = await viewerService.getFileIds('shared');
expect(idsShared).toEqual(resultDesc);
});
});
it('should use default with no sorting for personal-files and other sources', async () => {
spyOn(preferences, 'get').and.returnValues(...preferencesNoCurSortValues);
spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as unknown as NodePaging));
const idsFiles = await viewerService.getFileIds('personal-files', 'folder1');
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', () => {
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 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(noNodeId).toEqual(emptyAdjacent);
expect(wrongSource).toEqual(emptyAdjacent);
});
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 personal-files and libraries', async () => {
const ids = await viewerService.getFileIds('libraries', null);
expect(ids).toEqual([]);
});
});

View File

@@ -0,0 +1,227 @@
/*!
* 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 <http://www.gnu.org/licenses/>.
*/
import { ObjectUtils, UserPreferencesService } from '@alfresco/adf-core';
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'
})
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.
* @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<AdjacentFiles> {
const empty: AdjacentFiles = {
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
};
}
} catch {}
}
return empty;
}
/**
* Retrieves a list of node identifiers for the folder and data source.
*
* @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<string[]> {
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' || source === 'libraries-files') {
if (!folderId) {
return [];
}
const orderBy = isClient ? null : ['isFolder desc', `${sortKey} ${sortDirection}`];
nodes = await this.contentApi
.getNodeChildren(folderId, {
orderBy: orderBy,
fields: this.getFields(sortKey, previousSortKey),
where: '(isFile=true)'
})
.toPromise();
}
if (source === 'favorites') {
nodes = await this.contentApi
.getFavorites('-me-', {
where: '(EXISTS(target/file))',
fields: ['target']
})
.toPromise();
}
if (source === 'shared') {
nodes = await this.contentApi
.findSharedLinks({
fields: ['nodeId', this.getRootField(sortKey)]
})
.toPromise();
}
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
}
]
};
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);
}
this.sort(entries, sortKey, sortDirection);
}
return entries.map((entry) => entry.id ?? entry.nodeId);
}
/**
* Get the root field name from the property path.
* Example: 'property1.some.child.property' => 'property1'
*
* @param path Property path
*/
getRootField(path: string): string {
if (path) {
return path.split('.')[0];
}
return path;
}
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: Node | SharedLink, b: Node | SharedLink) => {
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 getFields(sortKey: string, previousSortKey?: string): string[] {
return ['id', this.getRootField(sortKey), this.getRootField(previousSortKey)];
}
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];
const sortDirection = this.preferences.get(`${source}.sorting.direction`) || this.getDefaults(source)[1];
return [sortKey, sortDirection, previousSortKey, previousSortDir];
}
private getDefaults(source: string): string[] {
if (source === 'personal-files' || source === 'libraries-files') {
return ['name', 'asc'];
} else {
return ['modifiedAt', 'desc'];
}
}
}

View File

@@ -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 {}

View File

@@ -27,4 +27,5 @@
*/
export * from './lib/components/viewer/viewer.component';
export * from './lib/components/preview/preview.component';
export * from './lib/viewer.module';