[ACA-1443] prettier formatting and checks (#629)

* intergrate prettier

* update settings

* integrate with travis

* unified formatting across all files
This commit is contained in:
Denys Vuika
2018-09-13 16:47:55 +01:00
committed by GitHub
parent 06402a9c72
commit 883a1971c5
163 changed files with 13571 additions and 12512 deletions

View File

@@ -4,7 +4,7 @@ root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

2
.prettierignore Normal file
View File

@@ -0,0 +1,2 @@
node_modules
src/assets/i18n

3
.prettierrc Normal file
View File

@@ -0,0 +1,3 @@
{
"singleQuote": true
}

View File

@@ -9,7 +9,7 @@ addons:
language: node_js
node_js:
- "8"
- '8'
before_script:
# Disable services enabled by default
@@ -24,7 +24,10 @@ before_install:
jobs:
include:
- stage: test
script: npm run lint && npm run spellcheck
script:
- npm run lint
- npm run spellcheck
- npm run format:check
- stage: test
script:
- npm run test:ci

View File

@@ -1,4 +1,5 @@
{
"javascript.preferences.quoteStyle": "single",
"typescript.preferences.quoteStyle": "single"
"typescript.preferences.quoteStyle": "single",
"editor.formatOnSave": true
}

6
package-lock.json generated
View File

@@ -11444,6 +11444,12 @@
"integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=",
"dev": true
},
"prettier": {
"version": "1.14.2",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-1.14.2.tgz",
"integrity": "sha512-McHPg0n1pIke+A/4VcaS2en+pTNjy4xF+Uuq86u/5dyDO59/TtFZtQ708QIRkEZ3qwKz3GVkVa6mpxK/CpB8Rg==",
"dev": true
},
"pretty-error": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-2.1.1.tgz",

View File

@@ -22,7 +22,8 @@
"stop:docker": "docker-compose stop",
"e2e:docker": "npm run start:docker && npm run e2e && npm run stop:docker",
"spellcheck": "cspell 'src/**/*.ts' 'e2e/**/*.ts' 'projects/**/*.ts'",
"inspect.bundle": "ng build app --prod --stats-json && npx webpack-bundle-analyzer dist/app/stats.json"
"inspect.bundle": "ng build app --prod --stats-json && npx webpack-bundle-analyzer dist/app/stats.json",
"format:check": "prettier --list-different \"src/{app,environments}/**/*{.ts,.js,.json,.css,.scss}\""
},
"private": true,
"dependencies": {
@@ -89,6 +90,7 @@
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"ng-packagr": "^4.1.1",
"prettier": "^1.14.2",
"protractor": "^5.4.0",
"rimraf": "2.6.2",
"selenium-webdriver": "4.0.0-alpha.1",

View File

@@ -41,7 +41,11 @@ import {
SetCurrentUrlAction,
SetInitialStateAction
} from './store/actions';
import { AppStore, AppState, INITIAL_APP_STATE } from './store/states/app.state';
import {
AppStore,
AppState,
INITIAL_APP_STATE
} from './store/states/app.state';
import { filter } from 'rxjs/operators';
import { MatDialog } from '@angular/material';
@@ -68,7 +72,10 @@ export class AppComponent implements OnInit {
this.alfrescoApiService.getInstance().on('error', error => {
if (error.status === 401) {
if (!this.authenticationService.isLoggedIn()) {
this.authenticationService.setRedirect({ provider: 'ECM', url: this.router.url });
this.authenticationService.setRedirect({
provider: 'ECM',
url: this.router.url
});
this.router.navigate(['/login']);
this.dialogRef.closeAll();

View File

@@ -28,7 +28,12 @@ import { NgModule } from '@angular/core';
import { RouterModule, RouteReuseStrategy } from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { TRANSLATION_PROVIDER, CoreModule, AppConfigService, DebugAppConfigService } from '@alfresco/adf-core';
import {
TRANSLATION_PROVIDER,
CoreModule,
AppConfigService,
DebugAppConfigService
} from '@alfresco/adf-core';
import { ContentModule } from '@alfresco/adf-content-services';
import { AppComponent } from './app.component';

View File

@@ -119,8 +119,6 @@ export class AppRouteReuseStrategy implements RouteReuseStrategy {
}
private getRouteData(route: ActivatedRouteSnapshot): RouteData {
return (
route.routeConfig && (route.routeConfig.data as RouteData)
);
return route.routeConfig && (route.routeConfig.data as RouteData);
}
}

View File

@@ -52,7 +52,8 @@ export const APP_ROUTES: Routes = [
},
{
path: 'settings',
loadChildren: 'src/app/components/settings/settings.module#AppSettingsModule',
loadChildren:
'src/app/components/settings/settings.module#AppSettingsModule',
data: {
title: 'Settings'
}
@@ -61,7 +62,7 @@ export const APP_ROUTES: Routes = [
path: 'preview/s/:id',
component: SharedLinkViewComponent,
data: {
title: 'APP.PREVIEW.TITLE',
title: 'APP.PREVIEW.TITLE'
}
},
{
@@ -89,7 +90,8 @@ export const APP_ROUTES: Routes = [
},
{
path: 'preview/:nodeId',
loadChildren: 'src/app/components/preview/preview.module#PreviewModule',
loadChildren:
'src/app/components/preview/preview.module#PreviewModule',
data: {
title: 'APP.PREVIEW.TITLE',
navigateMultiple: true,
@@ -103,13 +105,15 @@ export const APP_ROUTES: Routes = [
data: {
sortingPreferenceKey: 'libraries'
},
children: [{
children: [
{
path: '',
component: LibrariesComponent,
data: {
title: 'APP.BROWSE.LIBRARIES.TITLE'
}
}, {
},
{
path: ':folderId',
component: FilesComponent,
data: {
@@ -119,7 +123,8 @@ export const APP_ROUTES: Routes = [
},
{
path: ':folderId/preview/:nodeId',
loadChildren: 'src/app/components/preview/preview.module#PreviewModule',
loadChildren:
'src/app/components/preview/preview.module#PreviewModule',
data: {
title: 'APP.PREVIEW.TITLE',
navigateMultiple: true,
@@ -151,7 +156,8 @@ export const APP_ROUTES: Routes = [
},
{
path: 'preview/:nodeId',
loadChildren: 'src/app/components/preview/preview.module#PreviewModule',
loadChildren:
'src/app/components/preview/preview.module#PreviewModule',
data: {
title: 'APP.PREVIEW.TITLE',
navigateMultiple: true,
@@ -160,7 +166,8 @@ export const APP_ROUTES: Routes = [
},
{
path: ':folderId/preview/:nodeId',
loadChildren: 'src/app/components/preview/preview.module#PreviewModule',
loadChildren:
'src/app/components/preview/preview.module#PreviewModule',
data: {
title: 'APP.PREVIEW.TITLE',
navigateMultiple: true,
@@ -184,7 +191,8 @@ export const APP_ROUTES: Routes = [
},
{
path: 'preview/:nodeId',
loadChildren: 'src/app/components/preview/preview.module#PreviewModule',
loadChildren:
'src/app/components/preview/preview.module#PreviewModule',
data: {
title: 'APP.PREVIEW.TITLE',
navigateMultiple: true,
@@ -208,7 +216,8 @@ export const APP_ROUTES: Routes = [
},
{
path: 'preview/:nodeId',
loadChildren: 'src/app/components/preview/preview.module#PreviewModule',
loadChildren:
'src/app/components/preview/preview.module#PreviewModule',
data: {
title: 'APP.PREVIEW.TITLE',
navigateMultiple: true,
@@ -245,7 +254,8 @@ export const APP_ROUTES: Routes = [
},
{
path: 'preview/:nodeId',
loadChildren: 'src/app/components/preview/preview.module#PreviewModule',
loadChildren:
'src/app/components/preview/preview.module#PreviewModule',
data: {
title: 'APP.PREVIEW.TITLE',
navigateMultiple: true,
@@ -263,4 +273,3 @@ export const APP_ROUTES: Routes = [
canActivate: [AuthGuardEcm]
}
];

View File

@@ -40,7 +40,8 @@ export class AboutComponent implements OnInit {
status: ObjectDataTableAdapter;
license: ObjectDataTableAdapter;
modules: ObjectDataTableAdapter;
githubUrlCommitAlpha = 'https://github.com/Alfresco/alfresco-content-app/commits';
githubUrlCommitAlpha =
'https://github.com/Alfresco/alfresco-content-app/commits';
releaseVersion = '';
constructor(
@@ -49,7 +50,8 @@ export class AboutComponent implements OnInit {
) {}
ngOnInit() {
this.contentApi.getRepositoryInformation()
this.contentApi
.getRepositoryInformation()
.pipe(map(node => node.entry.repository))
.subscribe(repository => {
this.repository = repository;
@@ -57,49 +59,128 @@ export class AboutComponent implements OnInit {
this.modules = new ObjectDataTableAdapter(repository.modules, [
{ type: 'text', key: 'id', title: 'ID', sortable: true },
{ type: 'text', key: 'title', title: 'Title', sortable: true },
{type: 'text', key: 'version', title: 'Description', sortable: true},
{type: 'date', key: 'installDate', title: 'Install Date', sortable: true},
{type: 'text', key: 'installState', title: 'Install State', sortable: true},
{type: 'text', key: 'versionMin', title: 'Version Minor', sortable: true},
{type: 'text', key: 'versionMax', title: 'Version Max', sortable: true}
]);
this.status = new ObjectDataTableAdapter([repository.status], [
{type: 'text', key: 'isReadOnly', title: 'Read Only', sortable: true},
{type: 'text', key: 'isAuditEnabled', title: 'Audit Enable', sortable: true},
{type: 'text', key: 'isQuickShareEnabled', title: 'Quick Shared Enable', sortable: true},
{type: 'text', key: 'isThumbnailGenerationEnabled', title: 'Thumbnail Generation', sortable: true}
{
type: 'text',
key: 'version',
title: 'Description',
sortable: true
},
{
type: 'date',
key: 'installDate',
title: 'Install Date',
sortable: true
},
{
type: 'text',
key: 'installState',
title: 'Install State',
sortable: true
},
{
type: 'text',
key: 'versionMin',
title: 'Version Minor',
sortable: true
},
{
type: 'text',
key: 'versionMax',
title: 'Version Max',
sortable: true
}
]);
this.status = new ObjectDataTableAdapter(
[repository.status],
[
{
type: 'text',
key: 'isReadOnly',
title: 'Read Only',
sortable: true
},
{
type: 'text',
key: 'isAuditEnabled',
title: 'Audit Enable',
sortable: true
},
{
type: 'text',
key: 'isQuickShareEnabled',
title: 'Quick Shared Enable',
sortable: true
},
{
type: 'text',
key: 'isThumbnailGenerationEnabled',
title: 'Thumbnail Generation',
sortable: true
}
]
);
if (repository.license) {
this.license = new ObjectDataTableAdapter([repository.license], [
{type: 'date', key: 'issuedAt', title: 'Issued At', sortable: true},
{type: 'date', key: 'expiresAt', title: 'Expires At', sortable: true},
{type: 'text', key: 'remainingDays', title: 'Remaining Days', sortable: true},
this.license = new ObjectDataTableAdapter(
[repository.license],
[
{
type: 'date',
key: 'issuedAt',
title: 'Issued At',
sortable: true
},
{
type: 'date',
key: 'expiresAt',
title: 'Expires At',
sortable: true
},
{
type: 'text',
key: 'remainingDays',
title: 'Remaining Days',
sortable: true
},
{ type: 'text', key: 'holder', title: 'Holder', sortable: true },
{ type: 'text', key: 'mode', title: 'Type', sortable: true },
{type: 'text', key: 'isClusterEnabled', title: 'Cluster Enabled', sortable: true},
{type: 'text', key: 'isCryptodocEnabled', title: 'Cryptodoc Enable', sortable: true}
]);
{
type: 'text',
key: 'isClusterEnabled',
title: 'Cluster Enabled',
sortable: true
},
{
type: 'text',
key: 'isCryptodocEnabled',
title: 'Cryptodoc Enable',
sortable: true
}
]
);
}
});
this.http.get('/versions.json')
.subscribe((response: any) => {
this.http.get('/versions.json').subscribe((response: any) => {
const regexp = new RegExp('^(@alfresco|alfresco-)');
const alfrescoPackagesTableRepresentation = Object.keys(response.dependencies)
.filter((val) => regexp.test(val))
.map((val) => ({
const alfrescoPackagesTableRepresentation = Object.keys(
response.dependencies
)
.filter(val => regexp.test(val))
.map(val => ({
name: val,
version: response.dependencies[val].version
}));
this.data = new ObjectDataTableAdapter(alfrescoPackagesTableRepresentation, [
this.data = new ObjectDataTableAdapter(
alfrescoPackagesTableRepresentation,
[
{ type: 'text', key: 'name', title: 'Name', sortable: true },
{ type: 'text', key: 'version', title: 'Version', sortable: true }
]);
]
);
this.releaseVersion = response.version;
});

View File

@@ -37,12 +37,7 @@ const routes: Routes = [
];
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
RouterModule.forChild(routes)
],
imports: [CommonModule, CoreModule.forChild(), RouterModule.forChild(routes)],
declarations: [AboutComponent]
})
export class AboutModule {
}
export class AboutModule {}

View File

@@ -34,19 +34,35 @@ import {
} from '@angular/animations';
export const contextMenuAnimation = [
state('void', style({
state(
'void',
style({
opacity: 0,
transform: 'scale(0.01, 0.01)'
})),
transition('void => *', sequence([
})
),
transition(
'void => *',
sequence([
query('.mat-menu-content', style({ opacity: 0 })),
animate('100ms linear', style({ opacity: 1, transform: 'scale(1, 0.5)' })),
animate(
'100ms linear',
style({ opacity: 1, transform: 'scale(1, 0.5)' })
),
group([
query('.mat-menu-content', animate('400ms cubic-bezier(0.55, 0, 0.55, 0.2)',
query(
'.mat-menu-content',
animate(
'400ms cubic-bezier(0.55, 0, 0.55, 0.2)',
style({ opacity: 1 })
)),
animate('300ms cubic-bezier(0.25, 0.8, 0.25, 1)', style({ transform: 'scale(1, 1)' })),
)
),
animate(
'300ms cubic-bezier(0.25, 0.8, 0.25, 1)',
style({ transform: 'scale(1, 1)' })
)
])
])),
])
),
transition('* => void', animate('150ms 50ms linear', style({ opacity: 0 })))
];

View File

@@ -27,13 +27,13 @@ import { Directive, ElementRef, OnDestroy } from '@angular/core';
import { FocusableOption, FocusMonitor, FocusOrigin } from '@angular/cdk/a11y';
@Directive({
selector: '[acaContextMenuItem]',
selector: '[acaContextMenuItem]'
})
export class ContextMenuItemDirective implements OnDestroy, FocusableOption {
constructor(
private elementRef: ElementRef,
private focusMonitor: FocusMonitor) {
private focusMonitor: FocusMonitor
) {
focusMonitor.monitor(this.getHostElement(), false);
}

View File

@@ -1,15 +1,21 @@
import { Directive, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';
import {
Directive,
Output,
EventEmitter,
OnInit,
OnDestroy
} from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { delay } from 'rxjs/operators';
@Directive({
selector: '[acaContextMenuOutsideEvent]'
})
export class OutsideEventDirective implements OnInit, OnDestroy {
private subscriptions: Subscription[] = [];
@Output() clickOutside: EventEmitter<null> = new EventEmitter();
@Output()
clickOutside: EventEmitter<null> = new EventEmitter();
constructor() {}

View File

@@ -26,7 +26,6 @@
import { OverlayRef } from '@angular/cdk/overlay';
export class ContextMenuOverlayRef {
constructor(private overlayRef: OverlayRef) {}
close(): void {

View File

@@ -24,8 +24,14 @@
*/
import {
Component, ViewEncapsulation, OnInit, OnDestroy, HostListener,
ViewChildren, QueryList, AfterViewInit
Component,
ViewEncapsulation,
OnInit,
OnDestroy,
HostListener,
ViewChildren,
QueryList,
AfterViewInit
} from '@angular/core';
import { trigger } from '@angular/animations';
import { FocusKeyManager } from '@angular/cdk/a11y';
@@ -55,9 +61,7 @@ import { ContextMenuItemDirective } from './context-menu-item.directive';
class: 'aca-context-menu'
},
encapsulation: ViewEncapsulation.None,
animations: [
trigger('panelAnimation', contextMenuAnimation)
]
animations: [trigger('panelAnimation', contextMenuAnimation)]
})
export class ContextMenuComponent implements OnInit, OnDestroy, AfterViewInit {
private onDestroy$: Subject<boolean> = new Subject<boolean>();
@@ -100,7 +104,7 @@ export class ContextMenuComponent implements OnInit, OnDestroy, AfterViewInit {
constructor(
private contextMenuOverlayRef: ContextMenuOverlayRef,
private extensions: AppExtensionService,
private store: Store<AppStore>,
private store: Store<AppStore>
) {}
onClickOutsideEvent() {
@@ -136,7 +140,9 @@ export class ContextMenuComponent implements OnInit, OnDestroy, AfterViewInit {
}
ngAfterViewInit() {
this._keyManager = new FocusKeyManager<ContextMenuItemDirective>(this.contextMenuItems);
this._keyManager = new FocusKeyManager<ContextMenuItemDirective>(
this.contextMenuItems
);
this._keyManager.setFirstItemActive();
}
}

View File

@@ -40,7 +40,8 @@ export class ContextActionsDirective {
private overlayRef: ContextMenuOverlayRef = null;
// tslint:disable-next-line:no-input-rename
@Input('acaContextEnable') enabled = true;
@Input('acaContextEnable')
enabled = true;
@HostListener('window:resize', ['$event'])
onResize(event) {
@@ -93,7 +94,7 @@ export class ContextActionsDirective {
source: event,
hasBackdrop: false,
backdropClass: 'cdk-overlay-transparent-backdrop',
panelClass: 'cdk-overlay-pane',
panelClass: 'cdk-overlay-pane'
});
}
@@ -104,22 +105,27 @@ export class ContextActionsDirective {
}
private isInSelection(row: DataRow): MinimalNodeEntity {
return this.documentList.selection.find((selected) =>
row.getValue('name') === selected.entry.name);
return this.documentList.selection.find(
selected => row.getValue('name') === selected.entry.name
);
}
private getSelectedRow(event): DataRow {
const rowElement = this.findAncestor(<HTMLElement>event.target, 'adf-datatable-row');
const rowElement = this.findAncestor(
<HTMLElement>event.target,
'adf-datatable-row'
);
if (!rowElement) {
return null;
}
const rowName = rowElement.querySelector('.adf-data-table-cell--text .adf-datatable-cell')
.textContent
.trim();
const rowName = rowElement
.querySelector('.adf-data-table-cell--text .adf-datatable-cell')
.textContent.trim();
return this.documentList.data.getRows()
return this.documentList.data
.getRows()
.find((row: DataRow) => row.getValue('name') === rowName);
}

View File

@@ -24,7 +24,12 @@
*/
import { NgModule, ModuleWithProviders } from '@angular/core';
import { MatMenuModule, MatListModule, MatIconModule, MatButtonModule } from '@angular/material';
import {
MatMenuModule,
MatListModule,
MatIconModule,
MatButtonModule
} from '@angular/material';
import { BrowserModule } from '@angular/platform-browser';
import { CoreModule } from '@alfresco/adf-core';
import { CoreExtensionsModule } from '../../extensions/core.extensions.module';
@@ -58,17 +63,13 @@ import { OutsideEventDirective } from './context-menu-outside-event.directive';
ContextActionsDirective,
ContextMenuComponent
],
entryComponents: [
ContextMenuComponent
]
entryComponents: [ContextMenuComponent]
})
export class ContextMenuModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: ContextMenuModule,
providers: [
ContextMenuService
]
providers: [ContextMenuService]
};
}

View File

@@ -7,12 +7,9 @@ import { ContextmenuOverlayConfig } from './interfaces';
@Injectable()
export class ContextMenuService {
constructor(
private injector: Injector,
private overlay: Overlay) { }
constructor(private injector: Injector, private overlay: Overlay) {}
open(config: ContextmenuOverlayConfig) {
const overlay = this.createOverlay(config);
const overlayRef = new ContextMenuOverlayRef(overlay);
@@ -23,11 +20,14 @@ export class ContextMenuService {
// prevent native contextmenu on overlay element if config.hasBackdrop is true
if (config.hasBackdrop) {
(<any>overlay)._backdropElement
.addEventListener('contextmenu', () => {
(<any>overlay)._backdropElement.addEventListener(
'contextmenu',
() => {
event.preventDefault();
(<any>overlay)._backdropClick.next(null);
}, true);
},
true
);
}
return overlayRef;
@@ -38,16 +38,29 @@ export class ContextMenuService {
return this.overlay.create(overlayConfig);
}
private attachDialogContainer(overlay: OverlayRef, config: ContextmenuOverlayConfig, contextmenuOverlayRef: ContextMenuOverlayRef) {
private attachDialogContainer(
overlay: OverlayRef,
config: ContextmenuOverlayConfig,
contextmenuOverlayRef: ContextMenuOverlayRef
) {
const injector = this.createInjector(config, contextmenuOverlayRef);
const containerPortal = new ComponentPortal(ContextMenuComponent, null, injector);
const containerRef: ComponentRef<ContextMenuComponent> = overlay.attach(containerPortal);
const containerPortal = new ComponentPortal(
ContextMenuComponent,
null,
injector
);
const containerRef: ComponentRef<ContextMenuComponent> = overlay.attach(
containerPortal
);
return containerRef.instance;
}
private createInjector(config: ContextmenuOverlayConfig, contextmenuOverlayRef: ContextMenuOverlayRef): PortalInjector {
private createInjector(
config: ContextmenuOverlayConfig,
contextmenuOverlayRef: ContextMenuOverlayRef
): PortalInjector {
const injectionTokens = new WeakMap();
injectionTokens.set(ContextMenuOverlayRef, contextmenuOverlayRef);
@@ -67,23 +80,29 @@ export class ContextMenuService {
})
};
const positionStrategy = this.overlay.position()
const positionStrategy = this.overlay
.position()
.connectedTo(
new ElementRef(fakeElement),
{ originX: 'start', originY: 'bottom' },
{ overlayX: 'start', overlayY: 'top' })
{ overlayX: 'start', overlayY: 'top' }
)
.withFallbackPosition(
{ originX: 'start', originY: 'top' },
{ overlayX: 'start', overlayY: 'bottom' })
{ overlayX: 'start', overlayY: 'bottom' }
)
.withFallbackPosition(
{ originX: 'end', originY: 'top' },
{ overlayX: 'start', overlayY: 'top' })
{ overlayX: 'start', overlayY: 'top' }
)
.withFallbackPosition(
{ originX: 'start', originY: 'top' },
{ overlayX: 'end', overlayY: 'top' })
{ overlayX: 'end', overlayY: 'top' }
)
.withFallbackPosition(
{ originX: 'end', originY: 'center' },
{ overlayX: 'start', overlayY: 'center' })
{ overlayX: 'start', overlayY: 'center' }
)
.withFallbackPosition(
{ originX: 'start', originY: 'center' },
{ overlayX: 'end', overlayY: 'center' }

View File

@@ -18,7 +18,7 @@
text-align: center;
color: inherit;
border-radius: 100%;
background-color: mat-color($background, card, .15);
background-color: mat-color($background, card, 0.15);
}
.current-user__full-name {

View File

@@ -26,7 +26,10 @@
import { Component, ViewEncapsulation } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { selectUser, appLanguagePicker } from '../../store/selectors/app.selectors';
import {
selectUser,
appLanguagePicker
} from '../../store/selectors/app.selectors';
import { AppStore } from '../../store/states';
import { ProfileState } from '@alfresco/adf-extensions';
import { SetSelectedNodesAction } from '../../store/actions';

View File

@@ -28,8 +28,11 @@ import { Router } from '@angular/router';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import {
AlfrescoApiService,
TimeAgoPipe, NodeNameTooltipPipe,
NodeFavoriteDirective, DataTableComponent, AppConfigPipe
TimeAgoPipe,
NodeNameTooltipPipe,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe
} from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { ContentManagementService } from '../../services/content-management.service';
@@ -91,7 +94,9 @@ describe('FavoritesComponent', () => {
alfrescoApi = TestBed.get(AlfrescoApiService);
alfrescoApi.reset();
spyOn(alfrescoApi.favoritesApi, 'getFavorites').and.returnValue(Promise.resolve(page));
spyOn(alfrescoApi.favoritesApi, 'getFavorites').and.returnValue(
Promise.resolve(page)
);
contentApi = TestBed.get(ContentApiService);
@@ -142,7 +147,10 @@ describe('FavoritesComponent', () => {
component.navigate(node);
expect(router.navigate).toHaveBeenCalledWith([ '/libraries', 'folder-node' ]);
expect(router.navigate).toHaveBeenCalledWith([
'/libraries',
'folder-node'
]);
});
it('navigates to `/personal-files` if node path has no `Sites`', () => {
@@ -150,7 +158,10 @@ describe('FavoritesComponent', () => {
component.navigate(node);
expect(router.navigate).toHaveBeenCalledWith([ '/personal-files', 'folder-node' ]);
expect(router.navigate).toHaveBeenCalledWith([
'/personal-files',
'folder-node'
]);
});
it('does not navigate when node is not folder', () => {

View File

@@ -69,10 +69,7 @@ export class FavoritesComponent extends PageComponent implements OnInit {
this.content.favoriteToggle.subscribe(() => this.reload()),
this.breakpointObserver
.observe([
Breakpoints.HandsetPortrait,
Breakpoints.HandsetLandscape
])
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
@@ -94,9 +91,7 @@ export class FavoritesComponent extends PageComponent implements OnInit {
.getNode(id)
.pipe(map(node => node.entry))
.subscribe(({ path }: MinimalNodeEntryEntity) => {
const routeUrl = isSitePath(path)
? '/libraries'
: '/personal-files';
const routeUrl = isSitePath(path) ? '/libraries' : '/personal-files';
this.router.navigate([routeUrl, id]);
});
}

View File

@@ -23,11 +23,19 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { TestBed, fakeAsync, tick, ComponentFixture } from '@angular/core/testing';
import {
TestBed,
fakeAsync,
tick,
ComponentFixture
} from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {
TimeAgoPipe, NodeNameTooltipPipe, FileSizePipe, NodeFavoriteDirective,
TimeAgoPipe,
NodeNameTooltipPipe,
FileSizePipe,
NodeFavoriteDirective,
DataTableComponent,
UploadService,
AppConfigPipe
@@ -66,10 +74,13 @@ describe('FilesComponent', () => {
ExperimentalDirective
],
providers: [
{ provide: ActivatedRoute, useValue: {
{
provide: ActivatedRoute,
useValue: {
snapshot: { data: { preferencePrefix: 'prefix' } },
params: of({ folderId: 'someId' })
} }
}
}
],
schemas: [NO_ERRORS_SCHEMA]
});
@@ -126,7 +137,10 @@ describe('FilesComponent', () => {
fixture.detectChanges();
expect(router.navigate['calls'].argsFor(0)[0]).toEqual(['/personal-files', 'parent-id']);
expect(router.navigate['calls'].argsFor(0)[0]).toEqual([
'/personal-files',
'parent-id'
]);
});
});
@@ -239,7 +253,6 @@ describe('FilesComponent', () => {
}));
});
describe('onBreadcrumbNavigate()', () => {
beforeEach(() => {
spyOn(contentApi, 'getNode').and.returnValue(of({ entry: node }));
@@ -267,7 +280,10 @@ describe('FilesComponent', () => {
it('should navigates to node when id provided', () => {
component.navigate(node.id);
expect(router.navigate).toHaveBeenCalledWith(['./', node.id], jasmine.any(Object));
expect(router.navigate).toHaveBeenCalledWith(
['./', node.id],
jasmine.any(Object)
);
});
it('should navigates to home when id not provided', () => {

View File

@@ -27,7 +27,12 @@ import { FileUploadEvent, UploadService } from '@alfresco/adf-core';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { MinimalNodeEntity, MinimalNodeEntryEntity, PathElement, PathElementEntity } from 'alfresco-js-api';
import {
MinimalNodeEntity,
MinimalNodeEntryEntity,
PathElement,
PathElementEntity
} from 'alfresco-js-api';
import { ContentManagementService } from '../../services/content-management.service';
import { NodeActionsService } from '../../services/node-actions.service';
import { AppStore } from '../../store/states/app.state';
@@ -42,13 +47,13 @@ import { debounceTime } from 'rxjs/operators';
templateUrl: './files.component.html'
})
export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
isValidPath = true;
isSmallScreen = false;
private nodePath: PathElement[];
constructor(private router: Router,
constructor(
private router: Router,
private route: ActivatedRoute,
private contentApi: ContentApiService,
store: Store<AppStore>,
@@ -56,7 +61,8 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
private uploadService: UploadService,
content: ContentManagementService,
extensions: AppExtensionService,
private breakpointObserver: BreakpointObserver) {
private breakpointObserver: BreakpointObserver
) {
super(store, extensions, content);
}
@@ -71,40 +77,40 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
route.params.subscribe(({ folderId }: Params) => {
const nodeId = folderId || data.defaultNodeId;
this.contentApi
.getNode(nodeId)
.subscribe(
this.contentApi.getNode(nodeId).subscribe(
node => {
this.isValidPath = true;
if (node.entry && node.entry.isFolder) {
this.updateCurrentNode(node.entry);
} else {
this.router.navigate(
['/personal-files', node.entry.parentId],
{ replaceUrl: true }
);
this.router.navigate(['/personal-files', node.entry.parentId], {
replaceUrl: true
});
}
},
() => this.isValidPath = false
() => (this.isValidPath = false)
);
});
this.subscriptions = this.subscriptions.concat([
nodeActionsService.contentCopied.subscribe((nodes) => this.onContentCopied(nodes)),
nodeActionsService.contentCopied.subscribe(nodes =>
this.onContentCopied(nodes)
),
content.folderCreated.subscribe(() => this.documentList.reload()),
content.folderEdited.subscribe(() => this.documentList.reload()),
content.nodesDeleted.subscribe(() => this.documentList.reload()),
content.nodesMoved.subscribe(() => this.documentList.reload()),
content.nodesRestored.subscribe(() => this.documentList.reload()),
uploadService.fileUploadComplete.pipe(debounceTime(300)).subscribe(file => this.onFileUploadedEvent(file)),
uploadService.fileUploadDeleted.pipe(debounceTime(300)).subscribe((file) => this.onFileUploadedEvent(file)),
uploadService.fileUploadComplete
.pipe(debounceTime(300))
.subscribe(file => this.onFileUploadedEvent(file)),
uploadService.fileUploadDeleted
.pipe(debounceTime(300))
.subscribe(file => this.onFileUploadedEvent(file)),
this.breakpointObserver
.observe([
Breakpoints.HandsetPortrait,
Breakpoints.HandsetLandscape
])
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
@@ -149,7 +155,10 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
onBreadcrumbNavigate(route: PathElementEntity) {
// todo: review this approach once 5.2.3 is out
if (this.nodePath && this.nodePath.length > 2) {
if (this.nodePath[1].name === 'Sites' && this.nodePath[2].id === route.id) {
if (
this.nodePath[1].name === 'Sites' &&
this.nodePath[2].id === route.id
) {
return this.navigate(this.nodePath[3].id);
}
}
@@ -173,11 +182,14 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
if (event && event.file.options.parentId) {
if (this.nodePath) {
const correspondingNodePath = this.nodePath.find(pathItem => pathItem.id === event.file.options.parentId);
const correspondingNodePath = this.nodePath.find(
pathItem => pathItem.id === event.file.options.parentId
);
// check if the current folder has the 'trigger-upload-folder' as one of its parents
if (correspondingNodePath) {
const correspondingIndex = this.nodePath.length - this.nodePath.indexOf(correspondingNodePath);
const correspondingIndex =
this.nodePath.length - this.nodePath.indexOf(correspondingNodePath);
this.displayFolderParent(event.file.options.path, correspondingIndex);
}
}
@@ -189,7 +201,8 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
const currentFoldersDisplayed: any = this.documentList.data.getRows() || [];
const alreadyDisplayedParentFolder = currentFoldersDisplayed.find(
row => row.node.entry.isFolder && row.node.entry.name === parentName);
row => row.node.entry.isFolder && row.node.entry.name === parentName
);
if (alreadyDisplayedParentFolder) {
return;
@@ -198,9 +211,10 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
}
onContentCopied(nodes: MinimalNodeEntity[]) {
const newNode = nodes
.find((node) => {
return node && node.entry && node.entry.parentId === this.getParentNodeId();
const newNode = nodes.find(node => {
return (
node && node.entry && node.entry.parentId === this.getParentNodeId()
);
});
if (newNode) {
this.documentList.reload();
@@ -241,7 +255,9 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
if (this.isSiteContainer(node)) {
// rename 'documentLibrary' entry to the target site display name
// clicking on the breadcrumb entry loads the site content
const parentNode = await this.contentApi.getNodeInfo(node.parentId).toPromise();
const parentNode = await this.contentApi
.getNodeInfo(node.parentId)
.toPromise();
node.name = parentNode.properties['cm:title'] || parentNode.name;
// remove the site entry
@@ -251,7 +267,9 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
const docLib = elements.findIndex(el => el.name === 'documentLibrary');
if (docLib > -1) {
const siteFragment = elements[docLib - 1];
const siteNode = await this.contentApi.getNodeInfo(siteFragment.id).toPromise();
const siteNode = await this.contentApi
.getNodeInfo(siteFragment.id)
.toPromise();
// apply Site Name to the parent fragment
siteFragment.name = siteNode.properties['cm:title'] || siteNode.name;
@@ -268,7 +286,12 @@ export class FilesComponent extends PageComponent implements OnInit, OnDestroy {
}
isRootNode(nodeId: string): boolean {
if (this.node && this.node.path && this.node.path.elements && this.node.path.elements.length > 0) {
if (
this.node &&
this.node.path &&
this.node.path.elements &&
this.node.path.elements.length > 0
) {
return this.node.path.elements[0].id === nodeId;
}
return false;

View File

@@ -23,7 +23,11 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { Component, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/core';
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy
} from '@angular/core';
@Component({
selector: 'aca-generic-error',
@@ -33,4 +37,3 @@ import { Component, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/
host: { class: 'aca-generic-error' }
})
export class GenericErrorComponent {}

View File

@@ -34,8 +34,10 @@ import { SidebarTabRef } from '@alfresco/adf-extensions';
templateUrl: './info-drawer.component.html'
})
export class InfoDrawerComponent implements OnChanges, OnInit {
@Input() nodeId: string;
@Input() node: MinimalNodeEntity;
@Input()
nodeId: string;
@Input()
node: MinimalNodeEntity;
isLoading = false;
displayNode: MinimalNodeEntryEntity;
@@ -89,7 +91,7 @@ export class InfoDrawerComponent implements OnChanges, OnInit {
this.setDisplayNode(entity);
this.isLoading = false;
},
() => this.isLoading = false
() => (this.isLoading = false)
);
}
}

View File

@@ -38,7 +38,7 @@ import { NodePermissionService } from '../../../services/node-permission.service
</adf-content-metadata-card>
`,
encapsulation: ViewEncapsulation.None,
host: { 'class': 'app-metadata-tab' }
host: { class: 'app-metadata-tab' }
})
export class MetadataTabComponent {
@Input()

View File

@@ -39,10 +39,7 @@ describe('LayoutComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
LayoutComponent,
SidenavViewsManagerDirective
],
declarations: [LayoutComponent, SidenavViewsManagerDirective],
schemas: [NO_ERRORS_SCHEMA]
});

View File

@@ -91,15 +91,11 @@ export class LayoutComponent implements OnInit, OnDestroy {
.pipe(takeUntil(this.onDestroy$))
.subscribe(node => {
this.node = node;
this.canUpload =
node && this.permission.check(node, ['create']);
this.canUpload = node && this.permission.check(node, ['create']);
});
this.breakpointObserver
.observe([
Breakpoints.HandsetPortrait,
Breakpoints.HandsetLandscape
])
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
});

View File

@@ -12,7 +12,8 @@ import { filter } from 'rxjs/operators';
exportAs: 'acaSidenavManager'
})
export class SidenavViewsManagerDirective {
@ContentChild(SidenavLayoutComponent) sidenavLayout: SidenavLayoutComponent;
@ContentChild(SidenavLayoutComponent)
sidenavLayout: SidenavLayoutComponent;
minimizeSidenav = false;
hideSidenav = false;
@@ -81,10 +82,8 @@ export class SidenavViewsManagerDirective {
if (preserveState) {
return (
this.userPreferenceService.get(
'expandedSidenav',
expand.toString()
) === 'true'
this.userPreferenceService.get('expandedSidenav', expand.toString()) ===
'true'
);
}

View File

@@ -29,7 +29,11 @@ import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router } from '@angular/router';
import {
AlfrescoApiService,
TimeAgoPipe, NodeNameTooltipPipe, NodeFavoriteDirective, DataTableComponent, AppConfigPipe
TimeAgoPipe,
NodeNameTooltipPipe,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe
} from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { ShareDataTableAdapter } from '@alfresco/adf-content-services';
@@ -86,8 +90,12 @@ describe('LibrariesComponent', () => {
alfrescoApi.reset();
router = TestBed.get(Router);
spyOn(alfrescoApi.sitesApi, 'getSites').and.returnValue((Promise.resolve(page)));
spyOn(alfrescoApi.peopleApi, 'getSiteMembership').and.returnValue((Promise.resolve({})));
spyOn(alfrescoApi.sitesApi, 'getSites').and.returnValue(
Promise.resolve(page)
);
spyOn(alfrescoApi.peopleApi, 'getSiteMembership').and.returnValue(
Promise.resolve({})
);
contentApi = TestBed.get(ContentApiService);
});
@@ -119,7 +127,9 @@ describe('LibrariesComponent', () => {
node.title = 'title';
const data = new ShareDataTableAdapter(null, null);
data.setRows([<any>{ node: { entry: { id: 'some-id', title: 'title' } } }]);
data.setRows([
<any>{ node: { entry: { id: 'some-id', title: 'title' } } }
]);
component.documentList.data = data;
@@ -131,7 +141,9 @@ describe('LibrariesComponent', () => {
node.title = 'title';
const data = new ShareDataTableAdapter(null, null);
data.setRows([<any>{ node: { entry: { id: 'some-id', title: 'title-some-id' } } }]);
data.setRows([
<any>{ node: { entry: { id: 'some-id', title: 'title-some-id' } } }
]);
component.documentList.data = data;
const title = component.makeLibraryTitle(node);

View File

@@ -41,16 +41,17 @@ import { map } from 'rxjs/operators';
templateUrl: './libraries.component.html'
})
export class LibrariesComponent extends PageComponent implements OnInit {
isSmallScreen = false;
constructor(private route: ActivatedRoute,
constructor(
private route: ActivatedRoute,
content: ContentManagementService,
private contentApi: ContentApiService,
store: Store<AppStore>,
extensions: AppExtensionService,
private router: Router,
private breakpointObserver: BreakpointObserver) {
private breakpointObserver: BreakpointObserver
) {
super(store, extensions, content);
}
@@ -64,10 +65,7 @@ export class LibrariesComponent extends PageComponent implements OnInit {
}),
this.breakpointObserver
.observe([
Breakpoints.HandsetPortrait,
Breakpoints.HandsetLandscape
])
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})
@@ -88,9 +86,8 @@ export class LibrariesComponent extends PageComponent implements OnInit {
let isDuplicate = false;
if (entries) {
isDuplicate = entries
.some((entry: any) => {
return (entry.id !== id && entry.title === title);
isDuplicate = entries.some((entry: any) => {
return entry.id !== id && entry.title === title;
});
}
@@ -109,7 +106,9 @@ export class LibrariesComponent extends PageComponent implements OnInit {
.getNode(libraryId, { relativePath: '/documentLibrary' })
.pipe(map(node => node.entry))
.subscribe(documentLibrary => {
this.router.navigate([ './', documentLibrary.id ], { relativeTo: this.route });
this.router.navigate(['./', documentLibrary.id], {
relativeTo: this.route
});
});
}
}

View File

@@ -23,7 +23,14 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { Component, Input, ChangeDetectionStrategy, OnInit, ViewEncapsulation, HostListener } from '@angular/core';
import {
Component,
Input,
ChangeDetectionStrategy,
OnInit,
ViewEncapsulation,
HostListener
} from '@angular/core';
import { PathInfo, MinimalNodeEntity } from 'alfresco-js-api';
import { Observable, BehaviorSubject, of } from 'rxjs';
@@ -41,7 +48,7 @@ import { ContentApiService } from '../../services/content-api.service';
`,
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: { 'class': 'aca-location-link adf-location-cell' }
host: { class: 'aca-location-link adf-location-cell' }
})
export class LocationLinkComponent implements OnInit {
private _path: PathInfo;
@@ -60,14 +67,15 @@ export class LocationLinkComponent implements OnInit {
@Input()
tooltip: Observable<string>;
@HostListener('mouseenter') onMouseEnter() {
@HostListener('mouseenter')
onMouseEnter() {
this.getTooltip(this._path);
}
constructor(
private store: Store<AppStore>,
private contentApi: ContentApiService) {
}
private contentApi: ContentApiService
) {}
goToLocation() {
if (this.context) {
@@ -100,7 +108,11 @@ export class LocationLinkComponent implements OnInit {
}
// for non-admin users
if (elements.length === 3 && elements[0] === 'Company Home' && elements[1] === 'User Homes') {
if (
elements.length === 3 &&
elements[0] === 'Company Home' &&
elements[1] === 'User Homes'
) {
return of('Personal Files');
}
@@ -112,7 +124,9 @@ export class LocationLinkComponent implements OnInit {
return new Observable<string>(observer => {
this.contentApi.getNodeInfo(fragment.id).subscribe(
node => {
observer.next(node.properties['cm:title'] || node.name || fragment.name);
observer.next(
node.properties['cm:title'] || node.name || fragment.name
);
observer.complete();
},
() => {
@@ -141,7 +155,8 @@ export class LocationLinkComponent implements OnInit {
this.contentApi.getNodeInfo(fragment.id).subscribe(
node => {
elements.splice(0, 2);
elements[0].name = node.properties['cm:title'] || node.name || fragment.name;
elements[0].name =
node.properties['cm:title'] || node.name || fragment.name;
elements.splice(1, 1);
elements.unshift({ id: null, name: 'File Libraries' });

View File

@@ -27,7 +27,11 @@ import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AuthenticationService, UserPreferencesService, AppConfigPipe } from '@alfresco/adf-core';
import {
AuthenticationService,
UserPreferencesService,
AppConfigPipe
} from '@alfresco/adf-core';
import { LoginComponent } from './login.component';
import { AppTestingModule } from '../../testing/app-testing.module';
@@ -41,13 +45,8 @@ describe('LoginComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
LoginComponent,
AppConfigPipe
],
providers: [
Location
],
declarations: [LoginComponent, AppConfigPipe],
providers: [Location],
schemas: [NO_ERRORS_SCHEMA]
});

View File

@@ -33,7 +33,7 @@ import { AuthenticationService } from '@alfresco/adf-core';
export class LoginComponent implements OnInit {
constructor(
private location: Location,
private auth: AuthenticationService,
private auth: AuthenticationService
) {}
ngOnInit() {

View File

@@ -23,7 +23,10 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { DocumentListComponent, ShareDataRow } from '@alfresco/adf-content-services';
import {
DocumentListComponent,
ShareDataRow
} from '@alfresco/adf-content-services';
import { ContentActionRef, SelectionState } from '@alfresco/adf-extensions';
import { OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Store } from '@ngrx/store';
@@ -33,11 +36,16 @@ import { takeUntil } from 'rxjs/operators';
import { AppExtensionService } from '../extensions/extension.service';
import { ContentManagementService } from '../services/content-management.service';
import { SetSelectedNodesAction, ViewFileAction } from '../store/actions';
import { appSelection, currentFolder, documentDisplayMode, infoDrawerOpened, sharedUrl } from '../store/selectors/app.selectors';
import {
appSelection,
currentFolder,
documentDisplayMode,
infoDrawerOpened,
sharedUrl
} from '../store/selectors/app.selectors';
import { AppStore } from '../store/states/app.state';
export abstract class PageComponent implements OnInit, OnDestroy {
onDestroy$: Subject<boolean> = new Subject<boolean>();
@ViewChild(DocumentListComponent)
@@ -57,13 +65,17 @@ export abstract class PageComponent implements OnInit, OnDestroy {
protected subscriptions: Subscription[] = [];
static isLockedNode(node) {
return node.isLocked || (node.properties && node.properties['cm:lockType'] === 'READ_ONLY_LOCK');
return (
node.isLocked ||
(node.properties && node.properties['cm:lockType'] === 'READ_ONLY_LOCK')
);
}
constructor(
protected store: Store<AppStore>,
protected extensions: AppExtensionService,
protected content: ContentManagementService) {}
protected content: ContentManagementService
) {}
ngOnInit() {
this.sharedPreviewUrl$ = this.store.select(sharedUrl);
@@ -77,10 +89,13 @@ export abstract class PageComponent implements OnInit, OnDestroy {
this.selection = selection;
this.actions = this.extensions.getAllowedToolbarActions();
this.viewerToolbarActions = this.extensions.getViewerToolbarActions();
this.canUpdateNode = this.selection.count === 1 && this.content.canUpdateNode(selection.first);
this.canUpdateNode =
this.selection.count === 1 &&
this.content.canUpdateNode(selection.first);
});
this.store.select(currentFolder)
this.store
.select(currentFolder)
.pipe(takeUntil(this.onDestroy$))
.subscribe(node => {
this.canUpload = node && this.content.canUploadContent(node);

View File

@@ -24,7 +24,10 @@
*/
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NodePermissionDialogService, PermissionListComponent } from '@alfresco/adf-content-services';
import {
NodePermissionDialogService,
PermissionListComponent
} from '@alfresco/adf-content-services';
import { MinimalNodeEntryEntity } from 'alfresco-js-api';
import { Store } from '@ngrx/store';
import { AppStore } from '../../store/states/app.state';
@@ -51,11 +54,12 @@ export class PermissionsManagerComponent implements OnInit {
private dialog: MatDialog,
private contentApi: ContentApiService,
private nodePermissionDialogService: NodePermissionDialogService
) {
}
) {}
ngOnInit() {
this.contentApi.getNodeInfo(this.nodeId, {include: ['permissions'] }).subscribe( (currentNode: MinimalNodeEntryEntity) => {
this.contentApi
.getNodeInfo(this.nodeId, { include: ['permissions'] })
.subscribe((currentNode: MinimalNodeEntryEntity) => {
this.toggleStatus = currentNode.permissions.isInheritanceEnabled;
});
}
@@ -74,16 +78,17 @@ export class PermissionsManagerComponent implements OnInit {
}
openAddPermissionDialog(event: Event) {
this.nodePermissionDialogService.updateNodePermissionByDialog(this.nodeId)
.subscribe(() => {
this.nodePermissionDialogService
.updateNodePermissionByDialog(this.nodeId)
.subscribe(
() => {
this.dialog.open(NodePermissionsDialogComponent, {
data: { nodeId: this.nodeId },
panelClass: 'aca-permissions-dialog-panel',
width: '800px'
}
);
});
},
(error) => {
error => {
this.store.dispatch(new SnackbarErrorAction(error));
}
);

View File

@@ -26,7 +26,11 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { UserPreferencesService, AppConfigPipe, NodeFavoriteDirective } from '@alfresco/adf-core';
import {
UserPreferencesService,
AppConfigPipe,
NodeFavoriteDirective
} from '@alfresco/adf-core';
import { PreviewComponent } from './preview.component';
import { of, throwError } from 'rxjs';
import { EffectsModule } from '@ngrx/effects';
@@ -36,7 +40,6 @@ import { AppTestingModule } from '../../testing/app-testing.module';
import { ContentApiService } from '../../services/content-api.service';
describe('PreviewComponent', () => {
let fixture: ComponentFixture<PreviewComponent>;
let component: PreviewComponent;
let router: Router;
@@ -46,10 +49,7 @@ describe('PreviewComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppTestingModule,
EffectsModule.forRoot([NodeEffects])
],
imports: [AppTestingModule, EffectsModule.forRoot([NodeEffects])],
declarations: [
AppConfigPipe,
PreviewComponent,
@@ -83,9 +83,12 @@ describe('PreviewComponent', () => {
component.previousNodeId = 'previous1';
component.onNavigateBefore();
expect(router.navigate).toHaveBeenCalledWith(
['personal-files', 'folder1', 'preview', 'previous1']
);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'folder1',
'preview',
'previous1'
]);
});
it('should navigate back to previous node in the root path', () => {
@@ -96,9 +99,11 @@ describe('PreviewComponent', () => {
component.previousNodeId = 'previous1';
component.onNavigateBefore();
expect(router.navigate).toHaveBeenCalledWith(
['personal-files', 'preview', 'previous1']
);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'preview',
'previous1'
]);
});
it('should not navigate back if node unset', () => {
@@ -118,9 +123,12 @@ describe('PreviewComponent', () => {
component.nextNodeId = 'next1';
component.onNavigateNext();
expect(router.navigate).toHaveBeenCalledWith(
['personal-files', 'folder1', 'preview', 'next1']
);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'folder1',
'preview',
'next1'
]);
});
it('should navigate to next node in the root path', () => {
@@ -131,9 +139,11 @@ describe('PreviewComponent', () => {
component.nextNodeId = 'next1';
component.onNavigateNext();
expect(router.navigate).toHaveBeenCalledWith(
['personal-files', 'preview', 'next1']
);
expect(router.navigate).toHaveBeenCalledWith([
'personal-files',
'preview',
'next1'
]);
});
it('should not navigate back if node unset', () => {
@@ -148,33 +158,37 @@ describe('PreviewComponent', () => {
it('should generate preview path for a folder only', () => {
component.previewLocation = 'personal-files';
expect(component.getPreviewPath('folder1', null)).toEqual(
['personal-files', 'folder1']
);
expect(component.getPreviewPath('folder1', null)).toEqual([
'personal-files',
'folder1'
]);
});
it('should generate preview path for a folder and a node', () => {
component.previewLocation = 'personal-files';
expect(component.getPreviewPath('folder1', 'node1')).toEqual(
['personal-files', 'folder1', 'preview', 'node1']
);
expect(component.getPreviewPath('folder1', 'node1')).toEqual([
'personal-files',
'folder1',
'preview',
'node1'
]);
});
it('should generate preview path for a node only', () => {
component.previewLocation = 'personal-files';
expect(component.getPreviewPath(null, 'node1')).toEqual(
['personal-files', 'preview', 'node1']
);
expect(component.getPreviewPath(null, 'node1')).toEqual([
'personal-files',
'preview',
'node1'
]);
});
it('should generate preview for the location only', () => {
component.previewLocation = 'personal-files';
expect(component.getPreviewPath(null, null)).toEqual(
['personal-files']
);
expect(component.getPreviewPath(null, null)).toEqual(['personal-files']);
});
it('should navigate back to root path upon close', () => {
@@ -186,9 +200,7 @@ describe('PreviewComponent', () => {
component.onVisibilityChanged(false);
expect(router.navigate).toHaveBeenCalledWith(
['libraries', {}]
);
expect(router.navigate).toHaveBeenCalledWith(['libraries', {}]);
});
it('should navigate back to folder path upon close', () => {
@@ -200,9 +212,7 @@ describe('PreviewComponent', () => {
component.onVisibilityChanged(false);
expect(router.navigate).toHaveBeenCalledWith(
['libraries', {}, 'site1']
);
expect(router.navigate).toHaveBeenCalledWith(['libraries', {}, 'site1']);
});
it('should not navigate to root path for certain routes upon close', () => {
@@ -214,9 +224,7 @@ describe('PreviewComponent', () => {
component.onVisibilityChanged(false);
expect(router.navigate).toHaveBeenCalledWith(
['shared', {}]
);
expect(router.navigate).toHaveBeenCalledWith(['shared', {}]);
});
it('should not navigate back if viewer is still visible', () => {
@@ -315,9 +323,9 @@ describe('PreviewComponent', () => {
});
it('should return nearest nodes', async () => {
spyOn(component, 'getFileIds').and.returnValue(Promise.resolve(
[ 'node1', 'node2', 'node3', 'node4', 'node5' ]
));
spyOn(component, 'getFileIds').and.returnValue(
Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5'])
);
let nearest = await component.getNearestNodes('node1', 'folder1');
expect(nearest).toEqual({ left: null, right: 'node2' });
@@ -330,9 +338,9 @@ describe('PreviewComponent', () => {
});
it('should return empty nearest nodes if node is already deleted', async () => {
spyOn(component, 'getFileIds').and.returnValue(Promise.resolve(
[ 'node1', 'node2', 'node3', 'node4', 'node5' ]
));
spyOn(component, 'getFileIds').and.returnValue(
Promise.resolve(['node1', 'node2', 'node3', 'node4', 'node5'])
);
const nearest = await component.getNearestNodes('node9', 'folder1');
expect(nearest).toEqual({ left: null, right: null });
@@ -340,9 +348,7 @@ describe('PreviewComponent', () => {
it('should not display node when id is missing', async () => {
spyOn(router, 'navigate').and.stub();
spyOn(contentApi, 'getNodeInfo').and.returnValue(
of(null)
);
spyOn(contentApi, 'getNodeInfo').and.returnValue(of(null));
await component.displayNode(null);
@@ -352,9 +358,7 @@ describe('PreviewComponent', () => {
it('should navigate to original location if node not found', async () => {
spyOn(router, 'navigate').and.stub();
spyOn(contentApi, 'getNodeInfo').and.returnValue(
of(null)
);
spyOn(contentApi, 'getNodeInfo').and.returnValue(of(null));
component.previewLocation = 'personal-files';
await component.displayNode('folder1');
@@ -380,9 +384,7 @@ describe('PreviewComponent', () => {
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')
);
spyOn(contentApi, 'getNodeInfo').and.returnValue(throwError('error'));
component.previewLocation = 'personal-files';
await component.displayNode('folder1');
@@ -412,7 +414,10 @@ describe('PreviewComponent', () => {
it('should setup node for displaying', async () => {
spyOn(router, 'navigate').and.stub();
spyOn(component, 'getNearestNodes').and.returnValue({ left: 'node1', right: 'node3' });
spyOn(component, 'getNearestNodes').and.returnValue({
left: 'node1',
right: 'node3'
});
spyOn(contentApi, 'getNodeInfo').and.returnValue(
of({
id: 'node2',
@@ -559,9 +564,21 @@ describe('PreviewComponent', () => {
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) } } } }
{
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) } }
}
}
]
}
})
@@ -579,8 +596,20 @@ describe('PreviewComponent', () => {
of({
list: {
entries: [
{ entry: { nodeId: 'node2', name: 'node 2', modifiedAt: new Date(2) } },
{ entry: { nodeId: 'node1', name: 'node 1', modifiedAt: new Date(1) } }
{
entry: {
nodeId: 'node2',
name: 'node 2',
modifiedAt: new Date(2)
}
},
{
entry: {
nodeId: 'node1',
name: 'node 1',
modifiedAt: new Date(1)
}
}
]
}
})
@@ -597,8 +626,20 @@ describe('PreviewComponent', () => {
of({
list: {
entries: [
{ entry: { nodeId: 'node2', name: 'node 2', modifiedAt: new Date(2) } },
{ entry: { nodeId: 'node1', name: 'node 1', modifiedAt: new Date(1) } }
{
entry: {
nodeId: 'node2',
name: 'node 2',
modifiedAt: new Date(2)
}
},
{
entry: {
nodeId: 'node1',
name: 'node 1',
modifiedAt: new Date(1)
}
}
]
}
})

View File

@@ -24,7 +24,14 @@
*/
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET } from '@angular/router';
import {
ActivatedRoute,
Router,
UrlTree,
UrlSegmentGroup,
UrlSegment,
PRIMARY_OUTLET
} from '@angular/router';
import { UserPreferencesService, ObjectUtils } from '@alfresco/adf-core';
import { Store } from '@ngrx/store';
import { AppStore } from '../../store/states/app.state';
@@ -41,14 +48,19 @@ import { ViewUtilService } from './view-util.service';
templateUrl: 'preview.component.html',
styleUrls: ['preview.component.scss'],
encapsulation: ViewEncapsulation.None,
host: { 'class': 'app-preview' }
host: { class: 'app-preview' }
})
export class PreviewComponent extends PageComponent implements OnInit {
previewLocation: string = null;
routesSkipNavigation = ['shared', 'recent-files', 'favorites'];
navigateSource: string = null;
navigationSources = ['favorites', 'libraries', 'personal-files', 'recent-files', 'shared'];
navigationSources = [
'favorites',
'libraries',
'personal-files',
'recent-files',
'shared'
];
folderId: string = null;
nodeId: string = null;
previousNodeId: string;
@@ -65,7 +77,8 @@ export class PreviewComponent extends PageComponent implements OnInit {
private viewUtils: ViewUtilService,
store: Store<AppStore>,
extensions: AppExtensionService,
content: ContentManagementService) {
content: ContentManagementService
) {
super(store, extensions, content);
}
@@ -112,7 +125,10 @@ export class PreviewComponent extends PageComponent implements OnInit {
this.store.dispatch(new SetSelectedNodesAction([{ entry: this.node }]));
if (this.node && this.node.isFile) {
const nearest = await this.getNearestNodes(this.node.id, this.node.parentId);
const nearest = await this.getNearestNodes(
this.node.id,
this.node.parentId
);
this.previousNodeId = nearest.left;
this.nextNodeId = nearest.right;
@@ -133,7 +149,9 @@ export class PreviewComponent extends PageComponent implements OnInit {
* @param isVisible Indicator whether Viewer is visible or hidden.
*/
onVisibilityChanged(isVisible: boolean): void {
const shouldSkipNavigation = this.routesSkipNavigation.includes(this.previewLocation);
const shouldSkipNavigation = this.routesSkipNavigation.includes(
this.previewLocation
);
if (!isVisible) {
const route = this.getNavigationCommands(this.previewLocation);
@@ -158,9 +176,7 @@ export class PreviewComponent extends PageComponent implements OnInit {
/** Handles navigation to a next document */
onNavigateNext(): void {
if (this.nextNodeId) {
this.router.navigate(
this.getPreviewPath(this.folderId, this.nextNodeId)
);
this.router.navigate(this.getPreviewPath(this.folderId, this.nextNodeId));
}
}
@@ -183,13 +199,15 @@ export class PreviewComponent extends PageComponent implements OnInit {
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 }> {
async getNearestNodes(
nodeId: string,
folderId: string
): Promise<{ left: string; right: string }> {
const empty = {
left: null,
right: null
@@ -223,13 +241,17 @@ export class PreviewComponent extends PageComponent implements OnInit {
*/
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, {
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();
})
.toPromise();
const entries = nodes.list.entries.map(obj => obj.entry);
this.sort(entries, sortKey, sortDirection);
@@ -238,13 +260,17 @@ export class PreviewComponent extends PageComponent implements OnInit {
}
if (source === 'favorites') {
const nodes = await this.contentApi.getFavorites('-me-', {
const nodes = await this.contentApi
.getFavorites('-me-', {
where: '(EXISTS(target/file))',
fields: ['target']
}).toPromise();
})
.toPromise();
const sortKey = this.preferences.get('favorites.sorting.key') || 'modifiedAt';
const sortDirection = this.preferences.get('favorites.sorting.direction') || 'desc';
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);
@@ -252,12 +278,16 @@ export class PreviewComponent extends PageComponent implements OnInit {
}
if (source === 'shared') {
const sortingKey = this.preferences.get('shared.sorting.key') || 'modifiedAt';
const sortingDirection = this.preferences.get('shared.sorting.direction') || 'desc';
const sortingKey =
this.preferences.get('shared.sorting.key') || 'modifiedAt';
const sortingDirection =
this.preferences.get('shared.sorting.direction') || 'desc';
const nodes = await this.contentApi.findSharedLinks({
const nodes = await this.contentApi
.findSharedLinks({
fields: ['nodeId', this.getRootField(sortingKey)]
}).toPromise();
})
.toPromise();
const entries = nodes.list.entries.map(obj => obj.entry);
this.sort(entries, sortingKey, sortingDirection);
@@ -268,10 +298,13 @@ export class PreviewComponent extends PageComponent implements OnInit {
if (source === 'recent-files') {
const person = await this.contentApi.getPerson('-me-').toPromise();
const username = person.entry.id;
const sortingKey = this.preferences.get('recent-files.sorting.key') || 'modifiedAt';
const sortingDirection = this.preferences.get('recent-files.sorting.direction') || 'desc';
const sortingKey =
this.preferences.get('recent-files.sorting.key') || 'modifiedAt';
const sortingDirection =
this.preferences.get('recent-files.sorting.direction') || 'desc';
const nodes = await this.contentApi.search({
const nodes = await this.contentApi
.search({
query: {
query: '*',
language: 'afts'
@@ -279,15 +312,20 @@ export class PreviewComponent extends PageComponent implements OnInit {
filterQueries: [
{ query: `cm:modified:[NOW/DAY-30DAYS TO NOW/DAY+1DAY]` },
{ query: `cm:modifier:${username} OR cm:creator:${username}` },
{ query: `TYPE:"content" AND -TYPE:"app:filelink" AND -TYPE:"fm:post"` }
{
query: `TYPE:"content" AND -TYPE:"app:filelink" AND -TYPE:"fm:post"`
}
],
fields: ['id', this.getRootField(sortingKey)],
sort: [{
sort: [
{
type: 'FIELD',
field: 'cm:modified',
ascending: false
}]
}).toPromise();
}
]
})
.toPromise();
const entries = nodes.list.entries.map(obj => obj.entry);
this.sort(entries, sortingKey, sortingDirection);
@@ -308,14 +346,16 @@ export class PreviewComponent extends PageComponent implements OnInit {
items.sort((a: any, b: any) => {
let left = ObjectUtils.getValue(a, key);
if (left) {
left = (left instanceof Date) ? left.valueOf().toString() : left.toString();
left =
left instanceof Date ? left.valueOf().toString() : left.toString();
} else {
left = '';
}
let right = ObjectUtils.getValue(b, key);
if (right) {
right = (right instanceof Date) ? right.valueOf().toString() : right.toString();
right =
right instanceof Date ? right.valueOf().toString() : right.toString();
} else {
right = '';
}
@@ -344,7 +384,8 @@ export class PreviewComponent extends PageComponent implements OnInit {
private getNavigationCommands(url: string): any[] {
const urlTree: UrlTree = this.router.parseUrl(url);
const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
const urlSegmentGroup: UrlSegmentGroup =
urlTree.root.children[PRIMARY_OUTLET];
if (!urlSegmentGroup) {
return [url];

View File

@@ -54,15 +54,8 @@ const routes: Routes = [
CoreExtensionsModule.forChild(),
AppToolbarModule
],
declarations: [
PreviewComponent,
PreviewExtensionComponent
],
providers: [
ViewUtilService
],
exports: [
PreviewComponent
]
declarations: [PreviewComponent, PreviewExtensionComponent],
providers: [ViewUtilService],
exports: [PreviewComponent]
})
export class PreviewModule {}

View File

@@ -29,16 +29,36 @@ export class ViewUtilService {
* Mime-type grouping based on the ViewerComponent.
*/
private mimeTypes = {
text: ['text/plain', 'text/csv', 'text/xml', 'text/html', 'application/x-javascript'],
text: [
'text/plain',
'text/csv',
'text/xml',
'text/html',
'application/x-javascript'
],
pdf: ['application/pdf'],
image: ['image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'image/svg+xml'],
media: ['video/mp4', 'video/webm', 'video/ogg', 'audio/mpeg', 'audio/ogg', 'audio/wav']
image: [
'image/png',
'image/jpeg',
'image/gif',
'image/bmp',
'image/svg+xml'
],
media: [
'video/mp4',
'video/webm',
'video/ogg',
'audio/mpeg',
'audio/ogg',
'audio/wav'
]
};
constructor(private apiService: AlfrescoApiService,
constructor(
private apiService: AlfrescoApiService,
private contentApi: ContentApiService,
private logService: LogService) {
}
private logService: LogService
) {}
/**
* This method takes a url to trigger the print dialog against, and the type of artifact that it
@@ -86,10 +106,16 @@ export class ViewUtilService {
this.getRendition(nodeId, ViewUtilService.ContentGroup.PDF)
.then(value => {
const url: string = this.getRenditionUrl(nodeId, type, (value ? true : false));
const printType = (type === ViewUtilService.ContentGroup.PDF
|| type === ViewUtilService.ContentGroup.TEXT)
? ViewUtilService.ContentGroup.PDF : type;
const url: string = this.getRenditionUrl(
nodeId,
type,
value ? true : false
);
const printType =
type === ViewUtilService.ContentGroup.PDF ||
type === ViewUtilService.ContentGroup.TEXT
? ViewUtilService.ContentGroup.PDF
: type;
this.printFile(url, printType);
})
.catch(err => {
@@ -98,10 +124,17 @@ export class ViewUtilService {
});
}
public getRenditionUrl(nodeId: string, type: string, renditionExists: boolean): string {
return (renditionExists && type !== ViewUtilService.ContentGroup.IMAGE) ?
this.apiService.contentApi.getRenditionUrl(nodeId, ViewUtilService.ContentGroup.PDF) :
this.contentApi.getContentUrl(nodeId, false);
public getRenditionUrl(
nodeId: string,
type: string,
renditionExists: boolean
): string {
return renditionExists && type !== ViewUtilService.ContentGroup.IMAGE
? this.apiService.contentApi.getRenditionUrl(
nodeId,
ViewUtilService.ContentGroup.PDF
)
: this.contentApi.getContentUrl(nodeId, false);
}
/**
@@ -111,8 +144,15 @@ export class ViewUtilService {
* @param {number} retries
* @returns {Promise<AlfrescoApi.RenditionEntry>}
*/
private async waitRendition(nodeId: string, renditionId: string, retries: number): Promise<RenditionEntry> {
const rendition = await this.apiService.renditionsApi.getRendition(nodeId, renditionId);
private async waitRendition(
nodeId: string,
renditionId: string,
retries: number
): Promise<RenditionEntry> {
const rendition = await this.apiService.renditionsApi.getRendition(
nodeId,
renditionId
);
if (this.maxRetries < retries) {
const status = rendition.entry.status.toString();
@@ -127,7 +167,6 @@ export class ViewUtilService {
}
}
/**
* From ViewerComponent
* @param {string} mimeType
@@ -161,16 +200,23 @@ export class ViewUtilService {
* @param {string} nodeId
* @returns {string}
*/
public async getRendition(nodeId: string, renditionId: string): Promise<RenditionEntry> {
public async getRendition(
nodeId: string,
renditionId: string
): Promise<RenditionEntry> {
const supported = await this.apiService.renditionsApi.getRenditions(nodeId);
let rendition = supported.list.entries.find(obj => obj.entry.id.toLowerCase() === renditionId);
let rendition = supported.list.entries.find(
obj => obj.entry.id.toLowerCase() === renditionId
);
if (rendition) {
const status = rendition.entry.status.toString();
if (status === 'NOT_CREATED') {
try {
await this.apiService.renditionsApi.createRendition(nodeId, {id: renditionId});
await this.apiService.renditionsApi.createRendition(nodeId, {
id: renditionId
});
rendition = await this.waitRendition(nodeId, renditionId, 0);
} catch (err) {
this.logService.error(err);
@@ -179,5 +225,4 @@ export class ViewUtilService {
}
return new Promise(resolve => resolve(rendition));
}
}

View File

@@ -27,7 +27,11 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
AlfrescoApiService,
TimeAgoPipe, NodeNameTooltipPipe, NodeFavoriteDirective, DataTableComponent, AppConfigPipe
TimeAgoPipe,
NodeNameTooltipPipe,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe
} from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { ContentManagementService } from '../../services/content-management.service';
@@ -54,9 +58,7 @@ describe('RecentFilesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppTestingModule
],
imports: [AppTestingModule],
declarations: [
DataTableComponent,
TimeAgoPipe,
@@ -77,11 +79,15 @@ describe('RecentFilesComponent', () => {
alfrescoApi = TestBed.get(AlfrescoApiService);
alfrescoApi.reset();
spyOn(alfrescoApi.peopleApi, 'getPerson').and.returnValue(Promise.resolve({
spyOn(alfrescoApi.peopleApi, 'getPerson').and.returnValue(
Promise.resolve({
entry: { id: 'personId' }
}));
})
);
spyOn(alfrescoApi.searchApi, 'search').and.returnValue(Promise.resolve(page));
spyOn(alfrescoApi.searchApi, 'search').and.returnValue(
Promise.resolve(page)
);
});
describe('OnInit()', () => {

View File

@@ -56,10 +56,7 @@ export class RecentFilesComponent extends PageComponent implements OnInit {
this.content.nodesRestored.subscribe(() => this.reload()),
this.breakpointObserver
.observe([
Breakpoints.HandsetPortrait,
Breakpoints.HandsetLandscape
])
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})

View File

@@ -24,14 +24,36 @@
*/
import { ThumbnailService } from '@alfresco/adf-core';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component, EventEmitter, Input, OnDestroy, OnInit, Output,
QueryList, ViewEncapsulation, ViewChild, ViewChildren, ElementRef, TemplateRef, ContentChild } from '@angular/core';
import {
animate,
state,
style,
transition,
trigger
} from '@angular/animations';
import {
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
QueryList,
ViewEncapsulation,
ViewChild,
ViewChildren,
ElementRef,
TemplateRef,
ContentChild
} from '@angular/core';
import { MinimalNodeEntity, QueryBody } from 'alfresco-js-api';
import { Subject } from 'rxjs';
import { MatListItem } from '@angular/material';
import { debounceTime, filter } from 'rxjs/operators';
import { EmptySearchResultComponent, SearchComponent } from '@alfresco/adf-content-services';
import {
EmptySearchResultComponent,
SearchComponent
} from '@alfresco/adf-content-services';
@Component({
selector: 'app-search-input-control',
@@ -39,20 +61,29 @@ import { EmptySearchResultComponent, SearchComponent } from '@alfresco/adf-conte
styleUrls: ['./search-input-control.component.scss'],
animations: [
trigger('transitionMessages', [
state('active', style({ transform: 'translateX(0%)', 'margin-left': '13px' })),
state(
'active',
style({ transform: 'translateX(0%)', 'margin-left': '13px' })
),
state('inactive', style({ transform: 'translateX(81%)' })),
state('no-animation', style({ transform: 'translateX(0%)', width: '100%' })),
transition('inactive => active',
animate('300ms cubic-bezier(0.55, 0, 0.55, 0.2)')),
transition('active => inactive',
animate('300ms cubic-bezier(0.55, 0, 0.55, 0.2)'))
state(
'no-animation',
style({ transform: 'translateX(0%)', width: '100%' })
),
transition(
'inactive => active',
animate('300ms cubic-bezier(0.55, 0, 0.55, 0.2)')
),
transition(
'active => inactive',
animate('300ms cubic-bezier(0.55, 0, 0.55, 0.2)')
)
])
],
encapsulation: ViewEncapsulation.None,
host: { class: 'adf-search-control' }
})
export class SearchInputControlComponent implements OnInit, OnDestroy {
/** Toggles whether to use an expanding search control. If false
* then a regular input is used.
*/
@@ -123,15 +154,20 @@ export class SearchInputControlComponent implements OnInit, OnDestroy {
private focusSubject = new Subject<FocusEvent>();
constructor(private thumbnailService: ThumbnailService) {
this.toggleSearch.asObservable().pipe(debounceTime(this.toggleDebounceTime)).subscribe(() => {
this.toggleSearch
.asObservable()
.pipe(debounceTime(this.toggleDebounceTime))
.subscribe(() => {
if (this.expandable && !this.skipToggle) {
this.subscriptAnimationState = this.subscriptAnimationState === 'inactive' ? 'active' : 'inactive';
this.subscriptAnimationState =
this.subscriptAnimationState === 'inactive' ? 'active' : 'inactive';
if (this.subscriptAnimationState === 'inactive') {
this.searchTerm = '';
this.searchAutocomplete.resetResults();
if ( document.activeElement.id === this.searchInput.nativeElement.id) {
if (
document.activeElement.id === this.searchInput.nativeElement.id
) {
this.searchInput.nativeElement.blur();
}
}
@@ -147,7 +183,9 @@ export class SearchInputControlComponent implements OnInit, OnDestroy {
}
ngOnInit() {
this.subscriptAnimationState = this.expandable ? 'inactive' : 'no-animation';
this.subscriptAnimationState = this.expandable
? 'inactive'
: 'no-animation';
this.setupFocusEventHandlers();
}
@@ -226,7 +264,9 @@ export class SearchInputControlComponent implements OnInit, OnDestroy {
selectFirstResult() {
if (this.listResultElement && this.listResultElement.length > 0) {
const firstElement: MatListItem = <MatListItem> this.listResultElement.first;
const firstElement: MatListItem = <MatListItem>(
this.listResultElement.first
);
firstElement._getHostElement().focus();
}
}
@@ -239,7 +279,9 @@ export class SearchInputControlComponent implements OnInit, OnDestroy {
}
onRowArrowUp($event: KeyboardEvent): void {
const previousElement: any = this.getPreviousElementSibling(<Element> $event.target);
const previousElement: any = this.getPreviousElementSibling(<Element>(
$event.target
));
if (previousElement) {
previousElement.focus();
} else {
@@ -249,12 +291,17 @@ export class SearchInputControlComponent implements OnInit, OnDestroy {
}
private setupFocusEventHandlers() {
this.focusSubject.pipe(
this.focusSubject
.pipe(
debounceTime(50),
filter(($event: any) => {
return this.isSearchBarActive() && ($event.type === 'blur' || $event.type === 'focusout');
return (
this.isSearchBarActive() &&
($event.type === 'blur' || $event.type === 'focusout')
);
})
).subscribe(() => {
)
.subscribe(() => {
this.toggleSearchBar();
});
}
@@ -272,5 +319,4 @@ export class SearchInputControlComponent implements OnInit, OnDestroy {
private getPreviousElementSibling(node: Element): Element {
return node.previousElementSibling;
}
}

View File

@@ -24,12 +24,23 @@
*/
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed, async, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import {
TestBed,
async,
ComponentFixture,
fakeAsync,
tick
} from '@angular/core/testing';
import { SearchInputComponent } from './search-input.component';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { Actions, ofType } from '@ngrx/effects';
import { NAVIGATE_FOLDER, NavigateToFolder, VIEW_FILE, ViewFileAction } from '../../../store/actions';
import {
NAVIGATE_FOLDER,
NavigateToFolder,
VIEW_FILE,
ViewFileAction
} from '../../../store/actions';
import { map } from 'rxjs/operators';
describe('SearchInputComponent', () => {
@@ -39,12 +50,8 @@ describe('SearchInputComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
AppTestingModule
],
declarations: [
SearchInputComponent
],
imports: [AppTestingModule],
declarations: [SearchInputComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents()
@@ -66,7 +73,9 @@ describe('SearchInputComponent', () => {
})
);
const node = { entry: { isFile: true, id: 'node-id', parentId: 'parent-id' } };
const node = {
entry: { isFile: true, id: 'node-id', parentId: 'parent-id' }
};
component.onItemClicked(node);
tick();

View File

@@ -25,14 +25,23 @@
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import {
NavigationEnd, PRIMARY_OUTLET, Router, RouterEvent, UrlSegment, UrlSegmentGroup,
NavigationEnd,
PRIMARY_OUTLET,
Router,
RouterEvent,
UrlSegment,
UrlSegmentGroup,
UrlTree
} from '@angular/router';
import { MinimalNodeEntity } from 'alfresco-js-api';
import { SearchInputControlComponent } from '../search-input-control/search-input-control.component';
import { Store } from '@ngrx/store';
import { AppStore } from '../../../store/states/app.state';
import { SearchByTermAction, NavigateToFolder, ViewFileAction } from '../../../store/actions';
import {
SearchByTermAction,
NavigateToFolder,
ViewFileAction
} from '../../../store/actions';
import { filter } from 'rxjs/operators';
@Component({
@@ -42,7 +51,6 @@ import { filter } from 'rxjs/operators';
host: { class: 'aca-search-input' }
})
export class SearchInputComponent implements OnInit {
hasOneChange = false;
hasNewChange = false;
navigationTimer: any;
@@ -51,8 +59,7 @@ export class SearchInputComponent implements OnInit {
@ViewChild('searchInputControl')
searchInputControl: SearchInputControlComponent;
constructor(private router: Router, private store: Store<AppStore>) {
}
constructor(private router: Router, private store: Store<AppStore>) {}
ngOnInit() {
this.showInputValue();
@@ -68,10 +75,10 @@ export class SearchInputComponent implements OnInit {
showInputValue() {
if (this.onSearchResults) {
let searchedWord = null;
const urlTree: UrlTree = this.router.parseUrl(this.router.url);
const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
const urlSegmentGroup: UrlSegmentGroup =
urlTree.root.children[PRIMARY_OUTLET];
if (urlSegmentGroup) {
const urlSegments: UrlSegment[] = urlSegmentGroup.segments;
@@ -83,7 +90,6 @@ export class SearchInputComponent implements OnInit {
this.searchInputControl.searchTerm = searchedWord;
this.searchInputControl.subscriptAnimationState = 'no-animation';
}
} else {
if (this.searchInputControl.subscriptAnimationState === 'no-animation') {
this.searchInputControl.subscriptAnimationState = 'active';
@@ -124,7 +130,6 @@ export class SearchInputComponent implements OnInit {
onSearchChange(searchTerm: string) {
if (this.onSearchResults) {
if (this.hasOneChange) {
this.hasNewChange = true;
} else {

View File

@@ -19,6 +19,6 @@
}
.link:hover {
color: #2196F3;
color: #2196f3;
text-decoration: underline;
}

View File

@@ -23,7 +23,13 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { Component, Input, OnInit, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/core';
import {
Component,
Input,
OnInit,
ViewEncapsulation,
ChangeDetectionStrategy
} from '@angular/core';
import { MinimalNodeEntity } from 'alfresco-js-api';
import { ViewFileAction } from '../../../store/actions';
import { Store } from '@ngrx/store';
@@ -41,7 +47,8 @@ import { NavigateToFolder } from '../../../store/actions';
export class SearchResultsRowComponent implements OnInit {
private node: MinimalNodeEntity;
@Input() context: any;
@Input()
context: any;
constructor(private store: Store<AppStore>) {}
@@ -94,9 +101,7 @@ export class SearchResultsRowComponent implements OnInit {
}
showPreview() {
this.store.dispatch(
new ViewFileAction(this.node)
);
this.store.dispatch(new ViewFileAction(this.node));
}
navigate() {

View File

@@ -9,8 +9,7 @@ describe('SearchComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SearchResultsComponent]
})
.compileComponents();
}).compileComponents();
}));
beforeEach(() => {

View File

@@ -26,7 +26,11 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { NodePaging, Pagination, MinimalNodeEntity } from 'alfresco-js-api';
import { ActivatedRoute, Params } from '@angular/router';
import { SearchQueryBuilderService, SearchComponent as AdfSearchComponent, SearchFilterComponent } from '@alfresco/adf-content-services';
import {
SearchQueryBuilderService,
SearchComponent as AdfSearchComponent,
SearchFilterComponent
} from '@alfresco/adf-content-services';
import { PageComponent } from '../../page.component';
import { Store } from '@ngrx/store';
import { AppStore } from '../../../store/states/app.state';
@@ -41,7 +45,6 @@ import { ContentManagementService } from '../../../services/content-management.s
providers: [SearchQueryBuilderService]
})
export class SearchResultsComponent extends PageComponent implements OnInit {
@ViewChild('search')
search: AdfSearchComponent;
@@ -90,7 +93,9 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
if (this.route) {
this.route.params.forEach((params: Params) => {
this.searchedWord = params.hasOwnProperty(this.queryParamName) ? params[this.queryParamName] : null;
this.searchedWord = params.hasOwnProperty(this.queryParamName)
? params[this.queryParamName]
: null;
const query = this.formatSearchQuery(this.searchedWord);
if (query) {
@@ -98,7 +103,9 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
this.queryBuilder.update();
} else {
this.queryBuilder.userQuery = null;
this.queryBuilder.executed.next( {list: { pagination: { totalItems: 0 }, entries: []}} );
this.queryBuilder.executed.next({
list: { pagination: { totalItems: 0 }, entries: [] }
});
}
});
}
@@ -129,14 +136,17 @@ export class SearchResultsComponent extends PageComponent implements OnInit {
}
isFiltered(): boolean {
return this.searchFilter.selectedFacetQueries.length > 0
|| this.searchFilter.selectedBuckets.length > 0
|| this.hasCheckedCategories();
return (
this.searchFilter.selectedFacetQueries.length > 0 ||
this.searchFilter.selectedBuckets.length > 0 ||
this.hasCheckedCategories()
);
}
hasCheckedCategories() {
const checkedCategory = this.queryBuilder.categories
.find(category => !!this.queryBuilder.queryFragments[category.id]);
const checkedCategory = this.queryBuilder.categories.find(
category => !!this.queryBuilder.queryFragments[category.id]
);
return !!checkedCategory;
}

View File

@@ -24,12 +24,21 @@
*/
import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { AppConfigService, StorageService, SettingsService } from '@alfresco/adf-core';
import {
AppConfigService,
StorageService,
SettingsService
} from '@alfresco/adf-core';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { AppStore } from '../../store/states';
import { appLanguagePicker, selectHeaderColor, selectAppName, selectUser } from '../../store/selectors/app.selectors';
import {
appLanguagePicker,
selectHeaderColor,
selectAppName,
selectUser
} from '../../store/selectors/app.selectors';
import { MatCheckboxChange } from '@angular/material';
import { SetLanguagePickerAction } from '../../store/actions';
import { ProfileState } from '@alfresco/adf-extensions';
@@ -41,7 +50,6 @@ import { ProfileState } from '@alfresco/adf-extensions';
host: { class: 'aca-settings' }
})
export class SettingsComponent implements OnInit {
private defaultPath = '/assets/images/alfresco-logo-white.svg';
form: FormGroup;
@@ -50,14 +58,15 @@ export class SettingsComponent implements OnInit {
appName$: Observable<string>;
headerColor$: Observable<string>;
languagePicker$: Observable<boolean>;
experimental: Array<{ key: string, value: boolean }> = [];
experimental: Array<{ key: string; value: boolean }> = [];
constructor(
private store: Store<AppStore>,
private appConfig: AppConfigService,
private settingsService: SettingsService,
private storage: StorageService,
private fb: FormBuilder) {
private fb: FormBuilder
) {
this.profile$ = store.select(selectUser);
this.appName$ = store.select(selectAppName);
this.languagePicker$ = store.select(appLanguagePicker);
@@ -70,7 +79,10 @@ export class SettingsComponent implements OnInit {
ngOnInit() {
this.form = this.fb.group({
ecmHost: ['', [Validators.required, Validators.pattern('^(http|https):\/\/.*[^/]$')]]
ecmHost: [
'',
[Validators.required, Validators.pattern('^(http|https)://.*[^/]$')]
]
});
this.reset();
@@ -80,7 +92,7 @@ export class SettingsComponent implements OnInit {
const value = this.appConfig.get(`experimental.${key}`);
return {
key,
value: (value === true || value === 'true')
value: value === true || value === 'true'
};
});
}

View File

@@ -37,11 +37,7 @@ const routes: Routes = [
];
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
RouterModule.forChild(routes)
],
imports: [CommonModule, CoreModule.forChild(), RouterModule.forChild(routes)],
declarations: [SettingsComponent]
})
export class AppSettingsModule {}

View File

@@ -27,7 +27,11 @@ import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
AlfrescoApiService,
TimeAgoPipe, NodeNameTooltipPipe, NodeFavoriteDirective, DataTableComponent, AppConfigPipe
TimeAgoPipe,
NodeNameTooltipPipe,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe
} from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { ContentManagementService } from '../../services/content-management.service';
@@ -52,8 +56,7 @@ describe('SharedFilesComponent', () => {
});
beforeEach(() => {
TestBed
.configureTestingModule({
TestBed.configureTestingModule({
imports: [AppTestingModule],
declarations: [
DataTableComponent,
@@ -75,7 +78,9 @@ describe('SharedFilesComponent', () => {
alfrescoApi = TestBed.get(AlfrescoApiService);
alfrescoApi.reset();
spyOn(alfrescoApi.sharedLinksApi, 'findSharedLinks').and.returnValue(Promise.resolve(page));
spyOn(alfrescoApi.sharedLinksApi, 'findSharedLinks').and.returnValue(
Promise.resolve(page)
);
});
describe('OnInit', () => {

View File

@@ -56,10 +56,7 @@ export class SharedFilesComponent extends PageComponent implements OnInit {
this.content.linksUnshared.subscribe(() => this.reload()),
this.breakpointObserver
.observe([
Breakpoints.HandsetPortrait,
Breakpoints.HandsetLandscape
])
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})

View File

@@ -7,10 +7,9 @@ import { ActivatedRoute } from '@angular/router';
styleUrls: ['shared-link-view.component.scss'],
encapsulation: ViewEncapsulation.None,
// tslint:disable-next-line:use-host-property-decorator
host: { 'class': 'app-shared-link-view' }
host: { class: 'app-shared-link-view' }
})
export class SharedLinkViewComponent implements OnInit {
sharedLinkId: string = null;
constructor(private route: ActivatedRoute) {}
@@ -20,5 +19,4 @@ export class SharedLinkViewComponent implements OnInit {
this.sharedLinkId = params.id;
});
}
}

View File

@@ -37,14 +37,8 @@ describe('SidenavComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
AppTestingModule,
EffectsModule.forRoot([NodeEffects])
],
declarations: [
SidenavComponent,
ExperimentalDirective
],
imports: [AppTestingModule, EffectsModule.forRoot([NodeEffects])],
declarations: [SidenavComponent, ExperimentalDirective],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents()

View File

@@ -4,7 +4,7 @@
$foreground: map-get($theme, foreground);
$background: map-get($theme, background);
$border: 1px solid mat-color($foreground, divider, .07);
$border: 1px solid mat-color($foreground, divider, 0.07);
.sidenav {
@include angular-material-theme($theme);
@@ -28,8 +28,7 @@
}
.menu__item--default {
color: mat-color($primary, .87);
}
color: mat-color($primary, 0.87);
}
}
}

View File

@@ -38,7 +38,8 @@ import { ContentActionRef, NavBarGroupRef } from '@alfresco/adf-extensions';
styleUrls: ['./sidenav.component.scss']
})
export class SidenavComponent implements OnInit, OnDestroy {
@Input() showLabel: boolean;
@Input()
showLabel: boolean;
groups: Array<NavBarGroupRef> = [];
createActions: Array<ContentActionRef> = [];

View File

@@ -43,7 +43,6 @@ import { ToggleDocumentDisplayMode } from '../../../store/actions';
`
})
export class DocumentDisplayModeComponent {
displayMode$: Observable<string>;
constructor(private store: Store<AppStore>) {

View File

@@ -46,12 +46,12 @@ import { ContentManagementService } from '../../../services/content-management.s
`
})
export class ToggleFavoriteComponent {
selection$: Observable<SelectionState>;
constructor(
private store: Store<AppStore>,
private content: ContentManagementService) {
private content: ContentManagementService
) {
this.selection$ = this.store.select(appSelection);
}

View File

@@ -42,8 +42,10 @@ import { AppExtensionService } from '../../../extensions/extension.service';
host: { class: 'aca-toolbar-action' }
})
export class ToolbarActionComponent {
@Input() type = 'icon-button';
@Input() entry: ContentActionRef;
@Input()
type = 'icon-button';
@Input()
entry: ContentActionRef;
constructor(
protected store: Store<AppStore>,

View File

@@ -41,8 +41,10 @@ export enum ToolbarButtonType {
templateUrl: 'toolbar-button.component.html'
})
export class ToolbarButtonComponent {
@Input() type: ToolbarButtonType = ToolbarButtonType.ICON_BUTTON;
@Input() actionRef: ContentActionRef;
@Input()
type: ToolbarButtonType = ToolbarButtonType.ICON_BUTTON;
@Input()
actionRef: ContentActionRef;
constructor(
protected store: Store<AppStore>,

View File

@@ -44,11 +44,7 @@ export function components() {
}
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
ExtensionsModule.forChild()
],
imports: [CommonModule, CoreModule.forChild(), ExtensionsModule.forChild()],
declarations: components(),
exports: components(),
entryComponents: components()

View File

@@ -26,8 +26,11 @@ import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import {
AlfrescoApiService,
TimeAgoPipe, NodeNameTooltipPipe,
NodeFavoriteDirective, DataTableComponent, AppConfigPipe
TimeAgoPipe,
NodeNameTooltipPipe,
NodeFavoriteDirective,
DataTableComponent,
AppConfigPipe
} from '@alfresco/adf-core';
import { DocumentListComponent } from '@alfresco/adf-content-services';
import { ContentManagementService } from '../../services/content-management.service';
@@ -81,7 +84,9 @@ describe('TrashcanComponent', () => {
});
beforeEach(() => {
spyOn(alfrescoApi.nodesApi, 'getDeletedNodes').and.returnValue(Promise.resolve(page));
spyOn(alfrescoApi.nodesApi, 'getDeletedNodes').and.returnValue(
Promise.resolve(page)
);
});
describe('onRestoreNode()', () => {

View File

@@ -41,10 +41,12 @@ export class TrashcanComponent extends PageComponent implements OnInit {
isSmallScreen = false;
user$: Observable<ProfileState>;
constructor(content: ContentManagementService,
constructor(
content: ContentManagementService,
extensions: AppExtensionService,
store: Store<AppStore>,
private breakpointObserver: BreakpointObserver) {
private breakpointObserver: BreakpointObserver
) {
super(store, extensions, content);
this.user$ = this.store.select(selectUser);
}
@@ -58,10 +60,7 @@ export class TrashcanComponent extends PageComponent implements OnInit {
this.content.nodesRestored.subscribe(() => this.reload()),
this.breakpointObserver
.observe([
Breakpoints.HandsetPortrait,
Breakpoints.HandsetLandscape
])
.observe([Breakpoints.HandsetPortrait, Breakpoints.HandsetLandscape])
.subscribe(result => {
this.isSmallScreen = result.matches;
})

View File

@@ -45,7 +45,9 @@ export function forbidSpecialCharacters({ value }: FormControl) {
const validCharacters: RegExp = /[^A-Za-z0-9-]/;
const isValid: boolean = !validCharacters.test(value);
return (isValid) ? null : {
return isValid
? null
: {
message: 'LIBRARY.ERRORS.ILLEGAL_CHARACTERS'
};
}

View File

@@ -1,4 +1,3 @@
.mat-radio-group {
display: flex;
flex-direction: column;

View File

@@ -24,7 +24,6 @@ import { ContentApiService } from '../../services/content-api.service';
import { SiteIdValidator, forbidSpecialCharacters } from './form.validators';
import { debounceTime } from 'rxjs/operators';
@Component({
selector: 'app-library-dialog',
styleUrls: ['./library.dialog.scss'],
@@ -43,7 +42,11 @@ export class LibraryDialogComponent implements OnInit {
visibilityOptions = [
{ value: 'PUBLIC', label: 'LIBRARY.VISIBILITY.PUBLIC', disabled: false },
{ value: 'PRIVATE', label: 'LIBRARY.VISIBILITY.PRIVATE', disabled: false },
{ value: 'MODERATED', label: 'LIBRARY.VISIBILITY.MODERATED', disabled: false }
{
value: 'MODERATED',
label: 'LIBRARY.VISIBILITY.MODERATED',
disabled: false
}
];
constructor(
@@ -54,7 +57,11 @@ export class LibraryDialogComponent implements OnInit {
ngOnInit() {
const validators = {
id: [ Validators.required, Validators.maxLength(72), forbidSpecialCharacters ],
id: [
Validators.required,
Validators.maxLength(72),
forbidSpecialCharacters
],
title: [Validators.required, Validators.maxLength(256)],
description: [Validators.maxLength(512)]
};
@@ -62,7 +69,7 @@ export class LibraryDialogComponent implements OnInit {
this.form = this.formBuilder.group({
title: ['', validators.title],
id: ['', validators.id, SiteIdValidator.createValidator(this.contentApi)],
description: [ '', validators.description ],
description: ['', validators.description]
});
this.visibilityOption = this.visibilityOptions[0].value;
@@ -106,15 +113,16 @@ export class LibraryDialogComponent implements OnInit {
submit() {
const { form, dialog } = this;
if (!form.valid) { return; }
if (!form.valid) {
return;
}
this.create().subscribe(
(node: SiteEntry) => {
this.success.emit(node);
dialog.close(node);
},
(error) => this.handleError(error)
error => this.handleError(error)
);
}
@@ -135,16 +143,18 @@ export class LibraryDialogComponent implements OnInit {
}
private sanitize(input: string) {
return input
.replace(/[\s]/g, '-')
.replace(/[^A-Za-z0-9-]/g, '');
return input.replace(/[\s]/g, '-').replace(/[^A-Za-z0-9-]/g, '');
}
private handleError(error: any): any {
const { error: { statusCode } } = JSON.parse(error.message);
const {
error: { statusCode }
} = JSON.parse(error.message);
if (statusCode === 409) {
this.form.controls['id'].setErrors({ message: 'LIBRARY.ERRORS.CONFLICT' });
this.form.controls['id'].setErrors({
message: 'LIBRARY.ERRORS.CONFLICT'
});
}
return error;

View File

@@ -34,9 +34,7 @@ import { MAT_DIALOG_DATA } from '@angular/material';
export class NodePermissionsDialogComponent {
nodeId: string;
constructor(
@Inject(MAT_DIALOG_DATA) data: any,
) {
constructor(@Inject(MAT_DIALOG_DATA) data: any) {
this.nodeId = data.nodeId;
}
}

View File

@@ -21,7 +21,6 @@
flex: 0 0 auto;
}
.mat-dialog-title {
font-size: 20px;
font-weight: 600;
@@ -33,7 +32,6 @@
color: mat-color($foreground, text, 0.87);
}
.mat-dialog-actions {
padding: 8px 8px 24px 8px;
display: -webkit-box;

View File

@@ -34,10 +34,6 @@ import { PaginationDirective } from './pagination.directive';
DocumentListDirective,
PaginationDirective
],
exports: [
ExperimentalDirective,
DocumentListDirective,
PaginationDirective
]
exports: [ExperimentalDirective, DocumentListDirective, PaginationDirective]
})
export class DirectivesModule {}

View File

@@ -124,16 +124,13 @@ export class DocumentListDirective implements OnInit, OnDestroy {
return entry;
});
this.store.dispatch(
new SetSelectedNodesAction(selection)
);
this.store.dispatch(new SetSelectedNodesAction(selection));
}
private isLockedNode(node): boolean {
return (
node.isLocked ||
(node.properties &&
node.properties['cm:lockType'] === 'READ_ONLY_LOCK')
(node.properties && node.properties['cm:lockType'] === 'READ_ONLY_LOCK')
);
}

View File

@@ -23,7 +23,13 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { Directive, TemplateRef, ViewContainerRef, Input, EmbeddedViewRef } from '@angular/core';
import {
Directive,
TemplateRef,
ViewContainerRef,
Input,
EmbeddedViewRef
} from '@angular/core';
import { AppConfigService, StorageService } from '@alfresco/adf-core';
import { environment } from '../../environments/environment';
@@ -43,7 +49,8 @@ export class ExperimentalDirective {
private config: AppConfigService
) {}
@Input() set ifExperimental(featureKey: string) {
@Input()
set ifExperimental(featureKey: string) {
const key = `experimental.${featureKey}`;
const override = this.storage.getItem(key);
@@ -66,7 +73,8 @@ export class ExperimentalDirective {
this.updateView();
}
@Input() set ifExperimentalElse(templateRef: TemplateRef<any>) {
@Input()
set ifExperimentalElse(templateRef: TemplateRef<any>) {
this.elseTemplateRef = templateRef;
this.elseViewRef = null;
this.updateView();
@@ -88,7 +96,9 @@ export class ExperimentalDirective {
this.viewContainerRef.clear();
if (this.elseTemplateRef) {
this.elseViewRef = this.viewContainerRef.createEmbeddedView(this.elseTemplateRef);
this.elseViewRef = this.viewContainerRef.createEmbeddedView(
this.elseTemplateRef
);
}
}
}

View File

@@ -50,11 +50,9 @@ export class PaginationDirective implements OnInit, OnDestroy {
);
this.subscriptions.push(
this.pagination.changePageSize.subscribe(
(event: PaginationModel) => {
this.pagination.changePageSize.subscribe((event: PaginationModel) => {
this.preferences.paginationSize = event.maxItems;
}
)
})
);
}

View File

@@ -43,11 +43,7 @@ export function setupExtensions(service: AppExtensionService): Function {
}
@NgModule({
imports: [
CommonModule,
CoreModule.forChild(),
ExtensionsModule.forChild()
]
imports: [CommonModule, CoreModule.forChild(), ExtensionsModule.forChild()]
})
export class CoreExtensionsModule {
static forRoot(): ModuleWithProviders {

View File

@@ -96,18 +96,14 @@ export function canDeleteSelection(
}
if (isPreview(context, ...args)) {
return context.permissions.check(context.selection.nodes, [
'delete'
]);
return context.permissions.check(context.selection.nodes, ['delete']);
}
// workaround for Shared Files
if (isSharedFiles(context, ...args)) {
return context.permissions.check(
context.selection.nodes,
['delete'],
{ target: 'allowableOperationsOnTarget' }
);
return context.permissions.check(context.selection.nodes, ['delete'], {
target: 'allowableOperationsOnTarget'
});
}
return context.permissions.check(context.selection.nodes, ['delete']);
@@ -164,9 +160,7 @@ export function canDownloadSelection(
return context.selection.nodes.every(node => {
return (
node.entry &&
(node.entry.isFile ||
node.entry.isFolder ||
!!node.entry.nodeId)
(node.entry.isFile || node.entry.isFolder || !!node.entry.nodeId)
);
});
}

View File

@@ -28,8 +28,16 @@ import { AppTestingModule } from '../testing/app-testing.module';
import { AppExtensionService } from './extension.service';
import { Store } from '@ngrx/store';
import { AppStore } from '../store/states';
import { ContentActionType, mergeArrays,
sortByOrder, filterEnabled, reduceSeparators, reduceEmptyMenus, ExtensionService, ExtensionConfig } from '@alfresco/adf-extensions';
import {
ContentActionType,
mergeArrays,
sortByOrder,
filterEnabled,
reduceSeparators,
reduceEmptyMenus,
ExtensionService,
ExtensionConfig
} from '@alfresco/adf-extensions';
describe('AppExtensionService', () => {
let service: AppExtensionService;
@@ -38,9 +46,7 @@ describe('AppExtensionService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppTestingModule
]
imports: [AppTestingModule]
});
store = TestBed.get(Store);
@@ -96,7 +102,7 @@ describe('AppExtensionService', () => {
},
{
name: 'extra-1'
},
}
]);
});
});
@@ -121,9 +127,7 @@ describe('AppExtensionService', () => {
});
it('should find action by id', () => {
const action = extensions.getActionById(
'aca:actions/create-folder'
);
const action = extensions.getActionById('aca:actions/create-folder');
expect(action).toBeTruthy();
expect(action.type).toBe('CREATE_FOLDER');
expect(action.payload).toBe('folder-name');
@@ -305,7 +309,7 @@ describe('AppExtensionService', () => {
id: 'aca:toolbar/separator-1',
order: 1,
type: ContentActionType.separator,
title: 'action1',
title: 'action1'
},
{
id: 'aca:toolbar/separator-2',
@@ -343,12 +347,8 @@ describe('AppExtensionService', () => {
});
expect(service.toolbarActions.length).toBe(2);
expect(service.toolbarActions[0].id).toBe(
'aca:toolbar/separator-1'
);
expect(service.toolbarActions[1].id).toBe(
'aca:toolbar/separator-2'
);
expect(service.toolbarActions[0].id).toBe('aca:toolbar/separator-1');
expect(service.toolbarActions[1].id).toBe('aca:toolbar/separator-2');
});
});
@@ -519,11 +519,9 @@ describe('AppExtensionService', () => {
});
it('should use implicit order', () => {
const sorted = [
{ id: '3'},
{ id: '2' },
{ id: '1', order: 1 }
].sort(sortByOrder);
const sorted = [{ id: '3' }, { id: '2' }, { id: '1', order: 1 }].sort(
sortByOrder
);
expect(sorted[0].id).toBe('1');
expect(sorted[1].id).toBe('3');

View File

@@ -31,12 +31,20 @@ import { ruleContext } from '../store/selectors/app.selectors';
import { NodePermissionService } from '../services/node-permission.service';
import { ProfileResolver } from '../services/profile.resolver';
import {
SelectionState, NavigationState, ExtensionConfig,
RuleContext, RuleEvaluator, ViewerExtensionRef,
ContentActionRef, ContentActionType,
SelectionState,
NavigationState,
ExtensionConfig,
RuleContext,
RuleEvaluator,
ViewerExtensionRef,
ContentActionRef,
ContentActionType,
ExtensionLoaderService,
SidebarTabRef, NavBarGroupRef,
sortByOrder, reduceSeparators, reduceEmptyMenus,
SidebarTabRef,
NavBarGroupRef,
sortByOrder,
reduceSeparators,
reduceEmptyMenus,
ExtensionService,
ProfileState
} from '@alfresco/adf-extensions';
@@ -65,8 +73,8 @@ export class AppExtensionService implements RuleContext {
private store: Store<AppStore>,
private loader: ExtensionLoaderService,
private extensions: ExtensionService,
public permissions: NodePermissionService) {
public permissions: NodePermissionService
) {
this.store.select(ruleContext).subscribe(result => {
this.selection = result.selection;
this.navigation = result.navigation;
@@ -85,18 +93,42 @@ export class AppExtensionService implements RuleContext {
return;
}
this.toolbarActions = this.loader.getContentActions(config, 'features.toolbar');
this.viewerToolbarActions = this.loader.getContentActions(config, 'features.viewer.toolbar');
this.viewerContentExtensions = this.loader.getElements<ViewerExtensionRef>(config, 'features.viewer.content');
this.contextMenuActions = this.loader.getContentActions(config, 'features.contextMenu');
this.openWithActions = this.loader.getContentActions(config, 'features.viewer.openWith');
this.createActions = this.loader.getElements<ContentActionRef>(config, 'features.create');
this.toolbarActions = this.loader.getContentActions(
config,
'features.toolbar'
);
this.viewerToolbarActions = this.loader.getContentActions(
config,
'features.viewer.toolbar'
);
this.viewerContentExtensions = this.loader.getElements<ViewerExtensionRef>(
config,
'features.viewer.content'
);
this.contextMenuActions = this.loader.getContentActions(
config,
'features.contextMenu'
);
this.openWithActions = this.loader.getContentActions(
config,
'features.viewer.openWith'
);
this.createActions = this.loader.getElements<ContentActionRef>(
config,
'features.create'
);
this.navbar = this.loadNavBar(config);
this.sidebar = this.loader.getElements<SidebarTabRef>(config, 'features.sidebar');
this.sidebar = this.loader.getElements<SidebarTabRef>(
config,
'features.sidebar'
);
}
protected loadNavBar(config: ExtensionConfig): Array<NavBarGroupRef> {
const elements = this.loader.getElements<NavBarGroupRef>(config, 'features.navbar');
const elements = this.loader.getElements<NavBarGroupRef>(
config,
'features.navbar'
);
return elements.map(group => {
return {
@@ -131,9 +163,7 @@ export class AppExtensionService implements RuleContext {
getApplicationRoutes(): Array<Route> {
return this.extensions.routes.map(route => {
const guards = this.extensions.getAuthGuards(
route.auth && route.auth.length > 0
? route.auth
: this.defaults.auth
route.auth && route.auth.length > 0 ? route.auth : this.defaults.auth
);
return {
@@ -179,9 +209,7 @@ export class AppExtensionService implements RuleContext {
const copy = this.copyAction(action);
if (copy.children && copy.children.length > 0) {
copy.children = copy.children
.filter(childAction =>
this.filterByRules(childAction)
)
.filter(childAction => this.filterByRules(childAction))
.reduce(reduceSeparators, []);
}
return copy;
@@ -193,21 +221,19 @@ export class AppExtensionService implements RuleContext {
}
getViewerToolbarActions(): Array<ContentActionRef> {
return this.viewerToolbarActions
.filter(action => this.filterByRules(action));
return this.viewerToolbarActions.filter(action =>
this.filterByRules(action)
);
}
getAllowedContextMenuActions(): Array<ContentActionRef> {
return this.contextMenuActions
.filter(action => this.filterByRules(action));
return this.contextMenuActions.filter(action => this.filterByRules(action));
}
copyAction(action: ContentActionRef): ContentActionRef {
return {
...action,
children: (action.children || []).map(child =>
this.copyAction(child)
)
children: (action.children || []).map(child => this.copyAction(child))
};
}

View File

@@ -71,12 +71,7 @@ export class ContentApiService {
*/
getNode(nodeId: string, options: any = {}): Observable<MinimalNodeEntity> {
const defaults = {
include: [
'path',
'properties',
'allowableOperations',
'permissions'
]
include: ['path', 'properties', 'allowableOperations', 'permissions']
};
const queryOptions = Object.assign(defaults, options);
@@ -172,9 +167,7 @@ export class ContentApiService {
*/
getRepositoryInformation(): Observable<DiscoveryEntry> {
return from(
this.api
.getInstance()
.discovery.discoveryApi.getRepositoryInformation()
this.api.getInstance().discovery.discoveryApi.getRepositoryInformation()
);
}
@@ -202,10 +195,7 @@ export class ContentApiService {
return this.api.contentApi.getContentUrl(nodeId, attachment);
}
deleteSite(
siteId?: string,
opts?: { permanent?: boolean }
): Observable<any> {
deleteSite(siteId?: string, opts?: { permanent?: boolean }): Observable<any> {
return from(this.api.sitesApi.deleteSite(siteId, opts));
}

View File

@@ -23,15 +23,24 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { TestBed, fakeAsync } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { MatDialog, MatSnackBar } from '@angular/material';
import { Actions, ofType, EffectsModule } from '@ngrx/effects';
import {
SNACKBAR_INFO, SnackbarWarningAction, SnackbarInfoAction,
SnackbarErrorAction, SNACKBAR_ERROR, SNACKBAR_WARNING, PurgeDeletedNodesAction,
RestoreDeletedNodesAction, NavigateRouteAction, NAVIGATE_ROUTE, DeleteNodesAction, MoveNodesAction, CopyNodesAction
SNACKBAR_INFO,
SnackbarWarningAction,
SnackbarInfoAction,
SnackbarErrorAction,
SNACKBAR_ERROR,
SNACKBAR_WARNING,
PurgeDeletedNodesAction,
RestoreDeletedNodesAction,
NavigateRouteAction,
NAVIGATE_ROUTE,
DeleteNodesAction,
MoveNodesAction,
CopyNodesAction
} from '../store/actions';
import { map } from 'rxjs/operators';
import { NodeEffects } from '../store/effects/node.effects';
@@ -44,7 +53,6 @@ import { NodeActionsService } from './node-actions.service';
import { TranslationService } from '@alfresco/adf-core';
describe('ContentManagementService', () => {
let dialog: MatDialog;
let actions$: Actions;
let contentApi: ContentApiService;
@@ -56,10 +64,7 @@ describe('ContentManagementService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppTestingModule,
EffectsModule.forRoot([NodeEffects])
]
imports: [AppTestingModule, EffectsModule.forRoot([NodeEffects])]
});
contentApi = TestBed.get(ContentApiService);
@@ -84,7 +89,9 @@ describe('ContentManagementService', () => {
});
it('notifies successful copy of a node', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.COPY'));
spyOn(nodeActions, 'copyNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.COPY')
);
const selection = [{ entry: { id: 'node-to-copy-id', name: 'name' } }];
const createdItems = [{ entry: { id: 'copy-id', name: 'name' } }];
@@ -93,88 +100,114 @@ describe('ContentManagementService', () => {
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.SINGULAR'
);
});
it('notifies successful copy of multiple nodes', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.COPY'));
spyOn(nodeActions, 'copyNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.COPY')
);
const selection = [
{ entry: { id: 'node-to-copy-1', name: 'name1' } },
{ entry: { id: 'node-to-copy-2', name: 'name2' } }];
{ entry: { id: 'node-to-copy-2', name: 'name2' } }
];
const createdItems = [
{ entry: { id: 'copy-of-node-1', name: 'name1' } },
{ entry: { id: 'copy-of-node-2', name: 'name2' } }];
{ entry: { id: 'copy-of-node-2', name: 'name2' } }
];
store.dispatch(new CopyNodesAction(selection));
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.PLURAL');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.PLURAL'
);
});
it('notifies partially copy of one node out of a multiple selection of nodes', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.COPY'));
spyOn(nodeActions, 'copyNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.COPY')
);
const selection = [
{ entry: { id: 'node-to-copy-1', name: 'name1' } },
{ entry: { id: 'node-to-copy-2', name: 'name2' } }];
const createdItems = [
{ entry: { id: 'copy-of-node-1', name: 'name1' } }];
{ entry: { id: 'node-to-copy-2', name: 'name2' } }
];
const createdItems = [{ entry: { id: 'copy-of-node-1', name: 'name1' } }];
store.dispatch(new CopyNodesAction(selection));
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.PARTIAL_SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.PARTIAL_SINGULAR'
);
});
it('notifies partially copy of more nodes out of a multiple selection of nodes', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.COPY'));
spyOn(nodeActions, 'copyNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.COPY')
);
const selection = [
{ entry: { id: 'node-to-copy-0', name: 'name0' } },
{ entry: { id: 'node-to-copy-1', name: 'name1' } },
{ entry: { id: 'node-to-copy-2', name: 'name2' } }];
{ entry: { id: 'node-to-copy-2', name: 'name2' } }
];
const createdItems = [
{ entry: { id: 'copy-of-node-0', name: 'name0' } },
{ entry: { id: 'copy-of-node-1', name: 'name1' } }];
{ entry: { id: 'copy-of-node-1', name: 'name1' } }
];
store.dispatch(new CopyNodesAction(selection));
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.PARTIAL_PLURAL');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.PARTIAL_PLURAL'
);
});
it('notifies of failed copy of multiple nodes', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.COPY'));
spyOn(nodeActions, 'copyNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.COPY')
);
const selection = [
{ entry: { id: 'node-to-copy-0', name: 'name0' } },
{ entry: { id: 'node-to-copy-1', name: 'name1' } },
{ entry: { id: 'node-to-copy-2', name: 'name2' } }];
{ entry: { id: 'node-to-copy-2', name: 'name2' } }
];
const createdItems = [];
store.dispatch(new CopyNodesAction(selection));
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.FAIL_PLURAL');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.FAIL_PLURAL'
);
});
it('notifies of failed copy of one node', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.COPY'));
spyOn(nodeActions, 'copyNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.COPY')
);
const selection = [
{ entry: { id: 'node-to-copy', name: 'name' } }];
const selection = [{ entry: { id: 'node-to-copy', name: 'name' } }];
const createdItems = [];
store.dispatch(new CopyNodesAction(selection));
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.FAIL_SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.FAIL_SINGULAR'
);
});
it('notifies error if success message was not emitted', () => {
@@ -186,34 +219,46 @@ describe('ContentManagementService', () => {
nodeActions.contentCopied.next();
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.GENERIC');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.GENERIC'
);
});
it('notifies permission error on copy of node', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(throwError(new Error(JSON.stringify({error: {statusCode: 403}}))));
spyOn(nodeActions, 'copyNodes').and.returnValue(
throwError(new Error(JSON.stringify({ error: { statusCode: 403 } })))
);
const selection = [{ entry: { id: '1', name: 'name' } }];
store.dispatch(new CopyNodesAction(selection));
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.PERMISSION');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.PERMISSION'
);
});
it('notifies generic error message on all errors, but 403', () => {
spyOn(nodeActions, 'copyNodes').and.returnValue(throwError(new Error(JSON.stringify({error: {statusCode: 404}}))));
spyOn(nodeActions, 'copyNodes').and.returnValue(
throwError(new Error(JSON.stringify({ error: { statusCode: 404 } })))
);
const selection = [{ entry: { id: '1', name: 'name' } }];
store.dispatch(new CopyNodesAction(selection));
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.GENERIC');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.GENERIC'
);
});
});
describe('Undo Copy action', () => {
beforeEach(() => {
spyOn(nodeActions, 'copyNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.COPY'));
spyOn(nodeActions, 'copyNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.COPY')
);
spyOn(snackBar, 'open').and.returnValue({
onAction: () => of({})
@@ -230,32 +275,58 @@ describe('ContentManagementService', () => {
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.SINGULAR'
);
expect(contentApi.deleteNode).toHaveBeenCalledWith(createdItems[0].entry.id, { permanent: true });
expect(contentApi.deleteNode).toHaveBeenCalledWith(
createdItems[0].entry.id,
{ permanent: true }
);
});
it('should delete also the node created inside an already existing folder from destination', () => {
const spyOnDeleteNode = spyOn(contentApi, 'deleteNode').and.returnValue(of(null));
const spyOnDeleteNode = spyOn(contentApi, 'deleteNode').and.returnValue(
of(null)
);
const selection = [
{ entry: { id: 'node-to-copy-1', name: 'name1' } },
{ entry: { id: 'node-to-copy-2', name: 'folder-with-name-already-existing-on-destination' } }];
{
entry: {
id: 'node-to-copy-2',
name: 'folder-with-name-already-existing-on-destination'
}
}
];
const id1 = 'copy-of-node-1';
const id2 = 'copy-of-child-of-node-2';
const createdItems = [
{ entry: { id: id1, name: 'name1' } },
[ { entry: { id: id2, name: 'name-of-child-of-node-2' , parentId: 'the-folder-already-on-destination' } }] ];
[
{
entry: {
id: id2,
name: 'name-of-child-of-node-2',
parentId: 'the-folder-already-on-destination'
}
}
]
];
store.dispatch(new CopyNodesAction(selection));
nodeActions.contentCopied.next(<any>createdItems);
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_COPY.PLURAL');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_COPY.PLURAL'
);
expect(spyOnDeleteNode).toHaveBeenCalled();
expect(spyOnDeleteNode.calls.allArgs())
.toEqual([[id1, { permanent: true }], [id2, { permanent: true }]]);
expect(spyOnDeleteNode.calls.allArgs()).toEqual([
[id1, { permanent: true }],
[id2, { permanent: true }]
]);
});
it('notifies when error occurs on Undo action', () => {
@@ -269,11 +340,15 @@ describe('ContentManagementService', () => {
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(contentApi.deleteNode).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toEqual('APP.MESSAGES.INFO.NODE_COPY.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toEqual(
'APP.MESSAGES.INFO.NODE_COPY.SINGULAR'
);
});
it('notifies when some error of type Error occurs on Undo action', () => {
spyOn(contentApi, 'deleteNode').and.returnValue(throwError(new Error('oops!')));
spyOn(contentApi, 'deleteNode').and.returnValue(
throwError(new Error('oops!'))
);
const selection = [{ entry: { id: 'node-to-copy-id', name: 'name' } }];
const createdItems = [{ entry: { id: 'copy-id', name: 'name' } }];
@@ -283,11 +358,15 @@ describe('ContentManagementService', () => {
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(contentApi.deleteNode).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toEqual('APP.MESSAGES.INFO.NODE_COPY.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toEqual(
'APP.MESSAGES.INFO.NODE_COPY.SINGULAR'
);
});
it('notifies permission error when it occurs on Undo action', () => {
spyOn(contentApi, 'deleteNode').and.returnValue(throwError(new Error(JSON.stringify({error: {statusCode: 403}}))));
spyOn(contentApi, 'deleteNode').and.returnValue(
throwError(new Error(JSON.stringify({ error: { statusCode: 403 } })))
);
const selection = [{ entry: { id: 'node-to-copy-id', name: 'name' } }];
const createdItems = [{ entry: { id: 'copy-id', name: 'name' } }];
@@ -297,16 +376,18 @@ describe('ContentManagementService', () => {
expect(nodeActions.copyNodes).toHaveBeenCalled();
expect(contentApi.deleteNode).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toEqual('APP.MESSAGES.INFO.NODE_COPY.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toEqual(
'APP.MESSAGES.INFO.NODE_COPY.SINGULAR'
);
});
});
describe('Move node action', () => {
beforeEach(() => {
spyOn(translationService, 'instant').and.callFake((keysArray) => {
spyOn(translationService, 'instant').and.callFake(keysArray => {
if (Array.isArray(keysArray)) {
const processedKeys = {};
keysArray.forEach((key) => {
keysArray.forEach(key => {
processedKeys[key] = key;
});
return processedKeys;
@@ -328,7 +409,9 @@ describe('ContentManagementService', () => {
partiallySucceeded: []
};
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(nodeActions, 'processResponse').and.returnValue(moveResponse);
const selection = node;
@@ -337,20 +420,25 @@ describe('ContentManagementService', () => {
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_MOVE.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.SINGULAR'
);
});
it('notifies successful move of multiple nodes', () => {
const nodes = [
{ entry: { id: '1', name: 'name1' } },
{ entry: { id: '2', name: 'name2' } }];
{ entry: { id: '2', name: 'name2' } }
];
const moveResponse = {
succeeded: nodes,
failed: [],
partiallySucceeded: []
};
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(nodeActions, 'processResponse').and.returnValue(moveResponse);
const selection = nodes;
@@ -359,7 +447,9 @@ describe('ContentManagementService', () => {
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_MOVE.PLURAL');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.PLURAL'
);
});
it('notifies partial move of a node', () => {
@@ -370,7 +460,9 @@ describe('ContentManagementService', () => {
partiallySucceeded: nodes
};
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(nodeActions, 'processResponse').and.returnValue(moveResponse);
const selection = nodes;
@@ -379,20 +471,25 @@ describe('ContentManagementService', () => {
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.SINGULAR'
);
});
it('notifies partial move of multiple nodes', () => {
const nodes = [
{ entry: { id: '1', name: 'name' } },
{ entry: { id: '2', name: 'name2' } } ];
{ entry: { id: '2', name: 'name2' } }
];
const moveResponse = {
succeeded: [],
failed: [],
partiallySucceeded: nodes
};
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(nodeActions, 'processResponse').and.returnValue(moveResponse);
const selection = nodes;
@@ -401,19 +498,25 @@ describe('ContentManagementService', () => {
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.PLURAL');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.PLURAL'
);
});
it('notifies successful move and the number of nodes that could not be moved', () => {
const nodes = [ { entry: { id: '1', name: 'name' } },
{ entry: { id: '2', name: 'name2' } } ];
const nodes = [
{ entry: { id: '1', name: 'name' } },
{ entry: { id: '2', name: 'name2' } }
];
const moveResponse = {
succeeded: [nodes[0]],
failed: [nodes[1]],
partiallySucceeded: []
};
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(nodeActions, 'processResponse').and.returnValue(moveResponse);
store.dispatch(new MoveNodesAction(nodes));
@@ -421,28 +524,34 @@ describe('ContentManagementService', () => {
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0])
.toBe('APP.MESSAGES.INFO.NODE_MOVE.SINGULAR APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.FAIL');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.SINGULAR APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.FAIL'
);
});
it('notifies successful move and the number of partially moved ones', () => {
const nodes = [ { entry: { id: '1', name: 'name' } },
{ entry: { id: '2', name: 'name2' } } ];
const nodes = [
{ entry: { id: '1', name: 'name' } },
{ entry: { id: '2', name: 'name2' } }
];
const moveResponse = {
succeeded: [nodes[0]],
failed: [],
partiallySucceeded: [nodes[1]]
};
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(nodeActions, 'processResponse').and.returnValue(moveResponse);
store.dispatch(new MoveNodesAction(nodes));
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0])
.toBe('APP.MESSAGES.INFO.NODE_MOVE.SINGULAR APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.SINGULAR APP.MESSAGES.INFO.NODE_MOVE.PARTIAL.SINGULAR'
);
});
it('notifies error if success message was not emitted', () => {
@@ -459,37 +568,51 @@ describe('ContentManagementService', () => {
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.GENERIC');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.GENERIC'
);
});
it('notifies permission error on move of node', () => {
spyOn(nodeActions, 'moveNodes').and.returnValue(throwError(new Error(JSON.stringify({error: {statusCode: 403}}))));
spyOn(nodeActions, 'moveNodes').and.returnValue(
throwError(new Error(JSON.stringify({ error: { statusCode: 403 } })))
);
const selection = [{ entry: { id: '1', name: 'name' } }];
store.dispatch(new MoveNodesAction(selection));
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.PERMISSION');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.PERMISSION'
);
});
it('notifies generic error message on all errors, but 403', () => {
spyOn(nodeActions, 'moveNodes').and.returnValue(throwError(new Error(JSON.stringify({error: {statusCode: 404}}))));
spyOn(nodeActions, 'moveNodes').and.returnValue(
throwError(new Error(JSON.stringify({ error: { statusCode: 404 } })))
);
const selection = [{ entry: { id: '1', name: 'name' } }];
store.dispatch(new MoveNodesAction(selection));
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.GENERIC');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.GENERIC'
);
});
it('notifies conflict error message on 409', () => {
spyOn(nodeActions, 'moveNodes').and.returnValue(throwError(new Error(JSON.stringify({error: {statusCode: 409}}))));
spyOn(nodeActions, 'moveNodes').and.returnValue(
throwError(new Error(JSON.stringify({ error: { statusCode: 409 } })))
);
const selection = [{ entry: { id: '1', name: 'name' } }];
store.dispatch(new MoveNodesAction(selection));
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.NODE_MOVE');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.NODE_MOVE'
);
});
it('notifies error if move response has only failed items', () => {
@@ -500,23 +623,27 @@ describe('ContentManagementService', () => {
partiallySucceeded: []
};
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(nodeActions, 'processResponse').and.returnValue(moveResponse);
store.dispatch(new MoveNodesAction(nodes));
nodeActions.contentMoved.next(moveResponse);
expect(nodeActions.moveNodes).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.ERRORS.GENERIC');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.ERRORS.GENERIC'
);
});
});
describe('Undo Move action', () => {
beforeEach(() => {
spyOn(translationService, 'instant').and.callFake((keysArray) => {
spyOn(translationService, 'instant').and.callFake(keysArray => {
if (Array.isArray(keysArray)) {
const processedKeys = {};
keysArray.forEach((key) => {
keysArray.forEach(key => {
processedKeys[key] = key;
});
return processedKeys;
@@ -527,7 +654,9 @@ describe('ContentManagementService', () => {
});
beforeEach(() => {
spyOn(nodeActions, 'moveNodes').and.returnValue(of('OPERATION.SUCCES.CONTENT.MOVE'));
spyOn(nodeActions, 'moveNodes').and.returnValue(
of('OPERATION.SUCCES.CONTENT.MOVE')
);
spyOn(snackBar, 'open').and.returnValue({
onAction: () => of({})
@@ -538,7 +667,9 @@ describe('ContentManagementService', () => {
it('should move node back to initial parent, after succeeded move', () => {
const initialParent = 'parent-id-0';
const node = { entry: { id: 'node-to-move-id', name: 'name', parentId: initialParent } };
const node = {
entry: { id: 'node-to-move-id', name: 'name', parentId: initialParent }
};
const selection = [node];
spyOn(nodeActions, 'moveNodeAction').and.returnValue(of({}));
@@ -551,14 +682,25 @@ describe('ContentManagementService', () => {
};
nodeActions.contentMoved.next(<any>movedItems);
expect(nodeActions.moveNodeAction)
.toHaveBeenCalledWith(movedItems.succeeded[0].itemMoved.entry, movedItems.succeeded[0].initialParentId);
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_MOVE.SINGULAR');
expect(nodeActions.moveNodeAction).toHaveBeenCalledWith(
movedItems.succeeded[0].itemMoved.entry,
movedItems.succeeded[0].initialParentId
);
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.SINGULAR'
);
});
it('should move node back to initial parent, after succeeded move of a single file', () => {
const initialParent = 'parent-id-0';
const node = { entry: { id: 'node-to-move-id', name: 'name', isFolder: false, parentId: initialParent } };
const node = {
entry: {
id: 'node-to-move-id',
name: 'name',
isFolder: false,
parentId: initialParent
}
};
const selection = [node];
spyOn(nodeActions, 'moveNodeAction').and.returnValue(of({}));
@@ -572,8 +714,13 @@ describe('ContentManagementService', () => {
store.dispatch(new MoveNodesAction(selection));
nodeActions.contentMoved.next(<any>movedItems);
expect(nodeActions.moveNodeAction).toHaveBeenCalledWith(node.entry, initialParent);
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_MOVE.SINGULAR');
expect(nodeActions.moveNodeAction).toHaveBeenCalledWith(
node.entry,
initialParent
);
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.SINGULAR'
);
});
it('should restore deleted folder back to initial parent, after succeeded moving all its files', () => {
@@ -581,7 +728,14 @@ describe('ContentManagementService', () => {
spyOn(contentApi, 'restoreNode').and.returnValue(of(null));
const initialParent = 'parent-id-0';
const node = { entry: { id: 'folder-to-move-id', name: 'conflicting-name', parentId: initialParent, isFolder: true } };
const node = {
entry: {
id: 'folder-to-move-id',
name: 'conflicting-name',
parentId: initialParent,
isFolder: true
}
};
const selection = [node];
const itemMoved = {}; // folder was empty
@@ -597,7 +751,9 @@ describe('ContentManagementService', () => {
nodeActions.contentMoved.next(<any>movedItems);
expect(contentApi.restoreNode).toHaveBeenCalled();
expect(snackBar.open['calls'].argsFor(0)[0]).toBe('APP.MESSAGES.INFO.NODE_MOVE.SINGULAR');
expect(snackBar.open['calls'].argsFor(0)[0]).toBe(
'APP.MESSAGES.INFO.NODE_MOVE.SINGULAR'
);
});
it('should notify when error occurs on Undo Move action', fakeAsync(done => {
@@ -609,11 +765,23 @@ describe('ContentManagementService', () => {
);
const initialParent = 'parent-id-0';
const node = { entry: { id: 'node-to-move-id', name: 'conflicting-name', parentId: initialParent } };
const node = {
entry: {
id: 'node-to-move-id',
name: 'conflicting-name',
parentId: initialParent
}
};
const selection = [node];
const afterMoveParentId = 'parent-id-1';
const childMoved = { entry: { id: 'child-of-node-to-move-id', name: 'child-name', parentId: afterMoveParentId } };
const childMoved = {
entry: {
id: 'child-of-node-to-move-id',
name: 'child-name',
parentId: afterMoveParentId
}
};
nodeActions.moveDeletedEntries = [node]; // folder got deleted
const movedItems = {
@@ -629,7 +797,9 @@ describe('ContentManagementService', () => {
}));
it('should notify when some error of type Error occurs on Undo Move action', fakeAsync(done => {
spyOn(contentApi, 'restoreNode').and.returnValue(throwError(new Error('oops!')));
spyOn(contentApi, 'restoreNode').and.returnValue(
throwError(new Error('oops!'))
);
actions$.pipe(
ofType<SnackbarErrorAction>(SNACKBAR_ERROR),
@@ -637,10 +807,14 @@ describe('ContentManagementService', () => {
);
const initialParent = 'parent-id-0';
const node = { entry: { id: 'node-to-move-id', name: 'name', parentId: initialParent } };
const node = {
entry: { id: 'node-to-move-id', name: 'name', parentId: initialParent }
};
const selection = [node];
const childMoved = { entry: { id: 'child-of-node-to-move-id', name: 'child-name' } };
const childMoved = {
entry: { id: 'child-of-node-to-move-id', name: 'child-name' }
};
nodeActions.moveDeletedEntries = [node]; // folder got deleted
const movedItems = {
@@ -656,7 +830,9 @@ describe('ContentManagementService', () => {
}));
it('should notify permission error when it occurs on Undo Move action', fakeAsync(done => {
spyOn(contentApi, 'restoreNode').and.returnValue(throwError(new Error(JSON.stringify({error: {statusCode: 403}}))));
spyOn(contentApi, 'restoreNode').and.returnValue(
throwError(new Error(JSON.stringify({ error: { statusCode: 403 } })))
);
actions$.pipe(
ofType<SnackbarErrorAction>(SNACKBAR_ERROR),
@@ -664,10 +840,14 @@ describe('ContentManagementService', () => {
);
const initialParent = 'parent-id-0';
const node = { entry: { id: 'node-to-move-id', name: 'name', parentId: initialParent } };
const node = {
entry: { id: 'node-to-move-id', name: 'name', parentId: initialParent }
};
const selection = [node];
const childMoved = { entry: { id: 'child-of-node-to-move-id', name: 'child-name' } };
const childMoved = {
entry: { id: 'child-of-node-to-move-id', name: 'child-name' }
};
nodeActions.moveDeletedEntries = [node]; // folder got deleted
const movedItems = {
@@ -752,7 +932,7 @@ describe('ContentManagementService', () => {
}));
it('should raise warning message when only one file is successful', fakeAsync(done => {
spyOn(contentApi, 'deleteNode').and.callFake((id) => {
spyOn(contentApi, 'deleteNode').and.callFake(id => {
if (id === '1') {
return throwError(null);
} else {
@@ -776,7 +956,7 @@ describe('ContentManagementService', () => {
}));
it('should raise warning message when some files are successfully deleted', fakeAsync(done => {
spyOn(contentApi, 'deleteNode').and.callFake((id) => {
spyOn(contentApi, 'deleteNode').and.callFake(id => {
if (id === '1') {
return throwError(null);
}
@@ -807,7 +987,6 @@ describe('ContentManagementService', () => {
}));
});
describe('Permanent Delete', () => {
it('does not purge nodes if no selection', () => {
spyOn(contentApi, 'purgeDeletedNode');
@@ -834,7 +1013,7 @@ describe('ContentManagementService', () => {
})
);
spyOn(contentApi, 'purgeDeletedNode').and.callFake((id) => {
spyOn(contentApi, 'purgeDeletedNode').and.callFake(id => {
if (id === '1') {
return of({});
}
@@ -865,7 +1044,7 @@ describe('ContentManagementService', () => {
})
);
spyOn(contentApi, 'purgeDeletedNode').and.callFake((id) => {
spyOn(contentApi, 'purgeDeletedNode').and.callFake(id => {
if (id === '1') {
return of({});
}
@@ -903,9 +1082,7 @@ describe('ContentManagementService', () => {
spyOn(contentApi, 'purgeDeletedNode').and.returnValue(of({}));
const selection = [
{ entry: { id: '1', name: 'name1' } }
];
const selection = [{ entry: { id: '1', name: 'name1' } }];
store.dispatch(new PurgeDeletedNodesAction(selection));
}));
@@ -920,9 +1097,7 @@ describe('ContentManagementService', () => {
spyOn(contentApi, 'purgeDeletedNode').and.returnValue(throwError({}));
const selection = [
{ entry: { id: '1', name: 'name1' } }
];
const selection = [{ entry: { id: '1', name: 'name1' } }];
store.dispatch(new PurgeDeletedNodesAction(selection));
}));
@@ -934,7 +1109,7 @@ describe('ContentManagementService', () => {
done();
})
);
spyOn(contentApi, 'purgeDeletedNode').and.callFake((id) => {
spyOn(contentApi, 'purgeDeletedNode').and.callFake(id => {
if (id === '1') {
return of({});
}
@@ -959,7 +1134,7 @@ describe('ContentManagementService', () => {
done();
})
);
spyOn(contentApi, 'purgeDeletedNode').and.callFake((id) => {
spyOn(contentApi, 'purgeDeletedNode').and.callFake(id => {
if (id === '1') {
return throwError({});
}
@@ -1001,9 +1176,11 @@ describe('ContentManagementService', () => {
it('call restore nodes if selection has nodes with path', fakeAsync(() => {
spyOn(contentApi, 'restoreNode').and.returnValue(of({}));
spyOn(contentApi, 'getDeletedNodes').and.returnValue(of({
spyOn(contentApi, 'getDeletedNodes').and.returnValue(
of({
list: { entries: [] }
}));
})
);
const path = {
elements: [
@@ -1031,9 +1208,11 @@ describe('ContentManagementService', () => {
describe('refresh()', () => {
it('dispatch event on finish', fakeAsync(done => {
spyOn(contentApi, 'restoreNode').and.returnValue(of({}));
spyOn(contentApi, 'getDeletedNodes').and.returnValue(of({
spyOn(contentApi, 'getDeletedNodes').and.returnValue(
of({
list: { entries: [] }
}));
})
);
const path = {
elements: [
@@ -1061,9 +1240,11 @@ describe('ContentManagementService', () => {
describe('notification', () => {
beforeEach(() => {
spyOn(contentApi, 'getDeletedNodes').and.returnValue(of({
spyOn(contentApi, 'getDeletedNodes').and.returnValue(
of({
list: { entries: [] }
}));
})
);
});
it('should raise error message on partial multiple fail ', fakeAsync(done => {
@@ -1074,7 +1255,7 @@ describe('ContentManagementService', () => {
map(action => done())
);
spyOn(contentApi, 'restoreNode').and.callFake((id) => {
spyOn(contentApi, 'restoreNode').and.callFake(id => {
if (id === '1') {
return of({});
}
@@ -1124,9 +1305,7 @@ describe('ContentManagementService', () => {
]
};
const selection = [
{ entry: { id: '1', name: 'name1', path } }
];
const selection = [{ entry: { id: '1', name: 'name1', path } }];
store.dispatch(new RestoreDeletedNodesAction(selection));
}));
@@ -1150,9 +1329,7 @@ describe('ContentManagementService', () => {
]
};
const selection = [
{ entry: { id: '1', name: 'name1', path } }
];
const selection = [{ entry: { id: '1', name: 'name1', path } }];
store.dispatch(new RestoreDeletedNodesAction(selection));
}));
@@ -1176,15 +1353,13 @@ describe('ContentManagementService', () => {
]
};
const selection = [
{ entry: { id: '1', name: 'name1', path } }
];
const selection = [{ entry: { id: '1', name: 'name1', path } }];
store.dispatch(new RestoreDeletedNodesAction(selection));
}));
it('should raise info message when restore multiple nodes', fakeAsync(done => {
spyOn(contentApi, 'restoreNode').and.callFake((id) => {
spyOn(contentApi, 'restoreNode').and.callFake(id => {
if (id === '1') {
return of({});
}
@@ -1233,9 +1408,7 @@ describe('ContentManagementService', () => {
]
};
const selection = [
{ entry: { id: '1', name: 'name1', path } }
];
const selection = [{ entry: { id: '1', name: 'name1', path } }];
store.dispatch(new RestoreDeletedNodesAction(selection));
}));
@@ -1271,5 +1444,4 @@ describe('ContentManagementService', () => {
}));
});
});
});

View File

@@ -26,10 +26,22 @@
import { Subject, Observable, forkJoin, of, zip } from 'rxjs';
import { Injectable } from '@angular/core';
import { MatDialog, MatSnackBar } from '@angular/material';
import { FolderDialogComponent, ConfirmDialogComponent, ShareDialogComponent } from '@alfresco/adf-content-services';
import {
FolderDialogComponent,
ConfirmDialogComponent,
ShareDialogComponent
} from '@alfresco/adf-content-services';
import { LibraryDialogComponent } from '../dialogs/library/library.dialog';
import { SnackbarErrorAction, SnackbarInfoAction, SnackbarAction, SnackbarWarningAction,
NavigateRouteAction, SnackbarUserAction, UndoDeleteNodesAction, SetSelectedNodesAction } from '../store/actions';
import {
SnackbarErrorAction,
SnackbarInfoAction,
SnackbarAction,
SnackbarWarningAction,
NavigateRouteAction,
SnackbarUserAction,
UndoDeleteNodesAction,
SetSelectedNodesAction
} from '../store/actions';
import { Store } from '@ngrx/store';
import { AppStore } from '../store/states';
import {
@@ -133,12 +145,9 @@ export class ContentManagementService {
const id = node.entry.nodeId || (<any>node).entry.guid;
if (id) {
this.contentApi
.getNodeInfo(id)
.subscribe(entry => {
this.contentApi.getNodeInfo(id).subscribe(entry => {
this.openVersionManagerDialog(entry);
});
} else {
this.openVersionManagerDialog(node.entry);
}
@@ -162,7 +171,6 @@ export class ContentManagementService {
shareNode(node: MinimalNodeEntity): void {
if (node && node.entry && node.entry.isFile) {
this.store
.select(sharedUrl)
.pipe(take(1))
@@ -244,23 +252,21 @@ export class ContentManagementService {
() => {
this.libraryDeleted.next(id);
this.store.dispatch(
new SnackbarInfoAction(
'APP.MESSAGES.INFO.LIBRARY_DELETED'
)
new SnackbarInfoAction('APP.MESSAGES.INFO.LIBRARY_DELETED')
);
},
() => {
this.store.dispatch(
new SnackbarErrorAction(
'APP.MESSAGES.ERRORS.DELETE_LIBRARY_FAILED'
)
new SnackbarErrorAction('APP.MESSAGES.ERRORS.DELETE_LIBRARY_FAILED')
);
}
);
}
async unshareNodes(links: Array<MinimalNodeEntity>) {
const promises = links.map(link => this.contentApi.deleteSharedLink(link.entry.id).toPromise());
const promises = links.map(link =>
this.contentApi.deleteSharedLink(link.entry.id).toPromise()
);
await Promise.all(promises);
this.linksUnshared.next();
}
@@ -330,10 +336,7 @@ export class ContentManagementService {
)
.subscribe((nodes: DeletedNodesPaging) => {
const selectedNodes = this.diff(status.fail, selection, false);
const remainingNodes = this.diff(
selectedNodes,
nodes.list.entries
);
const remainingNodes = this.diff(selectedNodes, nodes.list.entries);
if (!remainingNodes.length) {
this.showRestoreNotification(status);
@@ -376,16 +379,13 @@ export class ContentManagementService {
if (failedItems) {
if (numberOfCopiedItems) {
i18MessageSuffix =
numberOfCopiedItems === 1
? 'PARTIAL_SINGULAR'
: 'PARTIAL_PLURAL';
numberOfCopiedItems === 1 ? 'PARTIAL_SINGULAR' : 'PARTIAL_PLURAL';
} else {
i18MessageSuffix =
failedItems === 1 ? 'FAIL_SINGULAR' : 'FAIL_PLURAL';
}
} else {
i18MessageSuffix =
numberOfCopiedItems === 1 ? 'SINGULAR' : 'PLURAL';
i18MessageSuffix = numberOfCopiedItems === 1 ? 'SINGULAR' : 'PLURAL';
}
i18nMessageString = `APP.MESSAGES.INFO.NODE_COPY.${i18MessageSuffix}`;
@@ -461,47 +461,63 @@ export class ContentManagementService {
this.nodeActionsService.moveNodes(nodes, permissionForMove),
this.nodeActionsService.contentMoved
).subscribe(
(result) => {
result => {
const [operationResult, moveResponse] = result;
this.showMoveMessage(nodes, operationResult, moveResponse);
this.nodesMoved.next(null);
},
(error) => {
error => {
this.showMoveMessage(nodes, error);
}
);
}
private undoMoveNodes(moveResponse, selectionParentId) {
const movedNodes = (moveResponse && moveResponse['succeeded']) ? moveResponse['succeeded'] : [];
const partiallyMovedNodes = (moveResponse && moveResponse['partiallySucceeded']) ? moveResponse['partiallySucceeded'] : [];
const movedNodes =
moveResponse && moveResponse['succeeded']
? moveResponse['succeeded']
: [];
const partiallyMovedNodes =
moveResponse && moveResponse['partiallySucceeded']
? moveResponse['partiallySucceeded']
: [];
const restoreDeletedNodesBatch = this.nodeActionsService.moveDeletedEntries
.map((folderEntry) => {
const restoreDeletedNodesBatch = this.nodeActionsService.moveDeletedEntries.map(
folderEntry => {
return this.contentApi
.restoreNode(folderEntry.nodeId || folderEntry.id)
.pipe(map(node => node.entry));
});
}
);
zip(...restoreDeletedNodesBatch, of(null))
.pipe(mergeMap(() => {
.pipe(
mergeMap(() => {
const nodesToBeMovedBack = [...partiallyMovedNodes, ...movedNodes];
const revertMoveBatch = this.nodeActionsService
.flatten(nodesToBeMovedBack)
.filter(node => node.entry || (node.itemMoved && node.itemMoved.entry))
.map((node) => {
.filter(
node => node.entry || (node.itemMoved && node.itemMoved.entry)
)
.map(node => {
if (node.itemMoved) {
return this.nodeActionsService.moveNodeAction(node.itemMoved.entry, node.initialParentId);
return this.nodeActionsService.moveNodeAction(
node.itemMoved.entry,
node.initialParentId
);
} else {
return this.nodeActionsService.moveNodeAction(node.entry, selectionParentId);
return this.nodeActionsService.moveNodeAction(
node.entry,
selectionParentId
);
}
});
return zip(...revertMoveBatch, of(null));
}))
})
)
.subscribe(
() => {
this.nodesMoved.next(null);
@@ -514,7 +530,11 @@ export class ContentManagementService {
errorJson = JSON.parse(error.message);
} catch {}
if (errorJson && errorJson.error && errorJson.error.statusCode === 403) {
if (
errorJson &&
errorJson.error &&
errorJson.error.statusCode === 403
) {
message = 'APP.MESSAGES.ERRORS.PERMISSION';
}
@@ -574,9 +594,7 @@ export class ContentManagementService {
private undoDeleteNode(item: DeletedNodeInfo): Observable<DeletedNodeInfo> {
const { id, name } = item;
return this.contentApi
.restoreNode(id)
.pipe(
return this.contentApi.restoreNode(id).pipe(
map(() => {
return {
id,
@@ -614,8 +632,7 @@ export class ContentManagementService {
private restoreNode(node: MinimalNodeEntity): Observable<RestoredNode> {
const { entry } = node;
return this.contentApi.restoreNode(entry.id)
.pipe(
return this.contentApi.restoreNode(entry.id).pipe(
map(() => ({
status: 1,
entry
@@ -655,9 +672,7 @@ export class ContentManagementService {
private purgeDeletedNode(node: NodeInfo): Observable<DeletedNodeInfo> {
const { id, name } = node;
return this.contentApi
.purgeDeletedNode(id)
.pipe(
return this.contentApi.purgeDeletedNode(id).pipe(
map(() => ({
status: 1,
id,
@@ -851,10 +866,7 @@ export class ContentManagementService {
const { name } = node.entry;
const id = node.entry.nodeId || node.entry.id;
return this.contentApi
.deleteNode(id)
.pipe(
return this.contentApi.deleteNode(id).pipe(
map(() => {
return {
id,
@@ -881,10 +893,9 @@ export class ContentManagementService {
}
if (status.allSucceeded && !status.oneSucceeded) {
return new SnackbarInfoAction(
'APP.MESSAGES.INFO.NODE_DELETION.PLURAL',
{ number: status.success.length }
);
return new SnackbarInfoAction('APP.MESSAGES.INFO.NODE_DELETION.PLURAL', {
number: status.success.length
});
}
if (status.someFailed && status.someSucceeded && !status.oneSucceeded) {
@@ -908,10 +919,9 @@ export class ContentManagementService {
}
if (status.oneFailed && !status.someSucceeded) {
return new SnackbarErrorAction(
'APP.MESSAGES.ERRORS.NODE_DELETION',
{ name: status.fail[0].name }
);
return new SnackbarErrorAction('APP.MESSAGES.ERRORS.NODE_DELETION', {
name: status.fail[0].name
});
}
if (status.oneSucceeded && !status.someFailed) {
@@ -924,10 +934,23 @@ export class ContentManagementService {
return null;
}
private showMoveMessage(nodes: Array<MinimalNodeEntity>, info: any, moveResponse?: any) {
const succeeded = (moveResponse && moveResponse['succeeded']) ? moveResponse['succeeded'].length : 0;
const partiallySucceeded = (moveResponse && moveResponse['partiallySucceeded']) ? moveResponse['partiallySucceeded'].length : 0;
const failures = (moveResponse && moveResponse['failed']) ? moveResponse['failed'].length : 0;
private showMoveMessage(
nodes: Array<MinimalNodeEntity>,
info: any,
moveResponse?: any
) {
const succeeded =
moveResponse && moveResponse['succeeded']
? moveResponse['succeeded'].length
: 0;
const partiallySucceeded =
moveResponse && moveResponse['partiallySucceeded']
? moveResponse['partiallySucceeded'].length
: 0;
const failures =
moveResponse && moveResponse['failed']
? moveResponse['failed'].length
: 0;
let successMessage = '';
let partialSuccessMessage = '';
@@ -935,28 +958,29 @@ export class ContentManagementService {
let errorMessage = '';
if (typeof info === 'string') {
// in case of success
if (info.toLowerCase().indexOf('succes') !== -1) {
const i18nMessageString = 'APP.MESSAGES.INFO.NODE_MOVE.';
let i18MessageSuffix = '';
if (succeeded) {
i18MessageSuffix = ( succeeded === 1 ) ? 'SINGULAR' : 'PLURAL';
i18MessageSuffix = succeeded === 1 ? 'SINGULAR' : 'PLURAL';
successMessage = `${i18nMessageString}${i18MessageSuffix}`;
}
if (partiallySucceeded) {
i18MessageSuffix = ( partiallySucceeded === 1 ) ? 'PARTIAL.SINGULAR' : 'PARTIAL.PLURAL';
i18MessageSuffix =
partiallySucceeded === 1 ? 'PARTIAL.SINGULAR' : 'PARTIAL.PLURAL';
partialSuccessMessage = `${i18nMessageString}${i18MessageSuffix}`;
}
if (failures) {
// if moving failed for ALL nodes, emit error
if (failures === nodes.length) {
const errors = this.nodeActionsService.flatten(moveResponse['failed']);
const errors = this.nodeActionsService.flatten(
moveResponse['failed']
);
errorMessage = this.getErrorMessage(errors[0]);
} else {
i18MessageSuffix = 'PARTIAL.FAIL';
failedMessage = `${i18nMessageString}${i18MessageSuffix}`;
@@ -965,18 +989,24 @@ export class ContentManagementService {
} else {
errorMessage = 'APP.MESSAGES.ERRORS.GENERIC';
}
} else {
errorMessage = this.getErrorMessage(info);
}
const undo = (succeeded + partiallySucceeded > 0) ? this.translation.instant('APP.ACTIONS.UNDO') : '';
const undo =
succeeded + partiallySucceeded > 0
? this.translation.instant('APP.ACTIONS.UNDO')
: '';
failedMessage = errorMessage ? errorMessage : failedMessage;
const beforePartialSuccessMessage = (successMessage && partialSuccessMessage) ? ' ' : '';
const beforeFailedMessage = ((successMessage || partialSuccessMessage) && failedMessage) ? ' ' : '';
const beforePartialSuccessMessage =
successMessage && partialSuccessMessage ? ' ' : '';
const beforeFailedMessage =
(successMessage || partialSuccessMessage) && failedMessage ? ' ' : '';
const initialParentId = this.nodeActionsService.getEntryParentId(nodes[0].entry);
const initialParentId = this.nodeActionsService.getEntryParentId(
nodes[0].entry
);
const messages = this.translation.instant(
[successMessage, partialSuccessMessage, failedMessage],
@@ -986,13 +1016,17 @@ export class ContentManagementService {
// TODO: review in terms of i18n
this.snackBar
.open(
messages[successMessage]
+ beforePartialSuccessMessage + messages[partialSuccessMessage]
+ beforeFailedMessage + messages[failedMessage]
, undo, {
messages[successMessage] +
beforePartialSuccessMessage +
messages[partialSuccessMessage] +
beforeFailedMessage +
messages[failedMessage],
undo,
{
panelClass: 'info-snackbar',
duration: 3000
})
}
)
.onAction()
.subscribe(() => this.undoMoveNodes(moveResponse, initialParentId));
}
@@ -1001,16 +1035,18 @@ export class ContentManagementService {
let i18nMessageString = 'APP.MESSAGES.ERRORS.GENERIC';
try {
const { error: { statusCode } } = JSON.parse(errorObject.message);
const {
error: { statusCode }
} = JSON.parse(errorObject.message);
if (statusCode === 409) {
i18nMessageString = 'APP.MESSAGES.ERRORS.NODE_MOVE';
} else if (statusCode === 403) {
i18nMessageString = 'APP.MESSAGES.ERRORS.PERMISSION';
}
} catch (err) { /* Do nothing, keep the original message */ }
} catch (err) {
/* Do nothing, keep the original message */
}
return i18nMessageString;
}

File diff suppressed because it is too large Load Diff

View File

@@ -27,9 +27,22 @@ import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material';
import { Observable, Subject, of, zip, from } from 'rxjs';
import { AlfrescoApiService, ContentService, DataColumn, TranslationService } from '@alfresco/adf-core';
import { DocumentListService, ContentNodeSelectorComponent, ContentNodeSelectorComponentData } from '@alfresco/adf-content-services';
import { MinimalNodeEntity, MinimalNodeEntryEntity, SitePaging } from 'alfresco-js-api';
import {
AlfrescoApiService,
ContentService,
DataColumn,
TranslationService
} from '@alfresco/adf-core';
import {
DocumentListService,
ContentNodeSelectorComponent,
ContentNodeSelectorComponentData
} from '@alfresco/adf-content-services';
import {
MinimalNodeEntity,
MinimalNodeEntryEntity,
SitePaging
} from 'alfresco-js-api';
import { ContentApiService } from '../services/content-api.service';
import { catchError, map, mergeMap } from 'rxjs/operators';
@@ -38,17 +51,21 @@ export class NodeActionsService {
static SNACK_MESSAGE_DURATION_WITH_UNDO = 10000;
static SNACK_MESSAGE_DURATION = 3000;
contentCopied: Subject<MinimalNodeEntity[]> = new Subject<MinimalNodeEntity[]>();
contentCopied: Subject<MinimalNodeEntity[]> = new Subject<
MinimalNodeEntity[]
>();
contentMoved: Subject<any> = new Subject<any>();
moveDeletedEntries: any[] = [];
isSitesDestinationAvailable = false;
constructor(private contentService: ContentService,
constructor(
private contentService: ContentService,
private contentApi: ContentApiService,
private dialog: MatDialog,
private documentListService: DocumentListService,
private apiService: AlfrescoApiService,
private translation: TranslationService) {}
private translation: TranslationService
) {}
/**
* Copy node list
@@ -56,7 +73,10 @@ export class NodeActionsService {
* @param contentEntities nodes to copy
* @param permission permission which is needed to apply the action
*/
public copyNodes(contentEntities: any[], permission?: string): Subject<string> {
public copyNodes(
contentEntities: any[],
permission?: string
): Subject<string> {
return this.doBatchOperation('copy', contentEntities, permission);
}
@@ -66,7 +86,10 @@ export class NodeActionsService {
* @param contentEntities nodes to move
* @param permission permission which is needed to apply the action
*/
public moveNodes(contentEntities: any[], permission?: string): Subject<string> {
public moveNodes(
contentEntities: any[],
permission?: string
): Subject<string> {
return this.doBatchOperation('move', contentEntities, permission);
}
@@ -77,17 +100,23 @@ export class NodeActionsService {
* @param contentEntities the contentEntities which have to have the action performed on
* @param permission permission which is needed to apply the action
*/
doBatchOperation(action: string, contentEntities: any[], permission?: string): Subject<string> {
doBatchOperation(
action: string,
contentEntities: any[],
permission?: string
): Subject<string> {
const observable: Subject<string> = new Subject<string>();
if (!this.isEntryEntitiesArray(contentEntities)) {
observable.error(new Error(JSON.stringify({error: {statusCode: 400}})));
observable.error(
new Error(JSON.stringify({ error: { statusCode: 400 } }))
);
} else if (this.checkPermission(action, contentEntities, permission)) {
const destinationSelection = this.getContentNodeSelection(action, contentEntities);
const destinationSelection = this.getContentNodeSelection(
action,
contentEntities
);
destinationSelection.subscribe((selections: MinimalNodeEntryEntity[]) => {
const contentEntry = contentEntities[0].entry;
// Check if there's nodeId for Shared Files
const contentEntryId = contentEntry.nodeId || contentEntry.id;
@@ -98,35 +127,39 @@ export class NodeActionsService {
const selection = selections[0];
let action$: Observable<any>;
if (action === 'move' && contentEntities.length === 1 && type === 'content') {
action$ = this.documentListService.moveNode(contentEntryId, selection.id);
if (
action === 'move' &&
contentEntities.length === 1 &&
type === 'content'
) {
action$ = this.documentListService.moveNode(
contentEntryId,
selection.id
);
} else {
contentEntities.forEach((node) => {
contentEntities.forEach(node => {
batch.push(this[`${action}NodeAction`](node.entry, selection.id));
});
action$ = zip(...batch);
}
action$
.subscribe(
(newContent) => {
observable.next(`OPERATION.SUCCES.${type.toUpperCase()}.${action.toUpperCase()}`);
action$.subscribe(newContent => {
observable.next(
`OPERATION.SUCCES.${type.toUpperCase()}.${action.toUpperCase()}`
);
const processedData = this.processResponse(newContent);
if (action === 'copy') {
this.contentCopied.next(processedData.succeeded);
} else if (action === 'move') {
this.contentMoved.next(processedData);
}
},
observable.error.bind(observable)
);
}, observable.error.bind(observable));
});
} else {
observable.error(new Error(JSON.stringify({error: {statusCode: 403}})));
observable.error(
new Error(JSON.stringify({ error: { statusCode: 403 } }))
);
}
return observable;
@@ -134,14 +167,18 @@ export class NodeActionsService {
isEntryEntitiesArray(contentEntities: any[]): boolean {
if (contentEntities && contentEntities.length) {
const nonEntryNode = contentEntities.find(node => (!node || !node.entry || !(node.entry.nodeId || node.entry.id)));
const nonEntryNode = contentEntities.find(
node => !node || !node.entry || !(node.entry.nodeId || node.entry.id)
);
return !nonEntryNode;
}
return false;
}
checkPermission(action: string, contentEntities: any[], permission?: string) {
const notAllowedNode = contentEntities.find(node => !this.isActionAllowed(action, node.entry, permission));
const notAllowedNode = contentEntities.find(
node => !this.isActionAllowed(action, node.entry, permission)
);
return !notAllowedNode;
}
@@ -150,16 +187,25 @@ export class NodeActionsService {
if (nodeEntry.parentId) {
entryParentId = nodeEntry.parentId;
} else if (nodeEntry.path && nodeEntry.path.elements && nodeEntry.path.elements.length) {
entryParentId = nodeEntry.path.elements[nodeEntry.path.elements.length - 1].id;
} else if (
nodeEntry.path &&
nodeEntry.path.elements &&
nodeEntry.path.elements.length
) {
entryParentId =
nodeEntry.path.elements[nodeEntry.path.elements.length - 1].id;
}
return entryParentId;
}
getContentNodeSelection(action: string, contentEntities: MinimalNodeEntity[]): Subject<MinimalNodeEntryEntity[]> {
const currentParentFolderId = this.getEntryParentId(contentEntities[0].entry);
getContentNodeSelection(
action: string,
contentEntities: MinimalNodeEntity[]
): Subject<MinimalNodeEntryEntity[]> {
const currentParentFolderId = this.getEntryParentId(
contentEntities[0].entry
);
const customDropdown: SitePaging = {
list: {
@@ -219,7 +265,10 @@ export class NodeActionsService {
}
const number = nodes.length;
return this.translation.instant(`NODE_SELECTOR.${action.toUpperCase()}_${keyPrefix}`, {name, number});
return this.translation.instant(
`NODE_SELECTOR.${action.toUpperCase()}_${keyPrefix}`,
{ name, number }
);
}
private canCopyMoveInsideIt(entry: MinimalNodeEntryEntity): boolean {
@@ -231,7 +280,11 @@ export class NodeActionsService {
}
private isSite(entry) {
return !!entry.guid || entry.nodeType === 'st:site' || entry.nodeType === 'st:sites';
return (
!!entry.guid ||
entry.nodeType === 'st:site' ||
entry.nodeType === 'st:sites'
);
}
close() {
@@ -240,7 +293,6 @@ export class NodeActionsService {
// todo: review this approach once 5.2.3 is out
private customizeBreadcrumb(node: MinimalNodeEntryEntity) {
if (node && node.path && node.path.elements) {
const elements = node.path.elements;
@@ -250,16 +302,16 @@ export class NodeActionsService {
// make sure first item is 'Personal Files'
if (elements[0]) {
elements[0].name = this.translation.instant('APP.BROWSE.PERSONAL.TITLE');
elements[0].name = this.translation.instant(
'APP.BROWSE.PERSONAL.TITLE'
);
elements[0].id = '-my-';
} else {
node.name = this.translation.instant('APP.BROWSE.PERSONAL.TITLE');
}
} else if (elements[1].name === 'Sites') {
this.normalizeSitePath(node);
}
} else if (elements.length === 1) {
if (node.name === 'Sites') {
node.name = this.translation.instant('APP.BROWSE.LIBRARIES.TITLE');
@@ -313,7 +365,6 @@ export class NodeActionsService {
copyNodeAction(nodeEntry, selectionId): Observable<any> {
if (nodeEntry.isFolder) {
return this.copyFolderAction(nodeEntry, selectionId);
} else {
// any other type is treated as 'content'
return this.copyContentAction(nodeEntry, selectionId);
@@ -326,22 +377,30 @@ export class NodeActionsService {
const contentEntryId = contentEntry.nodeId || contentEntry.id;
// use local method until new name parameter is added on ADF copyNode
return this.copyNode(contentEntryId, selectionId, _oldName)
.pipe(catchError((err) => {
return this.copyNode(contentEntryId, selectionId, _oldName).pipe(
catchError(err => {
let errStatusCode;
try {
const {error: {statusCode}} = JSON.parse(err.message);
const {
error: { statusCode }
} = JSON.parse(err.message);
errStatusCode = statusCode;
} catch (e) { //
} catch (e) {
//
}
if (errStatusCode && errStatusCode === 409) {
return this.copyContentAction(contentEntry, selectionId, this.getNewNameFrom(_oldName, contentEntry.name));
return this.copyContentAction(
contentEntry,
selectionId,
this.getNewNameFrom(_oldName, contentEntry.name)
);
} else {
// do not throw error, to be able to show message in case of partial copy of files
return of(err || 'Server error');
}
}));
})
);
}
copyFolderAction(contentEntry, selectionId): Observable<any> {
@@ -351,33 +410,45 @@ export class NodeActionsService {
let $childrenToCopy: Observable<any>;
let newDestinationFolder;
return this.copyNode(contentEntryId, selectionId, contentEntry.name)
.pipe(
catchError((err) => {
return this.copyNode(contentEntryId, selectionId, contentEntry.name).pipe(
catchError(err => {
let errStatusCode;
try {
const {error: {statusCode}} = JSON.parse(err.message);
const {
error: { statusCode }
} = JSON.parse(err.message);
errStatusCode = statusCode;
} catch {}
if (errStatusCode && errStatusCode === 409) {
$destinationFolder = this.getChildByName(selectionId, contentEntry.name);
$destinationFolder = this.getChildByName(
selectionId,
contentEntry.name
);
$childrenToCopy = this.getNodeChildren(contentEntryId);
return $destinationFolder
.pipe(
mergeMap((destination) => {
return $destinationFolder.pipe(
mergeMap(destination => {
newDestinationFolder = destination;
return $childrenToCopy;
}),
mergeMap((nodesToCopy) => {
mergeMap(nodesToCopy => {
const batch = [];
nodesToCopy.list.entries.forEach((node) => {
nodesToCopy.list.entries.forEach(node => {
if (node.entry.isFolder) {
batch.push(this.copyFolderAction(node.entry, newDestinationFolder.entry.id));
batch.push(
this.copyFolderAction(
node.entry,
newDestinationFolder.entry.id
)
);
} else {
batch.push(this.copyContentAction(node.entry, newDestinationFolder.entry.id));
batch.push(
this.copyContentAction(
node.entry,
newDestinationFolder.entry.id
)
);
}
});
@@ -387,7 +458,6 @@ export class NodeActionsService {
return zip(...batch);
})
);
} else {
// do not throw error, to be able to show message in case of partial copy of files
return of(err || 'Server error');
@@ -402,9 +472,8 @@ export class NodeActionsService {
if (nodeEntry.isFolder) {
const initialParentId = nodeEntry.parentId;
return this.moveFolderAction(nodeEntry, selectionId)
.pipe(mergeMap((newContent) => {
return this.moveFolderAction(nodeEntry, selectionId).pipe(
mergeMap(newContent => {
// take no extra action, if folder is moved to the same location
if (initialParentId === selectionId) {
return of(newContent);
@@ -415,18 +484,14 @@ export class NodeActionsService {
// else, check if moving this nodeEntry succeeded for ALL of its nodes
if (processedData.failed.length === 0) {
// check if folder still exists on location
return this.getChildByName(initialParentId, nodeEntry.name)
.pipe(
return this.getChildByName(initialParentId, nodeEntry.name).pipe(
mergeMap(folderOnInitialLocation => {
if (folderOnInitialLocation) {
// Check if there's nodeId for Shared Files
const nodeEntryId = nodeEntry.nodeId || nodeEntry.id;
// delete it from location
return this.contentApi
.deleteNode(nodeEntryId)
.pipe(
return this.contentApi.deleteNode(nodeEntryId).pipe(
mergeMap(() => {
this.moveDeletedEntries.push(nodeEntry);
return of(newContent);
@@ -436,11 +501,10 @@ export class NodeActionsService {
return of(newContent);
})
);
}
return of(newContent);
}));
})
);
} else {
// any other type is treated as 'content'
return this.moveContentAction(nodeEntry, selectionId);
@@ -455,37 +519,50 @@ export class NodeActionsService {
let $childrenToMove: Observable<any>;
let newDestinationFolder;
return this.documentListService.moveNode(contentEntryId, selectionId)
.pipe(
map((itemMoved) => {
return this.documentListService.moveNode(contentEntryId, selectionId).pipe(
map(itemMoved => {
return { itemMoved, initialParentId };
}),
catchError(err => {
let errStatusCode;
try {
const {error: {statusCode}} = JSON.parse(err.message);
const {
error: { statusCode }
} = JSON.parse(err.message);
errStatusCode = statusCode;
} catch (e) { //
} catch (e) {
//
}
if (errStatusCode && errStatusCode === 409) {
$destinationFolder = this.getChildByName(selectionId, contentEntry.name);
$destinationFolder = this.getChildByName(
selectionId,
contentEntry.name
);
$childrenToMove = this.getNodeChildren(contentEntryId);
return $destinationFolder
.pipe(
mergeMap((destination) => {
return $destinationFolder.pipe(
mergeMap(destination => {
newDestinationFolder = destination;
return $childrenToMove;
}),
mergeMap((childrenToMove) => {
mergeMap(childrenToMove => {
const batch = [];
childrenToMove.list.entries.forEach((node) => {
childrenToMove.list.entries.forEach(node => {
if (node.entry.isFolder) {
batch.push(this.moveFolderAction(node.entry, newDestinationFolder.entry.id));
batch.push(
this.moveFolderAction(
node.entry,
newDestinationFolder.entry.id
)
);
} else {
batch.push(this.moveContentAction(node.entry, newDestinationFolder.entry.id));
batch.push(
this.moveContentAction(
node.entry,
newDestinationFolder.entry.id
)
);
}
});
@@ -508,13 +585,11 @@ export class NodeActionsService {
const contentEntryId = contentEntry.nodeId || contentEntry.id;
const initialParentId = this.getEntryParentId(contentEntry);
return this.documentListService
.moveNode(contentEntryId, selectionId)
.pipe(
map((itemMoved) => {
return this.documentListService.moveNode(contentEntryId, selectionId).pipe(
map(itemMoved => {
return { itemMoved, initialParentId };
}),
catchError((err) => {
catchError(err => {
// do not throw error, to be able to show message in case of partial move of files
return of(err);
})
@@ -526,22 +601,28 @@ export class NodeActionsService {
this.getNodeChildren(parentId).subscribe(
(childrenNodes: any) => {
const result = childrenNodes.list.entries.find(node => (node.entry.name === name));
const result = childrenNodes.list.entries.find(
node => node.entry.name === name
);
if (result) {
matchedNodes.next(result);
} else {
matchedNodes.next(null);
}
},
(err) => {
err => {
return of(err || 'Server error');
});
}
);
return matchedNodes;
}
private isActionAllowed(action: string, node: MinimalNodeEntryEntity, permission?: string): boolean {
private isActionAllowed(
action: string,
node: MinimalNodeEntryEntity,
permission?: string
): boolean {
if (action === 'copy') {
return true;
}
@@ -553,11 +634,14 @@ export class NodeActionsService {
const node: MinimalNodeEntryEntity = row.node.entry;
this.isSitesDestinationAvailable = !!node['guid'];
return (!node.isFile && (node.nodeType !== 'app:folderlink'));
return !node.isFile && node.nodeType !== 'app:folderlink';
}
// todo: review once 1.10-beta6 is out
private imageResolver(row: /*ShareDataRow*/ any, col: DataColumn): string | null {
private imageResolver(
row: /*ShareDataRow*/ any,
col: DataColumn
): string | null {
const entry: MinimalNodeEntryEntity = row.node.entry;
if (!this.contentService.hasPermission(entry, 'update')) {
return this.documentListService.getMimeTypeIcon('disable/folder');
@@ -571,7 +655,9 @@ export class NodeActionsService {
// remove extension in case there is one
const fileExtension = extensionMatch ? extensionMatch[0] : '';
let extensionFree = extensionMatch ? name.slice(0, extensionMatch.index) : name;
let extensionFree = extensionMatch
? name.slice(0, extensionMatch.index)
: name;
let prefixNumber = 1;
let baseExtensionFree;
@@ -580,25 +666,22 @@ export class NodeActionsService {
const baseExtensionMatch = baseName.match(/\.[^/.]+$/);
// remove extension in case there is one
baseExtensionFree = baseExtensionMatch ? baseName.slice(0, baseExtensionMatch.index) : baseName;
baseExtensionFree = baseExtensionMatch
? baseName.slice(0, baseExtensionMatch.index)
: baseName;
}
if (!baseExtensionFree || baseExtensionFree !== extensionFree) {
// check if name already has integer appended on end:
const oldPrefix = extensionFree.match('-[0-9]+$');
if (oldPrefix) {
// if so, try to get the number at the end
const oldPrefixNumber = parseInt(oldPrefix[0].slice(1), 10);
if (oldPrefixNumber.toString() === oldPrefix[0].slice(1)) {
extensionFree = extensionFree.slice(0, oldPrefix.index);
prefixNumber = oldPrefixNumber + 1;
}
}
}
return extensionFree + '-' + prefixNumber + fileExtension;
}
@@ -610,7 +693,9 @@ export class NodeActionsService {
* @param params optional parameters
*/
getNodeChildren(nodeId: string, params?) {
return from(this.apiService.getInstance().nodes.getNodeChildren(nodeId, params));
return from(
this.apiService.getInstance().nodes.getNodeChildren(nodeId, params)
);
}
// Copied from ADF document-list.service, and added the name parameter
@@ -622,7 +707,11 @@ export class NodeActionsService {
* @param name The new name for the copy that would be added on the destination folder
*/
copyNode(nodeId: string, targetParentId: string, name?: string) {
return from(this.apiService.getInstance().nodes.copyNode(nodeId, {targetParentId, name}));
return from(
this.apiService
.getInstance()
.nodes.copyNode(nodeId, { targetParentId, name })
);
}
public flatten(nDimArray) {
@@ -634,8 +723,7 @@ export class NodeActionsService {
const resultingArray = [];
do {
nodeQueue.forEach(
(node) => {
nodeQueue.forEach(node => {
if (Array.isArray(node)) {
nodeQueue.push(...node);
} else {
@@ -644,8 +732,7 @@ export class NodeActionsService {
const nodeIndex = nodeQueue.indexOf(node);
nodeQueue.splice(nodeIndex, 1);
}
);
});
} while (nodeQueue.length);
return resultingArray;
@@ -659,43 +746,38 @@ export class NodeActionsService {
};
if (Array.isArray(data)) {
return data.reduce(
(acc, next) => {
return data.reduce((acc, next) => {
if (next instanceof Error) {
acc.failed.push(next);
} else if (Array.isArray(next)) {
// if content of a folder was moved
const folderMoveResponseData = this.flatten(next);
const foundError = folderMoveResponseData.find(node => node instanceof Error);
const foundError = folderMoveResponseData.find(
node => node instanceof Error
);
// data might contain also items of form: { itemMoved, initialParentId }
const foundEntry = folderMoveResponseData.find(
node => (node.itemMoved && node.itemMoved.entry) || (node && node.entry)
node =>
(node.itemMoved && node.itemMoved.entry) || (node && node.entry)
);
if (!foundError) {
// consider success if NONE of the items from the folder move response is an error
acc.succeeded.push(next);
} else if (!foundEntry) {
// consider failed if NONE of the items has an entry
acc.failed.push(next);
} else {
// partially move folder
acc.partiallySucceeded.push(next);
}
} else {
acc.succeeded.push(next);
}
return acc;
},
moveStatus
);
}, moveStatus);
} else {
if ((data.itemMoved && data.itemMoved.entry) || (data && data.entry)) {
moveStatus.succeeded.push(data);

View File

@@ -32,7 +32,6 @@ describe('NodePermissionService', () => {
permission = new NodePermissionService();
});
it('should return false when source is null', () => {
const source = null;
@@ -57,7 +56,11 @@ describe('NodePermissionService', () => {
{ entry: { allowableOperationsOnTarget: ['update'] } }
];
expect(permission.check(source, ['update'], { target: 'allowableOperationsOnTarget' })).toBe(true);
expect(
permission.check(source, ['update'], {
target: 'allowableOperationsOnTarget'
})
).toBe(true);
});
it('should return false when source does not have allowableOperations permission', () => {
@@ -67,7 +70,11 @@ describe('NodePermissionService', () => {
{ entry: { allowableOperations: ['delete'] } }
];
expect(permission.check(source, ['update'], { target: 'allowableOperationsOnTarget' })).toBe(false);
expect(
permission.check(source, ['update'], {
target: 'allowableOperationsOnTarget'
})
).toBe(false);
});
it('should return false when source does not have allowableOperationsOnTarget permission', () => {
@@ -77,7 +84,11 @@ describe('NodePermissionService', () => {
{ entry: { allowableOperationsOnTarget: ['delete'] } }
];
expect(permission.check(source, ['update'], { target: 'allowableOperationsOnTarget' })).toBe(false);
expect(
permission.check(source, ['update'], {
target: 'allowableOperationsOnTarget'
})
).toBe(false);
});
it('should return true when source has `OR` allowableOperations permission', () => {
@@ -94,20 +105,32 @@ describe('NodePermissionService', () => {
const source = [
{ entry: { allowableOperations: ['update', 'delete', 'other'] } },
{ entry: { allowableOperations: ['update', 'create', 'other'] } },
{ entry: { allowableOperations: ['update', 'updatePermissions', 'other'] } }
{
entry: {
allowableOperations: ['update', 'updatePermissions', 'other']
}
}
];
expect(permission.check(source, ['update', 'other'], { operation: 'AND' })).toBe(true);
expect(
permission.check(source, ['update', 'other'], { operation: 'AND' })
).toBe(true);
});
it('should return false when source has no `AND` allowableOperations permission', () => {
const source = [
{ entry: { allowableOperations: ['update', 'delete', 'other'] } },
{ entry: { allowableOperations: ['update', 'create', 'other'] } },
{ entry: { allowableOperations: ['update', 'updatePermissions', 'other'] } }
{
entry: {
allowableOperations: ['update', 'updatePermissions', 'other']
}
}
];
expect(permission.check(source, ['update', 'bogus'], { operation: 'AND' })).toBe(false);
expect(
permission.check(source, ['update', 'bogus'], { operation: 'AND' })
).toBe(false);
});
it('should return false when source has no allowableOperations', () => {
@@ -131,7 +154,6 @@ describe('NodePermissionService', () => {
});
});
describe('Single source permission', () => {
it('should return true when source has allowableOperations permission', () => {
const source = { entry: { allowableOperations: ['update'] } };
@@ -142,7 +164,11 @@ describe('NodePermissionService', () => {
it('should return true when source has allowableOperationsOnTarget permission', () => {
const source = { entry: { allowableOperationsOnTarget: ['update'] } };
expect(permission.check(source, ['update'], { target: 'allowableOperationsOnTarget' })).toBe(true);
expect(
permission.check(source, ['update'], {
target: 'allowableOperationsOnTarget'
})
).toBe(true);
});
it('should return false when source does not have allowableOperations permission', () => {
@@ -154,7 +180,11 @@ describe('NodePermissionService', () => {
it('should return false when source does not have allowableOperationsOnTarget permission', () => {
const source = { entry: { allowableOperationsOnTarget: ['delete'] } };
expect(permission.check(source, ['update'], { target: 'allowableOperationsOnTarget' })).toBe(false);
expect(
permission.check(source, ['update'], {
target: 'allowableOperationsOnTarget'
})
).toBe(false);
});
it('should return true when source has `OR` allowableOperations permission', () => {
@@ -166,13 +196,19 @@ describe('NodePermissionService', () => {
it('should return true when source has `AND` allowableOperations permission', () => {
const source = { entry: { allowableOperations: ['update', 'other'] } };
expect(permission.check(source, ['update', 'other'], { operation: 'AND' })).toBe(true);
expect(
permission.check(source, ['update', 'other'], { operation: 'AND' })
).toBe(true);
});
it('should return false when source has no `AND` allowableOperations permission', () => {
const source = { entry: { allowableOperations: ['update', 'updatePermissions', 'other'] } };
const source = {
entry: { allowableOperations: ['update', 'updatePermissions', 'other'] }
};
expect(permission.check(source, ['update', 'bogus'], { operation: 'AND' })).toBe(false);
expect(
permission.check(source, ['update', 'bogus'], { operation: 'AND' })
).toBe(false);
});
it('should return false when source has no allowableOperations', () => {

View File

@@ -42,7 +42,10 @@ export class NodePermissionService implements NodePermissions {
if (Array.isArray(source) && source.length) {
const arr = this.sanitize(source);
return !!arr.length && source.every(node => this.hasPermission(node, permissions, opts));
return (
!!arr.length &&
source.every(node => this.hasPermission(node, permissions, opts))
);
}
return this.hasPermission(source, permissions, opts);
@@ -52,13 +55,20 @@ export class NodePermissionService implements NodePermissions {
}
private hasPermission(node, permissions, options): boolean {
const allowableOperations = this.getAllowableOperations(node, options.target);
const allowableOperations = this.getAllowableOperations(
node,
options.target
);
if (allowableOperations.length) {
if (options.operation === NodePermissionService.DEFAULT_OPERATION) {
return permissions.some(permission => allowableOperations.includes(permission));
return permissions.some(permission =>
allowableOperations.includes(permission)
);
} else {
return permissions.every(permission => allowableOperations.includes(permission));
return permissions.every(permission =>
allowableOperations.includes(permission)
);
}
}

View File

@@ -45,10 +45,7 @@ import {
@NgModule({
imports: [
StoreModule.forRoot(
{ app: appReducer },
{ initialState: INITIAL_STATE }
),
StoreModule.forRoot({ app: appReducer }, { initialState: INITIAL_STATE }),
StoreRouterConnectingModule.forRoot({ stateKey: 'router' }),
EffectsModule.forRoot([
SnackbarEffects,

View File

@@ -99,10 +99,7 @@ export class DownloadEffects {
private downloadFile(node: NodeInfo) {
if (node) {
this.download(
this.contentApi.getContentUrl(node.id, true),
node.name
);
this.download(this.contentApi.getContentUrl(node.id, true), node.name);
}
}

View File

@@ -26,7 +26,12 @@
import { Effect, Actions, ofType } from '@ngrx/effects';
import { Injectable } from '@angular/core';
import { map, take } from 'rxjs/operators';
import { ADD_FAVORITE, AddFavoriteAction, RemoveFavoriteAction, REMOVE_FAVORITE } from '../actions/favorite.actions';
import {
ADD_FAVORITE,
AddFavoriteAction,
RemoveFavoriteAction,
REMOVE_FAVORITE
} from '../actions/favorite.actions';
import { Store } from '@ngrx/store';
import { AppStore } from '../states';
import { appSelection } from '../selectors/app.selectors';
@@ -77,6 +82,4 @@ export class FavoriteEffects {
}
})
);
}

View File

@@ -27,8 +27,10 @@ import { Effect, Actions, ofType } from '@ngrx/effects';
import { Injectable } from '@angular/core';
import { map, take } from 'rxjs/operators';
import {
DeleteLibraryAction, DELETE_LIBRARY,
CreateLibraryAction, CREATE_LIBRARY
DeleteLibraryAction,
DELETE_LIBRARY,
CreateLibraryAction,
CREATE_LIBRARY
} from '../actions';
import { ContentManagementService } from '../../services/content-management.service';
import { Store } from '@ngrx/store';

View File

@@ -117,9 +117,7 @@ export class NodeEffects {
.pipe(take(1))
.subscribe(selection => {
if (selection && selection.count > 0) {
this.contentService.purgeDeletedNodes(
selection.nodes
);
this.contentService.purgeDeletedNodes(selection.nodes);
}
});
}
@@ -138,9 +136,7 @@ export class NodeEffects {
.pipe(take(1))
.subscribe(selection => {
if (selection && selection.count > 0) {
this.contentService.restoreDeletedNodes(
selection.nodes
);
this.contentService.restoreDeletedNodes(selection.nodes);
}
});
}
@@ -264,9 +260,7 @@ export class NodeEffects {
.pipe(take(1))
.subscribe(selection => {
if (selection && !selection.isEmpty) {
this.contentService.managePermissions(
selection.first
);
this.contentService.managePermissions(selection.first);
}
});
}
@@ -285,9 +279,7 @@ export class NodeEffects {
.pipe(take(1))
.subscribe(selection => {
if (selection && selection.file) {
this.contentService.manageVersions(
selection.file
);
this.contentService.manageVersions(selection.file);
}
});
}

View File

@@ -55,7 +55,6 @@ export class UploadEffects {
this.fileInput.addEventListener('change', event => this.upload(event));
renderer.appendChild(document.body, this.fileInput);
this.folderInput = renderer.createElement('input') as HTMLInputElement;
this.folderInput.id = 'app-upload-folder';
this.folderInput.type = 'file';
@@ -89,15 +88,13 @@ export class UploadEffects {
.subscribe(node => {
if (node && node.id) {
const input = <HTMLInputElement>event.currentTarget;
const files = FileUtils.toFileArray(input.files).map(
file => {
const files = FileUtils.toFileArray(input.files).map(file => {
return new FileModel(file, {
parentId: node.id,
path: (file.webkitRelativePath || '').replace(/\/[^\/]*$/, ''),
nodeType: 'cm:content'
});
}
);
});
this.uploadQueue(files);
event.target.value = '';

View File

@@ -67,16 +67,10 @@ export class ViewerEffects {
.pipe(take(1))
.subscribe(result => {
if (result.selection && result.selection.file) {
const {
id,
nodeId,
isFile
} = result.selection.file.entry;
const { id, nodeId, isFile } = result.selection.file.entry;
if (isFile || nodeId) {
const parentId = result.folder
? result.folder.id
: null;
const parentId = result.folder ? result.folder.id : null;
this.displayPreview(nodeId || id, parentId);
}
}

View File

@@ -57,22 +57,16 @@ export function appReducer(
newState = Object.assign({}, (<SetInitialStateAction>action).payload);
break;
case SET_SELECTED_NODES:
newState = updateSelectedNodes(state, <SetSelectedNodesAction>(
action
));
newState = updateSelectedNodes(state, <SetSelectedNodesAction>action);
break;
case SET_USER_PROFILE:
newState = updateUser(state, <SetUserProfileAction>action);
break;
case SET_LANGUAGE_PICKER:
newState = updateLanguagePicker(state, <SetLanguagePickerAction>(
action
));
newState = updateLanguagePicker(state, <SetLanguagePickerAction>action);
break;
case SET_CURRENT_FOLDER:
newState = updateCurrentFolder(state, <SetCurrentFolderAction>(
action
));
newState = updateCurrentFolder(state, <SetCurrentFolderAction>action);
break;
case SET_CURRENT_URL:
newState = updateCurrentUrl(state, <SetCurrentUrlAction>action);
@@ -81,9 +75,9 @@ export function appReducer(
newState = updateInfoDrawer(state, <ToggleInfoDrawerAction>action);
break;
case TOGGLE_DOCUMENT_DISPLAY_MODE:
newState = updateDocumentDisplayMode(state, <
ToggleDocumentDisplayMode
>action);
newState = updateDocumentDisplayMode(state, <ToggleDocumentDisplayMode>(
action
));
break;
default:
newState = Object.assign({}, state);
@@ -185,9 +179,7 @@ function updateSelectedNodes(
if (nodes.length === 1) {
file = nodes.find(entity => {
// workaround Shared
return entity.entry.isFile || entity.entry.nodeId
? true
: false;
return entity.entry.isFile || entity.entry.nodeId ? true : false;
});
folder = nodes.find(entity => entity.entry.isFolder);
}

View File

@@ -27,17 +27,38 @@ import { createSelector } from '@ngrx/store';
import { AppStore } from '../states/app.state';
export const selectApp = (state: AppStore) => state.app;
export const selectHeaderColor = createSelector(selectApp, state => state.headerColor);
export const selectHeaderColor = createSelector(
selectApp,
state => state.headerColor
);
export const selectAppName = createSelector(selectApp, state => state.appName);
export const selectLogoPath = createSelector(selectApp, state => state.logoPath);
export const selectLogoPath = createSelector(
selectApp,
state => state.logoPath
);
export const appSelection = createSelector(selectApp, state => state.selection);
export const appLanguagePicker = createSelector(selectApp, state => state.languagePicker);
export const appLanguagePicker = createSelector(
selectApp,
state => state.languagePicker
);
export const selectUser = createSelector(selectApp, state => state.user);
export const sharedUrl = createSelector(selectApp, state => state.sharedUrl);
export const appNavigation = createSelector(selectApp, state => state.navigation);
export const currentFolder = createSelector(selectApp, state => state.navigation.currentFolder);
export const infoDrawerOpened = createSelector(selectApp, state => state.infoDrawerOpened);
export const documentDisplayMode = createSelector(selectApp, state => state.documentDisplayMode);
export const appNavigation = createSelector(
selectApp,
state => state.navigation
);
export const currentFolder = createSelector(
selectApp,
state => state.navigation.currentFolder
);
export const infoDrawerOpened = createSelector(
selectApp,
state => state.infoDrawerOpened
);
export const documentDisplayMode = createSelector(
selectApp,
state => state.documentDisplayMode
);
export const ruleContext = createSelector(
appSelection,

View File

@@ -23,7 +23,11 @@
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
import { SelectionState, ProfileState, NavigationState } from '@alfresco/adf-extensions';
import {
SelectionState,
ProfileState,
NavigationState
} from '@alfresco/adf-extensions';
export interface AppState {
appName: string;

View File

@@ -61,7 +61,10 @@ import { NodePermissionService } from '../services/node-permission.service';
import { ContentApiService } from '../services/content-api.service';
import { AppExtensionService } from '../extensions/extension.service';
import { ViewUtilService } from '../components/preview/view-util.service';
import { ExtensionLoaderService, ExtensionService } from '@alfresco/adf-extensions';
import {
ExtensionLoaderService,
ExtensionService
} from '@alfresco/adf-extensions';
@NgModule({
imports: [
@@ -69,18 +72,11 @@ import { ExtensionLoaderService, ExtensionService } from '@alfresco/adf-extensio
HttpClientModule,
RouterTestingModule,
MaterialModule,
StoreModule.forRoot(
{ app: appReducer },
{ initialState: INITIAL_STATE }
),
StoreModule.forRoot({ app: appReducer }, { initialState: INITIAL_STATE }),
EffectsModule.forRoot([])
],
declarations: [TranslatePipeMock],
exports: [
TranslatePipeMock,
RouterTestingModule,
MaterialModule,
],
exports: [TranslatePipeMock, RouterTestingModule, MaterialModule],
providers: [
{ provide: AlfrescoApiService, useClass: AlfrescoApiMock },
{ provide: TranslationService, useClass: TranslationMock },

View File

@@ -33,11 +33,17 @@ export class TranslateServiceMock extends TranslateService {
super(null, null, null, null, null);
}
get(key: string | Array<string>, interpolateParams?: Object): Observable<string | any> {
get(
key: string | Array<string>,
interpolateParams?: Object
): Observable<string | any> {
return of(key);
}
instant(key: string | Array<string>, interpolateParams?: Object): string | any {
instant(
key: string | Array<string>,
interpolateParams?: Object
): string | any {
return key;
}
}

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