[AAE-7242] fix eslint warnings for content services project (#7505)

* fix eslint warnings for content services project

* fix typing issues
This commit is contained in:
Denys Vuika
2022-02-17 15:23:38 +00:00
committed by GitHub
parent bca5a783ab
commit 9f72e30fbc
158 changed files with 2604 additions and 2715 deletions
+3 -2
View File
@@ -24,13 +24,14 @@
"@typescript-eslint/naming-convention": "warn", "@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/consistent-type-assertions": "warn", "@typescript-eslint/consistent-type-assertions": "warn",
"@typescript-eslint/prefer-for-of": "warn", "@typescript-eslint/prefer-for-of": "warn",
"no-underscore-dangle": "warn", "@typescript-eslint/member-ordering": "off",
"no-underscore-dangle": ["error", { "allowAfterThis": true }],
"no-shadow": "warn", "no-shadow": "warn",
"quote-props": "warn", "quote-props": "warn",
"object-shorthand": "warn", "object-shorthand": "warn",
"prefer-const": "warn", "prefer-const": "warn",
"arrow-body-style": "warn", "arrow-body-style": "warn",
"@angular-eslint/no-output-native": "warn", "@angular-eslint/no-output-native": "off",
"space-before-function-paren": "warn", "space-before-function-paren": "warn",
"@angular-eslint/component-selector": [ "@angular-eslint/component-selector": [
@@ -102,7 +102,7 @@ describe('AspectListDialogComponent', () => {
describe('Without passing node id', () => { describe('Without passing node id', () => {
beforeEach(async () => { beforeEach(async () => {
data = <AspectListDialogComponentData> { data = {
title: 'Title', title: 'Title',
description: 'Description that can be longer or shorter', description: 'Description that can be longer or shorter',
overTableMessage: 'Over here', overTableMessage: 'Over here',
@@ -239,7 +239,7 @@ describe('AspectListDialogComponent', () => {
describe('Passing the node id', () => { describe('Passing the node id', () => {
beforeEach(async () => { beforeEach(async () => {
data = <AspectListDialogComponentData> { data = {
title: 'Title', title: 'Title',
description: 'Description that can be longer or shorter', description: 'Description that can be longer or shorter',
overTableMessage: 'Over here', overTableMessage: 'Over here',
@@ -85,9 +85,7 @@ export class AspectListService {
private filterAspectByConfig(visibleAspectList: string[], aspectEntries: AspectEntry[]): AspectEntry[] { private filterAspectByConfig(visibleAspectList: string[], aspectEntries: AspectEntry[]): AspectEntry[] {
let result = aspectEntries ? aspectEntries : []; let result = aspectEntries ? aspectEntries : [];
if (visibleAspectList?.length > 0 && aspectEntries) { if (visibleAspectList?.length > 0 && aspectEntries) {
result = aspectEntries.filter((value) => { result = aspectEntries.filter((value) => visibleAspectList.includes(value?.entry?.id));
return visibleAspectList.includes(value?.entry?.id);
});
} }
return result; return result;
} }
@@ -59,34 +59,34 @@ describe('AuditService', () => {
status: 200, status: 200,
contentType: 'json', contentType: 'json',
responseText: { responseText: {
'list': { list: {
'pagination': { pagination: {
'count': 3, count: 3,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 3, totalItems: 3,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'isEnabled': true, isEnabled: true,
'name': 'Alfresco Tagging Service', name: 'Alfresco Tagging Service',
'id': 'tagging' id: 'tagging'
} }
}, },
{ {
'entry': { entry: {
'isEnabled': true, isEnabled: true,
'name': 'ShareSiteAccess', name: 'ShareSiteAccess',
'id': 'share-site-access' id: 'share-site-access'
} }
}, },
{ {
'entry': { entry: {
'isEnabled': true, isEnabled: true,
'name': 'alfresco-access', name: 'alfresco-access',
'id': 'alfresco-access' id: 'alfresco-access'
} }
} }
] ]
@@ -106,10 +106,10 @@ describe('AuditService', () => {
status: 200, status: 200,
contentType: 'json', contentType: 'json',
responseText: { responseText: {
'entry': { entry: {
'id': 'alfresco-access', id: 'alfresco-access',
'name': 'alfresco-access', name: 'alfresco-access',
'isEnabled': true isEnabled: true
} }
} }
}); });
@@ -125,49 +125,49 @@ describe('AuditService', () => {
status: 200, status: 200,
contentType: 'json', contentType: 'json',
responseText: { responseText: {
'list': { list: {
'pagination': { pagination: {
'count': 3, count: 3,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 3, totalItems: 3,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'id': '1', id: '1',
'auditApplicationId': 'alfresco-access', auditApplicationId: 'alfresco-access',
'createdByUser': { createdByUser: {
'displayName': 'admin', displayName: 'admin',
'id': 'admin' id: 'admin'
}, },
'createdAt': '2020-08-11T13:11:59.141Z', createdAt: '2020-08-11T13:11:59.141Z',
'values': {} values: {}
} }
}, },
{ {
'entry': { entry: {
'id': '2', id: '2',
'auditApplicationId': 'alfresco-access', auditApplicationId: 'alfresco-access',
'createdByUser': { createdByUser: {
'displayName': 'admin', displayName: 'admin',
'id': 'admin' id: 'admin'
}, },
'createdAt': '2020-08-11T13:11:59.141Z', createdAt: '2020-08-11T13:11:59.141Z',
'values': {} values: {}
} }
}, },
{ {
'entry': { entry: {
'id': '3', id: '3',
'auditApplicationId': 'alfresco-access', auditApplicationId: 'alfresco-access',
'createdByUser': { createdByUser: {
'displayName': 'admin', displayName: 'admin',
'id': 'admin' id: 'admin'
}, },
'createdAt': '2020-08-11T13:11:59.141Z', createdAt: '2020-08-11T13:11:59.141Z',
'values': {} values: {}
} }
} }
] ]
@@ -187,15 +187,15 @@ describe('AuditService', () => {
status: 200, status: 200,
contentType: 'json', contentType: 'json',
responseText: { responseText: {
'entry': { entry: {
'id': '1', id: '1',
'auditApplicationId': 'alfresco-access', auditApplicationId: 'alfresco-access',
'createdByUser': { createdByUser: {
'displayName': 'admin', displayName: 'admin',
'id': 'admin' id: 'admin'
}, },
'createdAt': '2020-08-11T13:11:59.148Z', createdAt: '2020-08-11T13:11:59.148Z',
'values': {} values: {}
} }
} }
}); });
@@ -56,7 +56,7 @@ export class AuditService {
getAuditApp(auditApplicationId: string, opts?: any): Observable<AuditAppEntry> { getAuditApp(auditApplicationId: string, opts?: any): Observable<AuditAppEntry> {
const defaultOptions = { const defaultOptions = {
auditApplicationId: auditApplicationId auditApplicationId
}; };
const queryOptions = Object.assign({}, defaultOptions, opts); const queryOptions = Object.assign({}, defaultOptions, opts);
return from(this.auditApi.getAuditApp(queryOptions)) return from(this.auditApi.getAuditApp(queryOptions))
@@ -97,7 +97,7 @@ export class AuditService {
getAuditEntriesForNode(nodeId: string, opts?: any): Observable<AuditEntryPaging> { getAuditEntriesForNode(nodeId: string, opts?: any): Observable<AuditEntryPaging> {
const defaultOptions = { const defaultOptions = {
nodeId: nodeId nodeId
}; };
const queryOptions = Object.assign({}, defaultOptions, opts); const queryOptions = Object.assign({}, defaultOptions, opts);
return from(this.auditApi.listAuditEntriesForNode(queryOptions)) return from(this.auditApi.listAuditEntriesForNode(queryOptions))
@@ -17,7 +17,7 @@
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PathElementEntity, Node } from '@alfresco/js-api'; import { Node } from '@alfresco/js-api';
import { setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { fakeNodeWithCreatePermission } from '../mock'; import { fakeNodeWithCreatePermission } from '../mock';
import { DocumentListComponent, DocumentListService } from '../document-list'; import { DocumentListComponent, DocumentListService } from '../document-list';
@@ -72,7 +72,7 @@ describe('Breadcrumb', () => {
}); });
it('should emit navigation event', (done) => { it('should emit navigation event', (done) => {
const node = <PathElementEntity> { id: '-id-', name: 'name' }; const node = { id: '-id-', name: 'name' };
component.navigate.subscribe((val) => { component.navigate.subscribe((val) => {
expect(val).toBe(node); expect(val).toBe(node);
done(); done();
@@ -112,8 +112,7 @@ describe('Breadcrumb', () => {
}); });
it('should update document list on click', () => { it('should update document list on click', () => {
const node = { id: '-id-', name: 'name' };
const node = <PathElementEntity> { id: '-id-', name: 'name' };
component.target = documentListComponent; component.target = documentListComponent;
component.onRoutePathClick(node, null); component.onRoutePathClick(node, null);
@@ -37,7 +37,7 @@ import { takeUntil } from 'rxjs/operators';
templateUrl: './breadcrumb.component.html', templateUrl: './breadcrumb.component.html',
styleUrls: ['./breadcrumb.component.scss'], styleUrls: ['./breadcrumb.component.scss'],
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,
host: { 'class': 'adf-breadcrumb' } host: { class: 'adf-breadcrumb' }
}) })
export class BreadcrumbComponent implements OnInit, OnChanges, OnDestroy { export class BreadcrumbComponent implements OnInit, OnChanges, OnDestroy {
@@ -143,13 +143,13 @@ export class BreadcrumbComponent implements OnInit, OnChanges, OnDestroy {
parseRoute(node: Node): PathElementEntity[] { parseRoute(node: Node): PathElementEntity[] {
if (node && node.path) { if (node && node.path) {
const route = <PathElementEntity[]> (node.path.elements || []).slice(); const route = (node.path.elements || []).slice();
route.push(<PathElementEntity> { route.push({
id: node.id, id: node.id,
name: node.name, name: node.name,
node: node node
}); } as PathElementEntity);
const rootPos = this.getElementPosition(route, this.rootId); const rootPos = this.getElementPosition(route, this.rootId);
if (rootPos > 0) { if (rootPos > 0) {
@@ -31,7 +31,7 @@ describe('DropdownBreadcrumb', () => {
let component: DropdownBreadcrumbComponent; let component: DropdownBreadcrumbComponent;
let fixture: ComponentFixture<DropdownBreadcrumbComponent>; let fixture: ComponentFixture<DropdownBreadcrumbComponent>;
let documentList: DocumentListComponent; let documentList: DocumentListComponent;
let documentListService: DocumentListService = jasmine.createSpyObj({ 'loadFolderByNodeId': of(''), 'isCustomSourceService': false }); let documentListService: DocumentListService = jasmine.createSpyObj({ loadFolderByNodeId: of(''), isCustomSourceService: false });
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -53,22 +53,22 @@ describe('DropdownBreadcrumb', () => {
fixture.destroy(); fixture.destroy();
}); });
function openSelect() { const openSelect = () => {
const folderIcon = fixture.debugElement.nativeElement.querySelector('[data-automation-id="dropdown-breadcrumb-trigger"]'); const folderIcon = fixture.debugElement.nativeElement.querySelector('[data-automation-id="dropdown-breadcrumb-trigger"]');
folderIcon.click(); folderIcon.click();
fixture.detectChanges(); fixture.detectChanges();
} };
function triggerComponentChange(fakeNodeData) { const triggerComponentChange = (fakeNodeData) => {
component.folderNode = fakeNodeData; component.folderNode = fakeNodeData;
component.ngOnChanges(); component.ngOnChanges();
fixture.detectChanges(); fixture.detectChanges();
} };
function clickOnTheFirstOption() { const clickOnTheFirstOption = () => {
const option: any = document.querySelector('[id^="mat-option"]'); const option: any = document.querySelector('[id^="mat-option"]');
option.click(); option.click();
} };
it('should display only the current folder name if there is no previous folders', (done) => { it('should display only the current folder name if there is no previous folders', (done) => {
const fakeNodeWithCreatePermissionInstance = JSON.parse(JSON.stringify(fakeNodeWithCreatePermission)); const fakeNodeWithCreatePermissionInstance = JSON.parse(JSON.stringify(fakeNodeWithCreatePermission));
@@ -25,7 +25,7 @@ import { BreadcrumbComponent } from './breadcrumb.component';
templateUrl: './dropdown-breadcrumb.component.html', templateUrl: './dropdown-breadcrumb.component.html',
styleUrls: ['./dropdown-breadcrumb.component.scss'], styleUrls: ['./dropdown-breadcrumb.component.scss'],
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,
host: { 'class': 'adf-dropdown-breadcrumb' } host: { class: 'adf-dropdown-breadcrumb' }
}) })
export class DropdownBreadcrumbComponent extends BreadcrumbComponent implements OnChanges { export class DropdownBreadcrumbComponent extends BreadcrumbComponent implements OnChanges {
@@ -48,14 +48,14 @@ describe('ContentMetadataCardComponent', () => {
fixture = TestBed.createComponent(ContentMetadataCardComponent); fixture = TestBed.createComponent(ContentMetadataCardComponent);
contentMetadataService = TestBed.inject(ContentMetadataService); contentMetadataService = TestBed.inject(ContentMetadataService);
component = fixture.componentInstance; component = fixture.componentInstance;
node = <Node> { node = {
aspectNames: [], aspectNames: [],
nodeType: '', nodeType: '',
content: {}, content: {},
properties: {}, properties: {},
createdByUser: {}, createdByUser: {},
modifiedByUser: {} modifiedByUser: {}
}; } as Node;
component.node = node; component.node = node;
component.preset = preset; component.preset = preset;
@@ -25,7 +25,7 @@ import { PresetConfig } from '../../interfaces/content-metadata.interfaces';
templateUrl: './content-metadata-card.component.html', templateUrl: './content-metadata-card.component.html',
styleUrls: ['./content-metadata-card.component.scss'], styleUrls: ['./content-metadata-card.component.scss'],
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,
host: { 'class': 'adf-content-metadata-card' } host: { class: 'adf-content-metadata-card' }
}) })
export class ContentMetadataCardComponent implements OnChanges { export class ContentMetadataCardComponent implements OnChanges {
@@ -55,7 +55,7 @@ describe('ContentMetadataComponent', () => {
updateService = TestBed.inject(CardViewUpdateService); updateService = TestBed.inject(CardViewUpdateService);
nodesApiService = TestBed.inject(NodesApiService); nodesApiService = TestBed.inject(NodesApiService);
node = <Node> { node = {
id: 'node-id', id: 'node-id',
aspectNames: [], aspectNames: [],
nodeType: 'cm:node', nodeType: 'cm:node',
@@ -63,15 +63,15 @@ describe('ContentMetadataComponent', () => {
properties: {}, properties: {},
createdByUser: {}, createdByUser: {},
modifiedByUser: {} modifiedByUser: {}
}; } as Node;
folderNode = <Node> { folderNode = {
id: 'folder-id', id: 'folder-id',
aspectNames: [], aspectNames: [],
nodeType: '', nodeType: '',
createdByUser: {}, createdByUser: {},
modifiedByUser: {} modifiedByUser: {}
}; } as Node;
component.node = node; component.node = node;
component.preset = preset; component.preset = preset;
@@ -116,7 +116,7 @@ describe('ContentMetadataComponent', () => {
describe('Saving', () => { describe('Saving', () => {
it('itemUpdate', fakeAsync(() => { it('itemUpdate', fakeAsync(() => {
spyOn(component, 'updateChanges').and.callThrough(); spyOn(component, 'updateChanges').and.callThrough();
const property = <CardViewBaseItemModel> { key: 'properties.property-key', value: 'original-value' }; const property = { key: 'properties.property-key', value: 'original-value' } as CardViewBaseItemModel;
updateService.update(property, 'updated-value'); updateService.update(property, 'updated-value');
tick(600); tick(600);
@@ -126,7 +126,7 @@ describe('ContentMetadataComponent', () => {
})); }));
it('nodeAspectUpdate', fakeAsync(() => { it('nodeAspectUpdate', fakeAsync(() => {
const fakeNode: MinimalNode = <MinimalNode> { id: 'fake-minimal-node', aspectNames: ['ft:a', 'ft:b', 'ft:c'], name: 'fake-node'}; const fakeNode = { id: 'fake-minimal-node', aspectNames: ['ft:a', 'ft:b', 'ft:c'], name: 'fake-node'} as MinimalNode;
spyOn(contentMetadataService, 'getGroupedProperties').and.stub(); spyOn(contentMetadataService, 'getGroupedProperties').and.stub();
spyOn(contentMetadataService, 'getBasicProperties').and.stub(); spyOn(contentMetadataService, 'getBasicProperties').and.stub();
updateService.updateNodeAspect(fakeNode); updateService.updateNodeAspect(fakeNode);
@@ -138,7 +138,7 @@ describe('ContentMetadataComponent', () => {
it('should save changedProperties on save click', fakeAsync(async () => { it('should save changedProperties on save click', fakeAsync(async () => {
component.editable = true; component.editable = true;
const property = <CardViewBaseItemModel> { key: 'properties.property-key', value: 'original-value' }; const property = { key: 'properties.property-key', value: 'original-value' } as CardViewBaseItemModel;
const expectedNode = { ...node, name: 'some-modified-value' }; const expectedNode = { ...node, name: 'some-modified-value' };
spyOn(nodesApiService, 'updateNode').and.returnValue(of(expectedNode)); spyOn(nodesApiService, 'updateNode').and.returnValue(of(expectedNode));
@@ -158,7 +158,7 @@ describe('ContentMetadataComponent', () => {
it('should throw error on unsuccessful save', fakeAsync((done) => { it('should throw error on unsuccessful save', fakeAsync((done) => {
const logService: LogService = TestBed.inject(LogService); const logService: LogService = TestBed.inject(LogService);
component.editable = true; component.editable = true;
const property = <CardViewBaseItemModel> { key: 'properties.property-key', value: 'original-value' }; const property = { key: 'properties.property-key', value: 'original-value' } as CardViewBaseItemModel;
updateService.update(property, 'updated-value'); updateService.update(property, 'updated-value');
tick(600); tick(600);
@@ -182,7 +182,7 @@ describe('ContentMetadataComponent', () => {
it('should open the confirm dialog when content type is changed', fakeAsync(() => { it('should open the confirm dialog when content type is changed', fakeAsync(() => {
component.editable = true; component.editable = true;
const property = <CardViewBaseItemModel> { key: 'nodeType', value: 'ft:sbiruli' }; const property = { key: 'nodeType', value: 'ft:sbiruli' } as CardViewBaseItemModel;
const expectedNode = { ...node, nodeType: 'ft:sbiruli' }; const expectedNode = { ...node, nodeType: 'ft:sbiruli' };
spyOn(contentMetadataService, 'openConfirmDialog').and.returnValue(of(true)); spyOn(contentMetadataService, 'openConfirmDialog').and.returnValue(of(true));
spyOn(nodesApiService, 'updateNode').and.returnValue(of(expectedNode)); spyOn(nodesApiService, 'updateNode').and.returnValue(of(expectedNode));
@@ -203,7 +203,7 @@ describe('ContentMetadataComponent', () => {
it('should retrigger the load of the properties when the content type has changed', fakeAsync(() => { it('should retrigger the load of the properties when the content type has changed', fakeAsync(() => {
component.editable = true; component.editable = true;
const property = <CardViewBaseItemModel> { key: 'nodeType', value: 'ft:sbiruli' }; const property = { key: 'nodeType', value: 'ft:sbiruli' } as CardViewBaseItemModel;
const expectedNode = Object.assign({}, node, { nodeType: 'ft:sbiruli' }); const expectedNode = Object.assign({}, node, { nodeType: 'ft:sbiruli' });
spyOn(contentMetadataService, 'openConfirmDialog').and.returnValue(of(true)); spyOn(contentMetadataService, 'openConfirmDialog').and.returnValue(of(true));
spyOn(updateService, 'updateNodeAspect'); spyOn(updateService, 'updateNodeAspect');
@@ -512,6 +512,5 @@ describe('ContentMetadataComponent', () => {
}); });
}); });
function queryDom(fixture: ComponentFixture<ContentMetadataComponent>, properties: string = 'properties') { const queryDom = (fixture: ComponentFixture<ContentMetadataComponent>, properties: string = 'properties') =>
return fixture.debugElement.query(By.css(`[data-automation-id="adf-metadata-group-${properties}"]`)); fixture.debugElement.query(By.css(`[data-automation-id="adf-metadata-group-${properties}"]`));
}
@@ -33,17 +33,16 @@ import { ContentMetadataService } from '../../services/content-metadata.service'
import { CardViewGroup, PresetConfig } from '../../interfaces/content-metadata.interfaces'; import { CardViewGroup, PresetConfig } from '../../interfaces/content-metadata.interfaces';
import { takeUntil, debounceTime, catchError, map } from 'rxjs/operators'; import { takeUntil, debounceTime, catchError, map } from 'rxjs/operators';
const DEFAULT_SEPARATOR = ', ';
@Component({ @Component({
selector: 'adf-content-metadata', selector: 'adf-content-metadata',
templateUrl: './content-metadata.component.html', templateUrl: './content-metadata.component.html',
styleUrls: ['./content-metadata.component.scss'], styleUrls: ['./content-metadata.component.scss'],
host: { 'class': 'adf-content-metadata' }, host: { class: 'adf-content-metadata' },
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None
}) })
export class ContentMetadataComponent implements OnChanges, OnInit, OnDestroy { export class ContentMetadataComponent implements OnChanges, OnInit, OnDestroy {
static DEFAULT_SEPARATOR = ', ';
protected onDestroy$ = new Subject<boolean>(); protected onDestroy$ = new Subject<boolean>();
/** (required) The node entity to fetch metadata about */ /** (required) The node entity to fetch metadata about */
@@ -106,7 +105,7 @@ export class ContentMetadataComponent implements OnChanges, OnInit, OnDestroy {
private appConfig: AppConfigService private appConfig: AppConfigService
) { ) {
this.copyToClipboardAction = this.appConfig.get<boolean>('content-metadata.copy-to-clipboard-action'); this.copyToClipboardAction = this.appConfig.get<boolean>('content-metadata.copy-to-clipboard-action');
this.multiValueSeparator = this.appConfig.get<string>('content-metadata.multi-value-pipe-separator') || ContentMetadataComponent.DEFAULT_SEPARATOR; this.multiValueSeparator = this.appConfig.get<string>('content-metadata.multi-value-pipe-separator') || DEFAULT_SEPARATOR;
this.useChipsForMultiValueProperty = this.appConfig.get<boolean>('content-metadata.multi-value-chips'); this.useChipsForMultiValueProperty = this.appConfig.get<boolean>('content-metadata.multi-value-chips');
} }
@@ -233,9 +232,7 @@ export class ContentMetadataComponent implements OnChanges, OnInit, OnDestroy {
} }
showGroup(group: CardViewGroup): boolean { showGroup(group: CardViewGroup): boolean {
const properties = group.properties.filter((property) => { const properties = group.properties.filter((property) => !this.isEmpty(property.displayValue));
return !this.isEmpty(property.displayValue);
});
return properties.length > 0; return properties.length > 0;
} }
@@ -17,57 +17,57 @@
export const mockGroupProperties = [ export const mockGroupProperties = [
{ {
'title': 'EXIF', title: 'EXIF',
'properties': [ properties: [
{ {
'label': 'Image Width', label: 'Image Width',
'value': 363, value: 363,
'key': 'properties.exif:pixelXDimension', key: 'properties.exif:pixelXDimension',
'default': null, default: null,
'editable': true, editable: true,
'clickable': false, clickable: false,
'icon': '', icon: '',
'data': null, data: null,
'type': 'int', type: 'int',
'multiline': false, multiline: false,
'pipes': [], pipes: [],
'clickCallBack': null, clickCallBack: null,
'displayValue': 400 displayValue: 400
}, },
{ {
'label': 'Image Height', label: 'Image Height',
'value': 400, value: 400,
'key': 'properties.exif:pixelYDimension', key: 'properties.exif:pixelYDimension',
'default': null, default: null,
'editable': true, editable: true,
'clickable': false, clickable: false,
'icon': '', icon: '',
'data': null, data: null,
'type': 'int', type: 'int',
'multiline': false, multiline: false,
'pipes': [], pipes: [],
'clickCallBack': null, clickCallBack: null,
'displayValue': 400 displayValue: 400
} }
] ]
}, },
{ {
'title': 'CUSTOM', title: 'CUSTOM',
'properties': [ properties: [
{ {
'label': 'Height', label: 'Height',
'value': 400, value: 400,
'key': 'properties.custom:abc', key: 'properties.custom:abc',
'default': null, default: null,
'editable': true, editable: true,
'clickable': false, clickable: false,
'icon': '', icon: '',
'data': null, data: null,
'type': 'int', type: 'int',
'multiline': false, multiline: false,
'pipes': [], pipes: [],
'clickCallBack': null, clickCallBack: null,
'displayValue': 400 displayValue: 400
} }
] ]
} }
@@ -22,9 +22,7 @@ describe('AspectOrientedConfigService', () => {
let configService: AspectOrientedConfigService; let configService: AspectOrientedConfigService;
function createConfigService(configObj: AspectOrientedConfig) { const createConfigService = (configObj: AspectOrientedConfig) => new AspectOrientedConfigService(configObj);
return new AspectOrientedConfigService(configObj);
}
describe('reorganiseByConfig', () => { describe('reorganiseByConfig', () => {
@@ -34,10 +32,10 @@ describe('AspectOrientedConfigService', () => {
expectations: OrganisedPropertyGroup[]; expectations: OrganisedPropertyGroup[];
} }
const property1 = <Property> { name: 'property1' }; const property1 = { name: 'property1' } as Property;
const property2 = <Property> { name: 'property2' }; const property2 = { name: 'property2' } as Property;
const property3 = <Property> { name: 'property3' }; const property3 = { name: 'property3' } as Property;
const property4 = <Property> { name: 'property4' }; const property4 = { name: 'property4' } as Property;
const propertyGroups: PropertyGroupContainer = { const propertyGroups: PropertyGroupContainer = {
berseria: { title: 'Berseria', description: '', name: 'berseria', properties: { property1, property2 } }, berseria: { title: 'Berseria', description: '', name: 'berseria', properties: { property1, property2 } },
@@ -53,7 +51,7 @@ describe('AspectOrientedConfigService', () => {
{ {
name: 'One property from One group', name: 'One property from One group',
config: { config: {
'berseria': [ 'property1' ] berseria: [ 'property1' ]
}, },
expectations: [{ expectations: [{
title: 'Berseria', title: 'Berseria',
@@ -63,7 +61,7 @@ describe('AspectOrientedConfigService', () => {
{ {
name: 'More properties from One group', name: 'More properties from One group',
config: { config: {
'berseria': [ 'property1', 'property2' ] berseria: [ 'property1', 'property2' ]
}, },
expectations: [{ expectations: [{
title: 'Berseria', title: 'Berseria',
@@ -73,8 +71,8 @@ describe('AspectOrientedConfigService', () => {
{ {
name: 'One-one properties from More group', name: 'One-one properties from More group',
config: { config: {
'berseria': [ 'property1' ], berseria: [ 'property1' ],
'zestiria': [ 'property3' ] zestiria: [ 'property3' ]
}, },
expectations: [ expectations: [
{ {
@@ -90,8 +88,8 @@ describe('AspectOrientedConfigService', () => {
{ {
name: 'More properties from More groups', name: 'More properties from More groups',
config: { config: {
'zestiria': [ 'property4', 'property3' ], zestiria: [ 'property4', 'property3' ],
'berseria': [ 'property2', 'property1' ] berseria: [ 'property2', 'property1' ]
}, },
expectations: [ expectations: [
{ {
@@ -107,8 +105,8 @@ describe('AspectOrientedConfigService', () => {
{ {
name: 'Wildcard', name: 'Wildcard',
config: { config: {
'berseria': '*', berseria: '*',
'zestiria': [ 'property4' ] zestiria: [ 'property4' ]
}, },
expectations: [ expectations: [
{ {
@@ -124,9 +122,9 @@ describe('AspectOrientedConfigService', () => {
{ {
name: 'Not existing group', name: 'Not existing group',
config: { config: {
'berseria': '*', berseria: '*',
'not-existing-group': '*', 'not-existing-group': '*',
'zestiria': [ 'property4' ] zestiria: [ 'property4' ]
}, },
expectations: [ expectations: [
{ {
@@ -142,8 +140,8 @@ describe('AspectOrientedConfigService', () => {
{ {
name: 'Not existing property', name: 'Not existing property',
config: { config: {
'berseria': [ 'not-existing-property' ], berseria: [ 'not-existing-property' ],
'zestiria': [ 'property4' ] zestiria: [ 'property4' ]
}, },
expectations: [ expectations: [
{ {
@@ -177,10 +175,10 @@ describe('AspectOrientedConfigService', () => {
}); });
describe('appendAllPreset', () => { describe('appendAllPreset', () => {
const property1 = <Property> { name: 'property1' }; const property1 = { name: 'property1' } as Property;
const property2 = <Property> { name: 'property2' }; const property2 = { name: 'property2' } as Property;
const property3 = <Property> { name: 'property3' }; const property3 = { name: 'property3' } as Property;
const property4 = <Property> { name: 'property4' }; const property4 = { name: 'property4' } as Property;
const propertyGroups: PropertyGroupContainer = { const propertyGroups: PropertyGroupContainer = {
berseria: { title: 'Berseria', description: '', name: 'berseria', properties: { property1, property2 } }, berseria: { title: 'Berseria', description: '', name: 'berseria', properties: { property1, property2 } },
@@ -92,9 +92,7 @@ export class AspectOrientedConfigService implements ContentMetadataConfig {
public filterExcludedPreset(propertyGroups: OrganisedPropertyGroup[]): OrganisedPropertyGroup[] { public filterExcludedPreset(propertyGroups: OrganisedPropertyGroup[]): OrganisedPropertyGroup[] {
if (this.config.exclude) { if (this.config.exclude) {
return propertyGroups.filter((preset) => { return propertyGroups.filter((preset) => !this.config.exclude.includes(preset.name));
return !this.config.exclude.includes(preset.name);
});
} }
return propertyGroups; return propertyGroups;
} }
@@ -114,7 +112,7 @@ export class AspectOrientedConfigService implements ContentMetadataConfig {
if (aspectProperties === '*') { if (aspectProperties === '*') {
properties = getProperty(propertyGroups, aspectName, aspectProperties); properties = getProperty(propertyGroups, aspectName, aspectProperties);
} else { } else {
properties = (<string[]> aspectProperties) properties = aspectProperties
.map((propertyName) => getProperty(propertyGroups, aspectName, propertyName)) .map((propertyName) => getProperty(propertyGroups, aspectName, propertyName))
.filter((props) => props !== undefined); .filter((props) => props !== undefined);
} }
@@ -87,13 +87,13 @@ describe('ContentMetadataConfigFactory', () => {
describe('set', () => { describe('set', () => {
function setConfig(presetName: string, presetConfig: any) { const setConfig = (presetName: string, presetConfig: any) => {
appConfig.config['content-metadata'] = { appConfig.config['content-metadata'] = {
presets: { presets: {
[presetName]: presetConfig [presetName]: presetConfig
} }
}; };
} };
it('should get back the IndifferentConfigService preset if the preset config is indifferent', () => { it('should get back the IndifferentConfigService preset if the preset config is indifferent', () => {
setConfig('default', '*'); setConfig('default', '*');
@@ -20,21 +20,15 @@ import { AppConfigService, LogService } from '@alfresco/adf-core';
import { AspectOrientedConfigService } from './aspect-oriented-config.service'; import { AspectOrientedConfigService } from './aspect-oriented-config.service';
import { IndifferentConfigService } from './indifferent-config.service'; import { IndifferentConfigService } from './indifferent-config.service';
import { LayoutOrientedConfigService } from './layout-oriented-config.service'; import { LayoutOrientedConfigService } from './layout-oriented-config.service';
import { import { PresetConfig, ContentMetadataConfig } from '../../interfaces/content-metadata.interfaces';
PresetConfig,
ContentMetadataConfig, const INDIFFERENT_PRESET = '*';
AspectOrientedConfig, const DEFAULT_PRESET_NAME = 'default';
LayoutOrientedConfig
} from '../../interfaces/content-metadata.interfaces';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class ContentMetadataConfigFactory { export class ContentMetadataConfigFactory {
static readonly INDIFFERENT_PRESET = '*';
static readonly DEFAULT_PRESET_NAME = 'default';
constructor(private appConfigService: AppConfigService, private logService: LogService) {} constructor(private appConfigService: AppConfigService, private logService: LogService) {}
public get(presetName: string = 'default'): ContentMetadataConfig { public get(presetName: string = 'default'): ContentMetadataConfig {
@@ -42,10 +36,10 @@ export class ContentMetadataConfigFactory {
try { try {
presetConfig = this.appConfigService.config['content-metadata'].presets[presetName]; presetConfig = this.appConfigService.config['content-metadata'].presets[presetName];
} catch { } catch {
if (presetName !== ContentMetadataConfigFactory.DEFAULT_PRESET_NAME) { if (presetName !== DEFAULT_PRESET_NAME) {
this.logService.error(`No content-metadata preset for: ${presetName}`); this.logService.error(`No content-metadata preset for: ${presetName}`);
} }
presetConfig = ContentMetadataConfigFactory.INDIFFERENT_PRESET; presetConfig = INDIFFERENT_PRESET;
} }
return this.createConfig(presetConfig); return this.createConfig(presetConfig);
@@ -55,9 +49,9 @@ export class ContentMetadataConfigFactory {
let config: ContentMetadataConfig; let config: ContentMetadataConfig;
if (this.isLayoutOrientedPreset(presetConfig)) { if (this.isLayoutOrientedPreset(presetConfig)) {
config = new LayoutOrientedConfigService(<LayoutOrientedConfig> presetConfig); config = new LayoutOrientedConfigService(presetConfig);
} else if (this.isAspectOrientedPreset(presetConfig)) { } else if (this.isAspectOrientedPreset(presetConfig)) {
config = new AspectOrientedConfigService(<AspectOrientedConfig> presetConfig); config = new AspectOrientedConfigService(presetConfig);
} else { } else {
config = new IndifferentConfigService(); config = new IndifferentConfigService();
} }
@@ -27,9 +27,7 @@ describe('LayoutOrientedConfigService', () => {
let configService: LayoutOrientedConfigService; let configService: LayoutOrientedConfigService;
function createConfigService(configObj: LayoutOrientedConfig) { const createConfigService = (configObj: LayoutOrientedConfig) => new LayoutOrientedConfigService(configObj);
return new LayoutOrientedConfigService(configObj);
}
describe('isGroupAllowed', () => { describe('isGroupAllowed', () => {
@@ -102,12 +100,12 @@ describe('LayoutOrientedConfigService', () => {
expectations: OrganisedPropertyGroup[]; expectations: OrganisedPropertyGroup[];
} }
const property1 = <Property> { name: 'property1' }; const property1 = { name: 'property1' } as Property;
const property2 = <Property> { name: 'property2' }; const property2 = { name: 'property2' } as Property;
const property3 = <Property> { name: 'property3' }; const property3 = { name: 'property3' } as Property;
const property4 = <Property> { name: 'property4' }; const property4 = { name: 'property4' } as Property;
const property5 = <Property> { name: 'property5' }; const property5 = { name: 'property5' } as Property;
const property6 = <Property> { name: 'property6' }; const property6 = { name: 'property6' } as Property;
const propertyGroups: PropertyGroupContainer = { const propertyGroups: PropertyGroupContainer = {
berseria: { title: 'Berseria', description: '', name: 'berseria', properties: { property1, property2 } }, berseria: { title: 'Berseria', description: '', name: 'berseria', properties: { property1, property2 } },
@@ -282,8 +280,8 @@ describe('LayoutOrientedConfigService', () => {
title: 'First group', title: 'First group',
items: [ items: [
{ aspect: 'zestiria', properties: 'property3' }, { aspect: 'zestiria', properties: 'property3' },
{ type: 'berseria', properties: ['property2', <any> { title: 'Custom title', name: 'property1' }] }, { type: 'berseria', properties: ['property2', { title: 'Custom title', name: 'property1' } as any] },
{ type: 'otherTales', properties: [<any> { title: 'Custom title', name: 'property5' }] } { type: 'otherTales', properties: [{ title: 'Custom title', name: 'property5' } as any] }
] ]
} }
], ],
@@ -293,8 +291,8 @@ describe('LayoutOrientedConfigService', () => {
properties: [ properties: [
property3, property3,
property2, property2,
<Property> { name: 'property1', title: 'Custom title', editable: true }, { name: 'property1', title: 'Custom title', editable: true } as Property,
<Property> { name: 'property5', title: 'Custom title', editable: true } { name: 'property5', title: 'Custom title', editable: true } as Property
] ]
} }
] ]
@@ -83,9 +83,7 @@ export class LayoutOrientedConfigService implements ContentMetadataConfig {
excludedConfig = [excludedConfig]; excludedConfig = [excludedConfig];
} }
return propertyGroups.filter((props) => { return propertyGroups.filter((props) => !excludedConfig.includes(props.name));
return !excludedConfig.includes(props.name);
});
} }
public isIncludeAllEnabled() { public isIncludeAllEnabled() {
@@ -116,13 +114,11 @@ export class LayoutOrientedConfigService implements ContentMetadataConfig {
private flattenItems(items) { private flattenItems(items) {
return items.reduce((accumulator, item) => { return items.reduce((accumulator, item) => {
const properties = Array.isArray(item.properties) ? item.properties : [item.properties]; const properties = Array.isArray(item.properties) ? item.properties : [item.properties];
const flattenedProperties = properties.map((property) => { const flattenedProperties = properties.map((property) => ({
return {
groupName: item.aspect || item.type, groupName: item.aspect || item.type,
property, property,
editable: item.editable editable: item.editable
}; }));
});
return accumulator.concat(flattenedProperties); return accumulator.concat(flattenedProperties);
}, []); }, []);
@@ -21,15 +21,10 @@ const emptyGroup = {
properties: {} properties: {}
}; };
function convertObjectToArray(object: any): Property[] { const convertObjectToArray = (object: any): Property[] => Object.keys(object).map((key) => object[key]);
return Object.keys(object).map((key) => object[key]); export const getGroup = (propertyGroups: PropertyGroupContainer, groupName: string): PropertyGroup | undefined => propertyGroups[groupName];
}
export function getGroup(propertyGroups: PropertyGroupContainer, groupName: string): PropertyGroup | undefined { export const getProperty = (propertyGroups: PropertyGroupContainer, groupName: string, propertyName: string): Property | Property[] | undefined => {
return propertyGroups[groupName];
}
export function getProperty(propertyGroups: PropertyGroupContainer, groupName: string, propertyName: string): Property | Property[] | undefined {
const groupDefinition = getGroup(propertyGroups, groupName) || emptyGroup; const groupDefinition = getGroup(propertyGroups, groupName) || emptyGroup;
let propertyDefinitions; let propertyDefinitions;
@@ -40,4 +35,4 @@ export function getProperty(propertyGroups: PropertyGroupContainer, groupName: s
} }
return propertyDefinitions; return propertyDefinitions;
} };
@@ -57,13 +57,13 @@ describe('ContentMetaDataService', () => {
] ]
}); });
function setConfig(presetName, presetConfig) { const setConfig = (presetName, presetConfig) => {
appConfig.config['content-metadata'] = { appConfig.config['content-metadata'] = {
presets: { presets: {
[presetName]: presetConfig [presetName]: presetConfig
} }
}; };
} };
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(ContentMetadataService); service = TestBed.inject(ContentMetadataService);
@@ -74,14 +74,14 @@ describe('ContentMetaDataService', () => {
}); });
it('should return all the properties of the node', () => { it('should return all the properties of the node', () => {
const fakeNode: Node = <Node> { const fakeNode: Node = {
name: 'Node', name: 'Node',
id: 'fake-id', id: 'fake-id',
isFile: true, isFile: true,
aspectNames: ['exif:exif'], aspectNames: ['exif:exif'],
createdByUser: {displayName: 'test-user'}, createdByUser: {displayName: 'test-user'},
modifiedByUser: {displayName: 'test-user-modified'} modifiedByUser: {displayName: 'test-user-modified'}
}; } as Node;
service.getBasicProperties(fakeNode).subscribe( service.getBasicProperties(fakeNode).subscribe(
(res) => { (res) => {
@@ -94,7 +94,7 @@ describe('ContentMetaDataService', () => {
}); });
it('should return the content type property', () => { it('should return the content type property', () => {
const fakeNode: Node = <Node> { const fakeNode: Node = {
name: 'Node', name: 'Node',
id: 'fake-id', id: 'fake-id',
isFile: true, isFile: true,
@@ -103,7 +103,7 @@ describe('ContentMetaDataService', () => {
createdByUser: {displayName: 'test-user'}, createdByUser: {displayName: 'test-user'},
modifiedByUser: {displayName: 'test-user-modified'}, modifiedByUser: {displayName: 'test-user-modified'},
properties: [] properties: []
}; } as Node;
spyOn(contentPropertyService, 'getContentTypeCardItem').and.returnValue(of({ label: 'hello i am a weird content type'} as any)); spyOn(contentPropertyService, 'getContentTypeCardItem').and.returnValue(of({ label: 'hello i am a weird content type'} as any));
service.getContentTypeProperty(fakeNode).subscribe( service.getContentTypeProperty(fakeNode).subscribe(
@@ -128,7 +128,7 @@ describe('ContentMetaDataService', () => {
describe('AspectOriented preset', () => { describe('AspectOriented preset', () => {
it('should return response with exif property', (done) => { it('should return response with exif property', (done) => {
const fakeNode: Node = <Node> { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } ; const fakeNode: Node = { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } as Node;
setConfig('default', { 'exif:exif': '*' }); setConfig('default', { 'exif:exif': '*' });
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse)); spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
@@ -146,7 +146,7 @@ describe('ContentMetaDataService', () => {
}); });
it('should filter the record options for node ', (done) => { it('should filter the record options for node ', (done) => {
const fakeNode: Node = <Node> { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } ; const fakeNode: Node = { name: 'Node', id: 'fake-id', isFile: true, aspectNames: ['exif:exif'] } as Node;
setConfig('default', { 'exif:exif': '*', 'rma:record': '*' }); setConfig('default', { 'exif:exif': '*', 'rma:record': '*' });
spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse)); spyOn(classesApi, 'getClass').and.returnValue(Promise.resolve(exifResponse));
@@ -167,17 +167,17 @@ describe('ContentMetaDataService', () => {
describe('LayoutOriented preset', () => { describe('LayoutOriented preset', () => {
it('should return the node property', (done) => { it('should return the node property', (done) => {
const fakeNode: Node = <Node> { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } ; const fakeNode: Node = { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } as Node;
const customLayoutOrientedScheme = [ const customLayoutOrientedScheme = [
{ {
'id': 'app.content.metadata.customGroup2', id: 'app.content.metadata.customGroup2',
'title': 'Properties', title: 'Properties',
'items': [ items: [
{ {
'id': 'app.content.metadata.content', id: 'app.content.metadata.content',
'aspect': 'cm:content', aspect: 'cm:content',
'properties': '*' properties: '*'
} }
] ]
} }
@@ -199,28 +199,28 @@ describe('ContentMetaDataService', () => {
}); });
it('should filter the exif property', (done) => { it('should filter the exif property', (done) => {
const fakeNode: Node = <Node> { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } ; const fakeNode: Node = { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } as Node;
const customLayoutOrientedScheme = [ const customLayoutOrientedScheme = [
{ {
'id': 'app.content.metadata.customGroup', id: 'app.content.metadata.customGroup',
'title': 'Exif', title: 'Exif',
'items': [ items: [
{ {
'id': 'app.content.metadata.exifAspect2', id: 'app.content.metadata.exifAspect2',
'aspect': 'exif:exif', aspect: 'exif:exif',
'properties': '*' properties: '*'
} }
] ]
}, },
{ {
'id': 'app.content.metadata.customGroup2', id: 'app.content.metadata.customGroup2',
'title': 'Properties', title: 'Properties',
'items': [ items: [
{ {
'id': 'app.content.metadata.content', id: 'app.content.metadata.content',
'aspect': 'cm:content', aspect: 'cm:content',
'properties': '*' properties: '*'
} }
] ]
} }
@@ -242,19 +242,19 @@ describe('ContentMetaDataService', () => {
}); });
it('should exclude the property if this property is excluded from config', (done) => { it('should exclude the property if this property is excluded from config', (done) => {
const fakeNode: Node = <Node> { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } ; const fakeNode: Node = { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } as Node;
const customLayoutOrientedScheme = [ const customLayoutOrientedScheme = [
{ {
'id': 'app.content.metadata.customGroup', id: 'app.content.metadata.customGroup',
'title': 'Exif', title: 'Exif',
'includeAll': true, includeAll: true,
'exclude': ['cm:content'], exclude: ['cm:content'],
'items': [ items: [
{ {
'id': 'app.content.metadata.exifAspect2', id: 'app.content.metadata.exifAspect2',
'aspect': 'exif:exif', aspect: 'exif:exif',
'properties': '*' properties: '*'
} }
] ]
} }
@@ -277,28 +277,28 @@ describe('ContentMetaDataService', () => {
describe('Provided preset config', () => { describe('Provided preset config', () => {
it('should create the metadata config on the fly when preset config is provided', async (done) => { it('should create the metadata config on the fly when preset config is provided', async (done) => {
const fakeNode: Node = <Node> { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } ; const fakeNode: Node = { name: 'Node Action', id: 'fake-id', nodeType: 'cm:content', isFile: true, aspectNames: [] } as Node;
const customLayoutOrientedScheme = [ const customLayoutOrientedScheme = [
{ {
'id': 'app.content.metadata.customGroup', id: 'app.content.metadata.customGroup',
'title': 'Exif', title: 'Exif',
'items': [ items: [
{ {
'id': 'app.content.metadata.exifAspect2', id: 'app.content.metadata.exifAspect2',
'aspect': 'exif:exif', aspect: 'exif:exif',
'properties': '*' properties: '*'
} }
] ]
}, },
{ {
'id': 'app.content.metadata.customGroup2', id: 'app.content.metadata.customGroup2',
'title': 'Properties', title: 'Properties',
'items': [ items: [
{ {
'id': 'app.content.metadata.content', id: 'app.content.metadata.content',
'aspect': 'cm:content', aspect: 'cm:content',
'properties': '*' properties: '*'
} }
] ]
} }
@@ -31,84 +31,84 @@ describe('ContentTypePropertyService', () => {
let contentTypeService: ContentTypeService; let contentTypeService: ContentTypeService;
const mockContent: any = { const mockContent: any = {
'entry': entry:
{ {
'associations': [], associations: [],
'isArchive': true, isArchive: true,
'includedInSupertypeQuery': true, includedInSupertypeQuery: true,
'description': 'Base Content Object', description: 'Base Content Object',
'isContainer': false, isContainer: false,
'id': 'fk:nodeType', id: 'fk:nodeType',
'title': 'Content', title: 'Content',
'model': { 'namespacePrefix': 'fk' }, model: { namespacePrefix: 'fk' },
'properties': [{ 'id': 'cm:name', 'title': 'Name', 'description': 'Name', 'dataType': 'd:text', 'isMultiValued': false, 'isMandatory': true, 'isMandatoryEnforced': true, 'isProtected': false }], properties: [{ id: 'cm:name', title: 'Name', description: 'Name', dataType: 'd:text', isMultiValued: false, isMandatory: true, isMandatoryEnforced: true, isProtected: false }],
'parentId': 'cm:cmobject' parentId: 'cm:cmobject'
} }
}; };
const mockContentWithProperties: any = { const mockContentWithProperties: any = {
'entry': entry:
{ {
'associations': [], associations: [],
'isArchive': true, isArchive: true,
'includedInSupertypeQuery': true, includedInSupertypeQuery: true,
'description': 'Base Content Object', description: 'Base Content Object',
'isContainer': false, isContainer: false,
'id': 'fk:nodeType', id: 'fk:nodeType',
'title': 'Content', title: 'Content',
'model': { 'namespacePrefix': 'fk' }, model: { namespacePrefix: 'fk' },
'properties': [ properties: [
{ {
'id': 'cm:name', id: 'cm:name',
'title': 'Name', title: 'Name',
'description': 'Name', description: 'Name',
'dataType': 'd:text', dataType: 'd:text',
'isMultiValued': false, isMultiValued: false,
'isMandatory': true, isMandatory: true,
'isMandatoryEnforced': true, isMandatoryEnforced: true,
'isProtected': false isProtected: false
}, },
{ {
'id': 'fk:brendonstare', id: 'fk:brendonstare',
'title': 'Brendon', title: 'Brendon',
'description': 'is watching the dark emperor', description: 'is watching the dark emperor',
'dataType': 'd:text', dataType: 'd:text',
'isMultiValued': false, isMultiValued: false,
'isMandatory': true, isMandatory: true,
'defaultValue': 'default', defaultValue: 'default',
'isMandatoryEnforced': true, isMandatoryEnforced: true,
'isProtected': false isProtected: false
}], }],
'parentId': 'cm:cmobject' parentId: 'cm:cmobject'
} }
}; };
const mockSelectOptions: TypeEntry[] = [ const mockSelectOptions: TypeEntry[] = [
{ {
'entry': { entry: {
'isArchive': true, isArchive: true,
'includedInSupertypeQuery': true, includedInSupertypeQuery: true,
'isContainer': false, isContainer: false,
'model': { model: {
'id': 'e2e:test', id: 'e2e:test',
'author': 'E2e Automation User', author: 'E2e Automation User',
'description': 'Custom type e2e model', description: 'Custom type e2e model',
'namespaceUri': 'http://www.customModel.com/whatever', namespaceUri: 'http://www.customModel.com/whatever',
'namespacePrefix': 'e2e' namespacePrefix: 'e2e'
}, },
'id': 'e2e:test', id: 'e2e:test',
'title': 'Test type', title: 'Test type',
'properties': [{ properties: [{
'id': 'cm:name', id: 'cm:name',
'title': 'Name', title: 'Name',
'description': 'Name', description: 'Name',
'dataType': 'd:text', dataType: 'd:text',
'isMultiValued': false, isMultiValued: false,
'isMandatory': true, isMandatory: true,
'isMandatoryEnforced': true, isMandatoryEnforced: true,
'isProtected': false isProtected: false
}], }],
'parentId': 'cm:content' parentId: 'cm:content'
} }
} }
]; ];
@@ -127,7 +127,7 @@ describe('ContentTypePropertyService', () => {
}); });
it('should return a card text item for ACS version below 7', (done) => { it('should return a card text item for ACS version below 7', (done) => {
const fakeNode: Node = <Node> { const fakeNode: Node = {
name: 'Node', name: 'Node',
id: 'fake-id', id: 'fake-id',
isFile: true, isFile: true,
@@ -136,7 +136,7 @@ describe('ContentTypePropertyService', () => {
createdByUser: { displayName: 'test-user' }, createdByUser: { displayName: 'test-user' },
modifiedByUser: { displayName: 'test-user-modified' }, modifiedByUser: { displayName: 'test-user-modified' },
properties: {} properties: {}
}; } as Node;
spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(false); spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(false);
service.getContentTypeCardItem(fakeNode).subscribe((items: CardViewItem[]) => { service.getContentTypeCardItem(fakeNode).subscribe((items: CardViewItem[]) => {
expect(items.length).toBe(1); expect(items.length).toBe(1);
@@ -150,7 +150,7 @@ describe('ContentTypePropertyService', () => {
}); });
it('should return a card select item for ACS version 7 and above', (done) => { it('should return a card select item for ACS version 7 and above', (done) => {
const fakeNode: Node = <Node> { const fakeNode: Node = {
name: 'Node', name: 'Node',
id: 'fake-id', id: 'fake-id',
isFile: true, isFile: true,
@@ -159,7 +159,7 @@ describe('ContentTypePropertyService', () => {
createdByUser: { displayName: 'test-user' }, createdByUser: { displayName: 'test-user' },
modifiedByUser: { displayName: 'test-user-modified' }, modifiedByUser: { displayName: 'test-user-modified' },
properties: {} properties: {}
}; } as Node;
spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(true); spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(true);
spyOn(contentTypeService, 'getContentTypeByPrefix').and.returnValue(of(mockContent)); spyOn(contentTypeService, 'getContentTypeByPrefix').and.returnValue(of(mockContent));
spyOn(contentTypeService, 'getContentTypeChildren').and.returnValue(of(mockSelectOptions)); spyOn(contentTypeService, 'getContentTypeChildren').and.returnValue(of(mockSelectOptions));
@@ -175,7 +175,7 @@ describe('ContentTypePropertyService', () => {
}); });
it('should return a list of cards for the content type and all its own properties', (done) => { it('should return a list of cards for the content type and all its own properties', (done) => {
const fakeNode: Node = <Node> { const fakeNode: Node = {
name: 'Node', name: 'Node',
id: 'fake-id', id: 'fake-id',
isFile: true, isFile: true,
@@ -184,7 +184,7 @@ describe('ContentTypePropertyService', () => {
createdByUser: { displayName: 'test-user' }, createdByUser: { displayName: 'test-user' },
modifiedByUser: { displayName: 'test-user-modified' }, modifiedByUser: { displayName: 'test-user-modified' },
properties: {} properties: {}
}; } as Node;
spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(true); spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(true);
spyOn(contentTypeService, 'getContentTypeByPrefix').and.returnValue(of(mockContentWithProperties)); spyOn(contentTypeService, 'getContentTypeByPrefix').and.returnValue(of(mockContentWithProperties));
spyOn(contentTypeService, 'getContentTypeChildren').and.returnValue(of(mockSelectOptions)); spyOn(contentTypeService, 'getContentTypeChildren').and.returnValue(of(mockSelectOptions));
@@ -206,7 +206,7 @@ describe('ContentTypePropertyService', () => {
}); });
it('should return a list of cards for the content type and all its own properties with relative value set', (done) => { it('should return a list of cards for the content type and all its own properties with relative value set', (done) => {
const fakeNode: Node = <Node> { const fakeNode: Node = {
name: 'Node', name: 'Node',
id: 'fake-id', id: 'fake-id',
isFile: true, isFile: true,
@@ -215,7 +215,7 @@ describe('ContentTypePropertyService', () => {
createdByUser: { displayName: 'test-user' }, createdByUser: { displayName: 'test-user' },
modifiedByUser: { displayName: 'test-user-modified' }, modifiedByUser: { displayName: 'test-user-modified' },
properties: {'fk:brendonstare': 'i keep staring i do not know why'} properties: {'fk:brendonstare': 'i keep staring i do not know why'}
}; } as Node;
spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(true); spyOn(versionCompatibilityService, 'isVersionSupported').and.returnValue(true);
spyOn(contentTypeService, 'getContentTypeByPrefix').and.returnValue(of(mockContentWithProperties)); spyOn(contentTypeService, 'getContentTypeByPrefix').and.returnValue(of(mockContentWithProperties));
spyOn(contentTypeService, 'getContentTypeChildren').and.returnValue(of(mockSelectOptions)); spyOn(contentTypeService, 'getContentTypeChildren').and.returnValue(of(mockSelectOptions));
@@ -85,7 +85,7 @@ export class ContentTypePropertiesService {
value: currentValue, value: currentValue,
key: 'nodeType', key: 'nodeType',
editable: true, editable: true,
options$: options$, options$,
displayNoneOption: false displayNoneOption: false
}); });
@@ -98,7 +98,7 @@ export class ContentTypePropertiesService {
distinctUntilChanged(), distinctUntilChanged(),
map(([contentTypesEntries, currentContentType]) => { map(([contentTypesEntries, currentContentType]) => {
const updatedTypes = this.appendCurrentType(currentContentType, contentTypesEntries); const updatedTypes = this.appendCurrentType(currentContentType, contentTypesEntries);
return updatedTypes.map((contentType) => <CardViewSelectItemOption<string>> { key: contentType.entry.id, label: contentType.entry.title ?? contentType.entry.id }); return updatedTypes.map((contentType) => ({ key: contentType.entry.id, label: contentType.entry.title ?? contentType.entry.id }));
})); }));
} }
@@ -121,7 +121,7 @@ export class ContentTypePropertiesService {
title: 'CORE.METADATA.CONTENT_TYPE.DIALOG.TITLE', title: 'CORE.METADATA.CONTENT_TYPE.DIALOG.TITLE',
description: 'CORE.METADATA.CONTENT_TYPE.DIALOG.DESCRIPTION', description: 'CORE.METADATA.CONTENT_TYPE.DIALOG.DESCRIPTION',
confirmMessage: 'CORE.METADATA.CONTENT_TYPE.DIALOG.CONFIRM', confirmMessage: 'CORE.METADATA.CONTENT_TYPE.DIALOG.CONFIRM',
select: select, select,
nodeType nodeType
}; };
@@ -74,9 +74,7 @@ describe('PropertyDescriptorLoaderService', () => {
const apiResponses = [ exifResponse, contentResponse ]; const apiResponses = [ exifResponse, contentResponse ];
let counter = 0; let counter = 0;
spyOn(classesApi, 'getClass').and.callFake(() => { spyOn(classesApi, 'getClass').and.callFake(() => Promise.resolve(apiResponses[counter++]));
return Promise.resolve(apiResponses[counter++]);
});
service.load(['exif:exif', 'cm:content']) service.load(['exif:exif', 'cm:content'])
.subscribe({ .subscribe({
@@ -47,10 +47,8 @@ export class PropertyDescriptorsService {
} }
private convertToObject(propertyGroupsArray: PropertyGroup[]): PropertyGroupContainer { private convertToObject(propertyGroupsArray: PropertyGroup[]): PropertyGroupContainer {
return propertyGroupsArray.reduce((propertyGroups, propertyGroup) => { return propertyGroupsArray.reduce((propertyGroups, propertyGroup) => Object.assign({}, propertyGroups, {
return Object.assign({}, propertyGroups, {
[propertyGroup.name]: propertyGroup [propertyGroup.name]: propertyGroup
}); }), {});
}, {});
} }
} }
@@ -15,8 +15,10 @@
* limitations under the License. * limitations under the License.
*/ */
/* eslint-disable @typescript-eslint/naming-convention */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { PropertyGroupTranslatorService } from './property-groups-translator.service'; import { PropertyGroupTranslatorService, RECOGNISED_ECM_TYPES } from './property-groups-translator.service';
import { Property, OrganisedPropertyGroup } from '../interfaces/content-metadata.interfaces'; import { Property, OrganisedPropertyGroup } from '../interfaces/content-metadata.interfaces';
import { import {
CardViewTextItemModel, CardViewTextItemModel,
@@ -165,7 +167,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': 'The Chariot Line' }; propertyValues = { 'FAS:PLAGUE': 'The Chariot Line' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = <CardViewTextItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel'); expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
}); });
@@ -183,7 +185,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAKE:NAME': 'API Fake response' }; propertyValues = { 'FAKE:NAME': 'API Fake response' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = <CardViewTextItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel'); expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty.editable).toBe(false); expect(cardViewProperty.editable).toBe(false);
}); });
@@ -195,7 +197,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyGroups.push(propertyGroup); propertyGroups.push(propertyGroup);
}); });
PropertyGroupTranslatorService.RECOGNISED_ECM_TYPES.forEach((dataType) => { RECOGNISED_ECM_TYPES.forEach((dataType) => {
it(`should translate properly the basic attributes of a property for ${dataType}`, () => { it(`should translate properly the basic attributes of a property for ${dataType}`, () => {
property.name = 'prefix:name'; property.name = 'prefix:name';
property.title = 'title'; property.title = 'title';
@@ -219,7 +221,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': 'The Chariot Line' }; propertyValues = { 'FAS:PLAGUE': 'The Chariot Line' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = <CardViewTextItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel'); expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty.value).toBe('The Chariot Line'); expect(cardViewProperty.value).toBe('The Chariot Line');
expect(cardViewProperty.multiline).toBeFalsy('Property should be singleline'); expect(cardViewProperty.multiline).toBeFalsy('Property should be singleline');
@@ -231,7 +233,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': 'The Chariot Line' }; propertyValues = { 'FAS:PLAGUE': 'The Chariot Line' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewTextItemModel = <CardViewTextItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewTextItemModel = cardViewGroup[0].properties[0] as CardViewTextItemModel;
expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel'); expect(cardViewProperty instanceof CardViewTextItemModel).toBeTruthy('Property should be instance of CardViewTextItemModel');
expect(cardViewProperty.value).toBe('The Chariot Line'); expect(cardViewProperty.value).toBe('The Chariot Line');
expect(cardViewProperty.multiline).toBeTruthy('Property should be multiline'); expect(cardViewProperty.multiline).toBeTruthy('Property should be multiline');
@@ -244,7 +246,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': expectedValue }; propertyValues = { 'FAS:PLAGUE': expectedValue };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewDateItemModel = <CardViewDateItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewDateItemModel = cardViewGroup[0].properties[0] as CardViewDateItemModel;
expect(cardViewProperty instanceof CardViewDateItemModel).toBeTruthy('Property should be instance of CardViewDateItemModel'); expect(cardViewProperty instanceof CardViewDateItemModel).toBeTruthy('Property should be instance of CardViewDateItemModel');
expect(cardViewProperty.value).toBe(expectedValue); expect(cardViewProperty.value).toBe(expectedValue);
}); });
@@ -256,7 +258,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': expectedValue }; propertyValues = { 'FAS:PLAGUE': expectedValue };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewDatetimeItemModel = <CardViewDatetimeItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewDatetimeItemModel = cardViewGroup[0].properties[0] as CardViewDatetimeItemModel;
expect(cardViewProperty instanceof CardViewDatetimeItemModel).toBeTruthy('Property should be instance of CardViewDatetimeItemModel'); expect(cardViewProperty instanceof CardViewDatetimeItemModel).toBeTruthy('Property should be instance of CardViewDatetimeItemModel');
expect(cardViewProperty.value).toBe(expectedValue); expect(cardViewProperty.value).toBe(expectedValue);
}); });
@@ -267,7 +269,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': '1024' }; propertyValues = { 'FAS:PLAGUE': '1024' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewIntItemModel = <CardViewIntItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewIntItemModel = cardViewGroup[0].properties[0] as CardViewIntItemModel;
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel'); expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel');
expect(cardViewProperty.value).toBe(1024); expect(cardViewProperty.value).toBe(1024);
}); });
@@ -278,7 +280,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': 0 }; propertyValues = { 'FAS:PLAGUE': 0 };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewIntItemModel = <CardViewIntItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewIntItemModel = cardViewGroup[0].properties[0] as CardViewIntItemModel;
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel'); expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel');
expect(cardViewProperty.value).toBe(0); expect(cardViewProperty.value).toBe(0);
}); });
@@ -289,7 +291,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': '1024' }; propertyValues = { 'FAS:PLAGUE': '1024' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewIntItemModel = <CardViewIntItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewIntItemModel = cardViewGroup[0].properties[0] as CardViewIntItemModel;
expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel'); expect(cardViewProperty instanceof CardViewIntItemModel).toBeTruthy('Property should be instance of CardViewIntItemModel');
expect(cardViewProperty.value).toBe(1024); expect(cardViewProperty.value).toBe(1024);
}); });
@@ -300,7 +302,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': '1024.24' }; propertyValues = { 'FAS:PLAGUE': '1024.24' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewFloatItemModel = <CardViewFloatItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewFloatItemModel = cardViewGroup[0].properties[0] as CardViewFloatItemModel;
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel'); expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel');
expect(cardViewProperty.value).toBe(1024.24); expect(cardViewProperty.value).toBe(1024.24);
}); });
@@ -311,7 +313,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': 0 }; propertyValues = { 'FAS:PLAGUE': 0 };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewFloatItemModel = <CardViewFloatItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewFloatItemModel = cardViewGroup[0].properties[0] as CardViewFloatItemModel;
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel'); expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel');
expect(cardViewProperty.value).toBe(0); expect(cardViewProperty.value).toBe(0);
}); });
@@ -322,7 +324,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': '1024.24' }; propertyValues = { 'FAS:PLAGUE': '1024.24' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewFloatItemModel = <CardViewFloatItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewFloatItemModel = cardViewGroup[0].properties[0] as CardViewFloatItemModel;
expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel'); expect(cardViewProperty instanceof CardViewFloatItemModel).toBeTruthy('Property should be instance of CardViewFloatItemModel');
expect(cardViewProperty.value).toBe(1024.24); expect(cardViewProperty.value).toBe(1024.24);
}); });
@@ -333,7 +335,7 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': true }; propertyValues = { 'FAS:PLAGUE': true };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, null);
const cardViewProperty: CardViewBoolItemModel = <CardViewBoolItemModel> cardViewGroup[0].properties[0]; const cardViewProperty: CardViewBoolItemModel = cardViewGroup[0].properties[0] as CardViewBoolItemModel;
expect(cardViewProperty instanceof CardViewBoolItemModel).toBeTruthy('Property should be instance of CardViewBoolItemModel'); expect(cardViewProperty instanceof CardViewBoolItemModel).toBeTruthy('Property should be instance of CardViewBoolItemModel');
expect(cardViewProperty.value).toBe(true); expect(cardViewProperty.value).toBe(true);
}); });
@@ -356,23 +358,23 @@ describe('PropertyGroupTranslatorService', () => {
propertyValues = { 'FAS:PLAGUE': 'two' }; propertyValues = { 'FAS:PLAGUE': 'two' };
const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, definition); const cardViewGroup = service.translateToCardViewGroups(propertyGroups, propertyValues, definition);
const cardViewProperty: CardViewSelectItemModel<CardViewSelectItemProperties<string>> = <CardViewSelectItemModel<CardViewSelectItemProperties<string>>> cardViewGroup[0].properties[0]; const cardViewProperty = cardViewGroup[0].properties[0] as CardViewSelectItemModel<CardViewSelectItemProperties<string>>;
expect(cardViewProperty instanceof CardViewSelectItemModel).toBeTruthy('Property should be instance of CardViewBoolItemModel'); expect(cardViewProperty instanceof CardViewSelectItemModel).toBeTruthy('Property should be instance of CardViewBoolItemModel');
expect(cardViewProperty.value).toBe('two'); expect(cardViewProperty.value).toBe('two');
}); });
it('should translate content type properties into card items', () => { it('should translate content type properties into card items', () => {
const propertyBase = <PropertyBase> { const propertyBase = {
'id': 'fk:brendonstare', id: 'fk:brendonstare',
'title': 'Brendon', title: 'Brendon',
'description': 'is watching the dark emperor', description: 'is watching the dark emperor',
'dataType': 'd:text', dataType: 'd:text',
'isMultiValued': true, isMultiValued: true,
'isMandatory': true, isMandatory: true,
'defaultValue': 'default', defaultValue: 'default',
'isMandatoryEnforced': true, isMandatoryEnforced: true,
'isProtected': false isProtected: false
}; } as PropertyBase;
const cardViewProperty = service.translateProperty(propertyBase, 'Scary Brandon and the DuckTales', true); const cardViewProperty = service.translateProperty(propertyBase, 'Scary Brandon and the DuckTales', true);
@@ -382,17 +384,17 @@ describe('PropertyGroupTranslatorService', () => {
}); });
it('should translate content type properties into card items with default value when no value is passed', () => { it('should translate content type properties into card items with default value when no value is passed', () => {
const propertyBase = <PropertyBase> { const propertyBase = {
'id': 'fk:brendonstare', id: 'fk:brendonstare',
'title': 'Brendon', title: 'Brendon',
'description': 'is watching the dark emperor', description: 'is watching the dark emperor',
'dataType': 'd:text', dataType: 'd:text',
'isMultiValued': true, isMultiValued: true,
'isMandatory': true, isMandatory: true,
'defaultValue': 'default', defaultValue: 'default',
'isMandatoryEnforced': true, isMandatoryEnforced: true,
'isProtected': false isProtected: false
}; } as PropertyBase;
const cardViewProperty = service.translateProperty(propertyBase, null, true); const cardViewProperty = service.translateProperty(propertyBase, null, true);
@@ -402,17 +404,17 @@ describe('PropertyGroupTranslatorService', () => {
}); });
it('should not edit the protected fields', () => { it('should not edit the protected fields', () => {
const propertyBase = <PropertyBase> { const propertyBase = {
'id': 'fk:emperor', id: 'fk:emperor',
'title': 'Emperor', title: 'Emperor',
'description': 'is watching the dark emperor', description: 'is watching the dark emperor',
'dataType': 'd:text', dataType: 'd:text',
'isMultiValued': true, isMultiValued: true,
'isMandatory': true, isMandatory: true,
'defaultValue': 'default', defaultValue: 'default',
'isMandatoryEnforced': true, isMandatoryEnforced: true,
'isProtected': true isProtected: true
}; } as PropertyBase;
const cardViewProperty = service.translateProperty(propertyBase, null, true); const cardViewProperty = service.translateProperty(propertyBase, null, true);
@@ -45,13 +45,12 @@ const D_FLOAT = 'd:float';
const D_DOUBLE = 'd:double'; const D_DOUBLE = 'd:double';
const D_BOOLEAN = 'd:boolean'; const D_BOOLEAN = 'd:boolean';
export const RECOGNISED_ECM_TYPES = [D_TEXT, D_MLTEXT, D_DATE, D_DATETIME, D_INT, D_LONG, D_FLOAT, D_DOUBLE, D_BOOLEAN];
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class PropertyGroupTranslatorService { export class PropertyGroupTranslatorService {
static readonly RECOGNISED_ECM_TYPES = [D_TEXT, D_MLTEXT, D_DATE, D_DATETIME, D_INT, D_LONG, D_FLOAT, D_DOUBLE, D_BOOLEAN];
valueSeparator: string; valueSeparator: string;
constructor(private logService: LogService, constructor(private logService: LogService,
@@ -87,9 +86,7 @@ export class PropertyGroupTranslatorService {
} }
private translateArray(properties: Property[], propertyValues: any, definition: Definition): CardViewItem[] { private translateArray(properties: Property[], propertyValues: any, definition: Definition): CardViewItem[] {
return properties.map((property) => { return properties.map((property) => this.translate(property, propertyValues, this.getPropertyConstraints(property.name, definition)));
return this.translate(property, propertyValues, this.getPropertyConstraints(property.name, definition));
});
} }
private translate(property: Property, propertyValues: any, constraints: Constraint[]): CardViewItem { private translate(property: Property, propertyValues: any, constraints: Constraint[]): CardViewItem {
@@ -108,7 +105,7 @@ export class PropertyGroupTranslatorService {
key: `${prefix}${property.name}`, key: `${prefix}${property.name}`,
default: property.defaultValue, default: property.defaultValue,
editable: property.protected ? false : property.editable !== undefined ? property.editable : true, editable: property.protected ? false : property.editable !== undefined ? property.editable : true,
constraints: constraints constraints
}; };
return this.transform(propertyDefinition, property.dataType, property.multiValued); return this.transform(propertyDefinition, property.dataType, property.multiValued);
@@ -189,7 +186,7 @@ export class PropertyGroupTranslatorService {
} }
private checkECMTypeValidity(ecmPropertyType: string) { private checkECMTypeValidity(ecmPropertyType: string) {
if (PropertyGroupTranslatorService.RECOGNISED_ECM_TYPES.indexOf(ecmPropertyType) === -1) { if (RECOGNISED_ECM_TYPES.indexOf(ecmPropertyType) === -1) {
this.logService.error(`Unknown type for mapping: ${ecmPropertyType}`); this.logService.error(`Unknown type for mapping: ${ecmPropertyType}`);
} }
} }
@@ -26,17 +26,17 @@ import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { NodeAction } from '../document-list/models/node-action.enum'; import { NodeAction } from '../document-list/models/node-action.enum';
const fakeNodeEntry: NodeEntry = <NodeEntry> { const fakeNodeEntry = {
entry: { entry: {
id: 'fake', id: 'fake',
name: 'fake-name' name: 'fake-name'
} }
}; } as NodeEntry;
const fakeNode: Node = <Node> { const fakeNode = {
id: 'fake', id: 'fake',
name: 'fake-name' name: 'fake-name'
}; } as Node;
const fakeSiteList: SitePaging = new SitePaging({ const fakeSiteList: SitePaging = new SitePaging({
list: { list: {
@@ -94,10 +94,10 @@ describe('ContentNodeDialogService', () => {
}); });
it('should not open the lock node dialog if have no permission', () => { it('should not open the lock node dialog if have no permission', () => {
const testNode: Node = <Node> { const testNode = {
id: 'fake', id: 'fake',
isFile: false isFile: false
}; } as Node;
service.openLockNodeDialog(testNode).subscribe(() => { service.openLockNodeDialog(testNode).subscribe(() => {
}, (error) => { }, (error) => {
@@ -143,26 +143,26 @@ describe('ContentNodeDialogService', () => {
})); }));
describe('for the copy/move dialog', () => { describe('for the copy/move dialog', () => {
const siteNode: Node = <Node> { const siteNode: Node = {
id: 'site-node-id', id: 'site-node-id',
nodeType: 'st:site' nodeType: 'st:site'
}; } as Node;
const sites: Node = <Node> { const sites: Node = {
id: 'sites-id', id: 'sites-id',
nodeType: 'st:sites' nodeType: 'st:sites'
}; } as Node;
const site: Site = <Site> { const site: Site = {
id: 'site-id', id: 'site-id',
guid: 'any-guid' guid: 'any-guid'
}; } as Site;
const nodeEntryWithRightPermissions: Node = <Node> { const nodeEntryWithRightPermissions: Node = {
id: 'node-id', id: 'node-id',
allowableOperations: ['create'] allowableOperations: ['create']
}; } as Node;
const nodeEntryNoPermissions: Node = <Node> { const nodeEntryNoPermissions: Node = {
id: 'node-id', id: 'node-id',
allowableOperations: [] allowableOperations: []
}; } as Node;
const siteFixture = [ const siteFixture = [
{ {
@@ -57,17 +57,17 @@ export class ContentNodeDialogService {
/** /**
* Opens a file browser at a chosen folder location. * Opens a file browser at a chosen folder location.
* shows files and folders in the dialog search result. * shows files and folders in the dialog search result.
*
* @param folderNodeId ID of the folder to use * @param folderNodeId ID of the folder to use
* @returns Information about the selected file(s) * @returns Information about the selected file(s)
*/ */
openFileBrowseDialogByFolderId(folderNodeId: string): Observable<Node[]> { openFileBrowseDialogByFolderId(folderNodeId: string): Observable<Node[]> {
return this.documentListService.getFolderNode(folderNodeId).pipe(switchMap((nodeEntry: NodeEntry) => { return this.documentListService.getFolderNode(folderNodeId).pipe(switchMap((nodeEntry: NodeEntry) => this.openUploadFileDialog(NodeAction.CHOOSE, nodeEntry.entry, true)));
return this.openUploadFileDialog(NodeAction.CHOOSE, nodeEntry.entry, true);
}));
} }
/** /**
* Opens a lock node dialog. * Opens a lock node dialog.
*
* @param contentEntry Node to lock * @param contentEntry Node to lock
* @returns Error/status message (if any) * @returns Error/status message (if any)
*/ */
@@ -95,17 +95,17 @@ export class ContentNodeDialogService {
/** /**
* Opens a file browser at a chosen site location. * Opens a file browser at a chosen site location.
* shows files and folders in the dialog search result. * shows files and folders in the dialog search result.
*
* @returns Information about the selected file(s) * @returns Information about the selected file(s)
*/ */
openFileBrowseDialogBySite(): Observable<Node[]> { openFileBrowseDialogBySite(): Observable<Node[]> {
return this.siteService.getSites().pipe(switchMap((response: SitePaging) => { return this.siteService.getSites().pipe(switchMap((response: SitePaging) => this.openFileBrowseDialogByFolderId(response.list.entries[0].entry.guid)));
return this.openFileBrowseDialogByFolderId(response.list.entries[0].entry.guid);
}));
} }
/** /**
* Opens a file browser at a default myFile location. * Opens a file browser at a default myFile location.
* shows files and folders in the dialog search result. * shows files and folders in the dialog search result.
*
* @returns Information about the selected file(s) * @returns Information about the selected file(s)
*/ */
openFileBrowseDialogByDefaultLocation(): Observable<Node[]> { openFileBrowseDialogByDefaultLocation(): Observable<Node[]> {
@@ -114,6 +114,7 @@ export class ContentNodeDialogService {
/** /**
* Opens a folder browser at a chosen site location. * Opens a folder browser at a chosen site location.
*
* @returns Information about the selected folder(s) * @returns Information about the selected folder(s)
*/ */
openFolderBrowseDialogBySite(): Observable<Node[]> { openFolderBrowseDialogBySite(): Observable<Node[]> {
@@ -122,17 +123,17 @@ export class ContentNodeDialogService {
/** /**
* Opens a folder browser at a chosen folder location. * Opens a folder browser at a chosen folder location.
*
* @param folderNodeId ID of the folder to use * @param folderNodeId ID of the folder to use
* @returns Information about the selected folder(s) * @returns Information about the selected folder(s)
*/ */
openFolderBrowseDialogByFolderId(folderNodeId: string): Observable<Node[]> { openFolderBrowseDialogByFolderId(folderNodeId: string): Observable<Node[]> {
return this.documentListService.getFolderNode(folderNodeId).pipe(switchMap((node: NodeEntry) => { return this.documentListService.getFolderNode(folderNodeId).pipe(switchMap((node: NodeEntry) => this.openUploadFolderDialog(NodeAction.CHOOSE, node.entry)));
return this.openUploadFolderDialog(NodeAction.CHOOSE, node.entry);
}));
} }
/** /**
* Opens a dialog to copy or move an item to a new location. * Opens a dialog to copy or move an item to a new location.
*
* @param action Name of the action (eg, "Copy" or "Move") to show in the title * @param action Name of the action (eg, "Copy" or "Move") to show in the title
* @param contentEntry Item to be copied or moved * @param contentEntry Item to be copied or moved
* @param permission Permission for the operation * @param permission Permission for the operation
@@ -153,7 +154,7 @@ export class ContentNodeDialogService {
where: '(isFolder=true)', where: '(isFolder=true)',
isSelectionValid: this.isCopyMoveSelectionValid.bind(this), isSelectionValid: this.isCopyMoveSelectionValid.bind(this),
excludeSiteContent: excludeSiteContent || ContentNodeDialogService.nonDocumentSiteContent, excludeSiteContent: excludeSiteContent || ContentNodeDialogService.nonDocumentSiteContent,
select: select select
}; };
const dialogRef = this.openContentNodeDialog(data, 'adf-content-node-selector-dialog', '630px'); const dialogRef = this.openContentNodeDialog(data, 'adf-content-node-selector-dialog', '630px');
@@ -168,6 +169,7 @@ export class ContentNodeDialogService {
/** /**
* Gets the translation of the dialog title. * Gets the translation of the dialog title.
*
* @param action Name of the action to display in the dialog title * @param action Name of the action to display in the dialog title
* @param name Name of the item on which the action is being performed * @param name Name of the item on which the action is being performed
* @returns Translated version of the title * @returns Translated version of the title
@@ -178,6 +180,7 @@ export class ContentNodeDialogService {
/** /**
* Opens a dialog to choose folders to upload. * Opens a dialog to choose folders to upload.
*
* @param action Name of the action to show in the title * @param action Name of the action to show in the title
* @param contentEntry Item to upload * @param contentEntry Item to upload
* @returns Information about the chosen folder(s) * @returns Information about the chosen folder(s)
@@ -193,7 +196,7 @@ export class ContentNodeDialogService {
imageResolver: this.imageResolver.bind(this), imageResolver: this.imageResolver.bind(this),
isSelectionValid: this.hasAllowableOperationsOnNodeFolder.bind(this), isSelectionValid: this.hasAllowableOperationsOnNodeFolder.bind(this),
where: '(isFolder=true)', where: '(isFolder=true)',
select: select select
}; };
const dialogRef = this.openContentNodeDialog(data, 'adf-content-node-selector-dialog', '630px'); const dialogRef = this.openContentNodeDialog(data, 'adf-content-node-selector-dialog', '630px');
@@ -204,6 +207,7 @@ export class ContentNodeDialogService {
/** /**
* Opens a dialog to choose a file to upload. * Opens a dialog to choose a file to upload.
*
* @param action Name of the action to show in the title * @param action Name of the action to show in the title
* @param contentEntry Item to upload * @param contentEntry Item to upload
* @param showFilesInResult Show files in dialog search result * @param showFilesInResult Show files in dialog search result
@@ -219,7 +223,7 @@ export class ContentNodeDialogService {
currentFolderId: contentEntry.id, currentFolderId: contentEntry.id,
imageResolver: this.imageResolver.bind(this), imageResolver: this.imageResolver.bind(this),
isSelectionValid: (entry: Node) => entry.isFile, isSelectionValid: (entry: Node) => entry.isFile,
select: select, select,
showFilesInResult showFilesInResult
}; };
@@ -69,16 +69,16 @@ describe('ContentNodeSelectorPanelComponent', () => {
let thumbnailService: ThumbnailService; let thumbnailService: ThumbnailService;
let contentService: ContentService; let contentService: ContentService;
function typeToSearchBox(searchTerm = 'string-to-search') { const typeToSearchBox = (searchTerm = 'string-to-search') => {
const searchInput = fixture.debugElement.query(By.css('[data-automation-id="content-node-selector-search-input"]')); const searchInput = fixture.debugElement.query(By.css('[data-automation-id="content-node-selector-search-input"]'));
searchInput.nativeElement.value = searchTerm; searchInput.nativeElement.value = searchTerm;
component.searchInput.setValue(searchTerm); component.searchInput.setValue(searchTerm);
fixture.detectChanges(); fixture.detectChanges();
} };
function triggerSearchResults(searchResults: ResultSetPaging) { const triggerSearchResults = (searchResults: ResultSetPaging) => {
component.queryBuilderService.executed.next(searchResults); component.queryBuilderService.executed.next(searchResults);
} };
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -122,12 +122,14 @@ describe('ContentNodeSelectorPanelComponent', () => {
beforeEach(() => { beforeEach(() => {
documentListService = TestBed.inject(DocumentListService); documentListService = TestBed.inject(DocumentListService);
spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } })); spyOn(documentListService, 'getFolderNode').and.returnValue(of({ entry: { path: { elements: [] } } }));
spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test')); spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test'));
spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({
list: { list: {
entries: [<SiteEntry> { entry: { guid: 'namek', id: 'namek' } }, entries: [
<SiteEntry> { entry: { guid: 'blog', id: 'blog' } }] { entry: { guid: 'namek', id: 'namek' } },
{ entry: { guid: 'blog', id: 'blog' } }
]
} }
}))); })));
@@ -140,7 +142,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
}); });
it('should trigger the select event when selection has been made', (done) => { it('should trigger the select event when selection has been made', (done) => {
const expectedNode = <Node> { id: 'fakeid'}; const expectedNode = { id: 'fakeid'} as Node;
component.select.subscribe((nodes) => { component.select.subscribe((nodes) => {
expect(nodes.length).toBe(1); expect(nodes.length).toBe(1);
expect(nodes[0]).toBe(expectedNode); expect(nodes[0]).toBe(expectedNode);
@@ -155,14 +157,12 @@ describe('ContentNodeSelectorPanelComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const testSiteContent = new Node({ id: 'blog-id', properties: { 'st:componentId': 'blog' } }); const testSiteContent = new Node({ id: 'blog-id', properties: { 'st:componentId': 'blog' } });
expect(component.rowFilter(<any> { node: { entry: testSiteContent } }, null, null)) expect(component.rowFilter({ node: { entry: testSiteContent } } as any, null, null))
.toBe(false, 'did not filter out blog'); .toBe(false, 'did not filter out blog');
}); });
it('should still be able to filter out the exclude site content after rowFilter changes', () => { it('should still be able to filter out the exclude site content after rowFilter changes', () => {
const filterFunction1 = () => { const filterFunction1 = () => true;
return true;
};
const filterFunction2 = (row: ShareDataRow) => { const filterFunction2 = (row: ShareDataRow) => {
const node: Node = row.node.entry; const node: Node = row.node.entry;
return node.isFile; return node.isFile;
@@ -177,12 +177,12 @@ describe('ContentNodeSelectorPanelComponent', () => {
properties: { 'st:componentId': 'blog' }, properties: { 'st:componentId': 'blog' },
isFile: true isFile: true
}); });
expect(component.rowFilter(<any> { node: { entry: testSiteContent } }, null, null)) expect(component.rowFilter({ node: { entry: testSiteContent } } as any, null, null))
.toBe(false, 'did not filter out blog with filterFunction1'); .toBe(false, 'did not filter out blog with filterFunction1');
component.rowFilter = filterFunction2; component.rowFilter = filterFunction2;
fixture.detectChanges(); fixture.detectChanges();
expect(component.rowFilter(<any> { node: { entry: testSiteContent } }, null, null)) expect(component.rowFilter({ node: { entry: testSiteContent } } as any, null, null))
.toBe(false, 'did not filter out blog with filterFunction2'); .toBe(false, 'did not filter out blog with filterFunction2');
}); });
@@ -190,7 +190,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const testSiteContent = new Node({ id: 'blog-id', properties: { 'st:componentId': 'blog' } }); const testSiteContent = new Node({ id: 'blog-id', properties: { 'st:componentId': 'blog' } });
expect(component.rowFilter(<any> { node: { entry: testSiteContent } }, null, null)).toBe(true); expect(component.rowFilter({ node: { entry: testSiteContent } } as any, null, null)).toBe(true);
}); });
it('should render search input by default', () => { it('should render search input by default', () => {
@@ -227,7 +227,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
beforeEach(() => { beforeEach(() => {
documentListService = TestBed.inject(DocumentListService); documentListService = TestBed.inject(DocumentListService);
spyOn(documentListService, 'getFolderNode').and.returnValue(of(<NodeEntry> { entry: { path: { elements: [] } } })); spyOn(documentListService, 'getFolderNode').and.returnValue(of({ entry: { path: { elements: [] } } }));
spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test')); spyOn(documentListService, 'getFolder').and.returnValue(throwError('No results for test'));
spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } }))); spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
@@ -305,7 +305,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
component.onFolderChange(nodeEntryEvent); component.onFolderChange(nodeEntryEvent);
fixture.detectChanges(); fixture.detectChanges();
const chosenNode = <Node> { path: { elements: [] } }; const chosenNode = { path: { elements: [] } } as Node;
component.onCurrentSelection([ { entry: chosenNode } ]); component.onCurrentSelection([ { entry: chosenNode } ]);
fixture.detectChanges(); fixture.detectChanges();
@@ -328,14 +328,12 @@ describe('ContentNodeSelectorPanelComponent', () => {
}); });
it('should make changes to breadcrumb folderNode if breadcrumbTransform is defined', (done) => { it('should make changes to breadcrumb folderNode if breadcrumbTransform is defined', (done) => {
const transformedFolderNode = <Node> { const transformedFolderNode = {
id: 'trans-node', id: 'trans-node',
name: 'trans-node-name', name: 'trans-node-name',
path: { elements: [{ id: 'testId', name: 'testName' }] } path: { elements: [{ id: 'testId', name: 'testName' }] }
}; };
component.breadcrumbTransform = (() => { component.breadcrumbTransform = (() => transformedFolderNode);
return transformedFolderNode;
});
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
@@ -387,11 +385,11 @@ describe('ContentNodeSelectorPanelComponent', () => {
describe('Search functionality', () => { describe('Search functionality', () => {
let getCorrespondingNodeIdsSpy; let getCorrespondingNodeIdsSpy;
let customResourcesService: CustomResourcesService; let customResourcesService: CustomResourcesService;
const entry: Node = <Node> { id: 'fakeid'}; const entry: Node = { id: 'fakeid'} as Node;
beforeEach(() => { beforeEach(() => {
const documentListService = TestBed.inject(DocumentListService); const documentListService = TestBed.inject(DocumentListService);
const expectedDefaultFolderNode = <NodeEntry> { entry: { path: { elements: [] } } }; const expectedDefaultFolderNode = { entry: { path: { elements: [] } } };
component.isSelectionValid = (node: Node) => node.isFile; component.isSelectionValid = (node: Node) => node.isFile;
spyOn(documentListService, 'getFolderNode').and.returnValue(of(expectedDefaultFolderNode)); spyOn(documentListService, 'getFolderNode').and.returnValue(of(expectedDefaultFolderNode));
@@ -506,7 +504,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
})); }));
it('should update the breadcrumb when changing to a custom site', async () => { it('should update the breadcrumb when changing to a custom site', async () => {
component.siteChanged(<SiteEntry> { entry: { guid: '-mysites-', title: 'My Sites' } }); component.siteChanged({ entry: { guid: '-mysites-', title: 'My Sites' } } as SiteEntry);
expect(component.breadcrumbFolderTitle).toBe('My Sites'); expect(component.breadcrumbFolderTitle).toBe('My Sites');
}); });
@@ -518,7 +516,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
expect(searchSpy.calls.count()).toBe(1, 'Search count should be one after only one search'); expect(searchSpy.calls.count()).toBe(1, 'Search count should be one after only one search');
component.siteChanged(<SiteEntry> { entry: { guid: 'namek' } }); component.siteChanged({ entry: { guid: 'namek' } } as SiteEntry);
const expectedQueryBody = mockQueryBody; const expectedQueryBody = mockQueryBody;
expectedQueryBody.filterQueries = [ { query: `ANCESTOR:'workspace://SpacesStore/namek'`} ]; expectedQueryBody.filterQueries = [ { query: `ANCESTOR:'workspace://SpacesStore/namek'`} ];
@@ -528,7 +526,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
})); }));
it('should create the query with the right parameters on changing the site selectBox value from a custom dropdown menu', fakeAsync(() => { it('should create the query with the right parameters on changing the site selectBox value from a custom dropdown menu', fakeAsync(() => {
component.dropdownSiteList = <SitePaging> { list: { entries: [<SiteEntry> { entry: { guid: '-sites-' } }, <SiteEntry> { entry: { guid: 'namek' } }] } }; component.dropdownSiteList = { list: { entries: [{ entry: { guid: '-sites-' } }, { entry: { guid: 'namek' } }] } } as SitePaging;
fixture.detectChanges(); fixture.detectChanges();
typeToSearchBox('search-term'); typeToSearchBox('search-term');
@@ -537,7 +535,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
expect(searchSpy.calls.count()).toBe(1); expect(searchSpy.calls.count()).toBe(1);
component.siteChanged(<SiteEntry> { entry: { guid: '-sites-' } }); component.siteChanged({ entry: { guid: '-sites-' } } as SiteEntry);
const expectedQueryBodyWithSiteChange = mockQueryBody; const expectedQueryBodyWithSiteChange = mockQueryBody;
expectedQueryBodyWithSiteChange.filterQueries = [ expectedQueryBodyWithSiteChange.filterQueries = [
@@ -555,26 +553,26 @@ describe('ContentNodeSelectorPanelComponent', () => {
tick(debounceSearch); tick(debounceSearch);
component.siteChanged(<SiteEntry> { entry: { guid: '-sites-' } }); component.siteChanged({ entry: { guid: '-sites-' } } as SiteEntry);
expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(1, 'getCorrespondingNodeIdsSpy calls count should be one after the site changes to known alias \'-sites\-'); expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(1, 'getCorrespondingNodeIdsSpy calls count should be one after the site changes to known alias \'-sites\-');
expect(getCorrespondingNodeIdsSpy.calls.mostRecent().args[0]).toEqual('-sites-'); expect(getCorrespondingNodeIdsSpy.calls.mostRecent().args[0]).toEqual('-sites-');
})); }));
it('should get the corresponding node ids on search when a known alias is selected from CUSTOM dropdown', fakeAsync(() => { it('should get the corresponding node ids on search when a known alias is selected from CUSTOM dropdown', fakeAsync(() => {
component.dropdownSiteList = <SitePaging> { list: { entries: [<SiteEntry> { entry: { guid: '-sites-' } }, <SiteEntry> { entry: { guid: 'namek' } }] } }; component.dropdownSiteList = { list: { entries: [{ entry: { guid: '-sites-' } }, { entry: { guid: 'namek' } }] } } as SitePaging;
fixture.detectChanges(); fixture.detectChanges();
typeToSearchBox('vegeta'); typeToSearchBox('vegeta');
tick(debounceSearch); tick(debounceSearch);
component.siteChanged(<SiteEntry> { entry: { guid: '-sites-' } }); component.siteChanged({ entry: { guid: '-sites-' } } as SiteEntry);
expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(1); expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(1);
expect(getCorrespondingNodeIdsSpy.calls.mostRecent().args[0]).toEqual('-sites-'); expect(getCorrespondingNodeIdsSpy.calls.mostRecent().args[0]).toEqual('-sites-');
})); }));
it('should NOT get the corresponding node ids on search when NOTHING is selected from dropdown', fakeAsync(() => { it('should NOT get the corresponding node ids on search when NOTHING is selected from dropdown', fakeAsync(() => {
component.dropdownSiteList = <SitePaging> { list: { entries: [<SiteEntry> { entry: { guid: '-sites-' } }, <SiteEntry> { entry: { guid: 'namek' } }] } }; component.dropdownSiteList = { list: { entries: [{ entry: { guid: '-sites-' } }, { entry: { guid: 'namek' } }] } } as SitePaging;
fixture.detectChanges(); fixture.detectChanges();
typeToSearchBox('vegeta'); typeToSearchBox('vegeta');
@@ -590,13 +588,13 @@ describe('ContentNodeSelectorPanelComponent', () => {
expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(0, 'getCorrespondingNodeIdsSpy should not be called'); expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(0, 'getCorrespondingNodeIdsSpy should not be called');
component.siteChanged(<SiteEntry> { entry: { guid: 'namek' } }); component.siteChanged({ entry: { guid: 'namek' } } as SiteEntry);
expect(getCorrespondingNodeIdsSpy).not.toHaveBeenCalled(); expect(getCorrespondingNodeIdsSpy).not.toHaveBeenCalled();
})); }));
it('should NOT get the corresponding node ids on search when NO known alias is selected from CUSTOM dropdown', fakeAsync(() => { it('should NOT get the corresponding node ids on search when NO known alias is selected from CUSTOM dropdown', fakeAsync(() => {
component.dropdownSiteList = <SitePaging> { list: { entries: [<SiteEntry> { entry: { guid: '-sites-' } }, <SiteEntry> { entry: { guid: 'namek' } }] } }; component.dropdownSiteList = { list: { entries: [{ entry: { guid: '-sites-' } }, { entry: { guid: 'namek' } }] } } as SitePaging;
fixture.detectChanges(); fixture.detectChanges();
typeToSearchBox('vegeta'); typeToSearchBox('vegeta');
@@ -604,7 +602,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(0, 'getCorrespondingNodeIdsSpy should not be called'); expect(getCorrespondingNodeIdsSpy.calls.count()).toBe(0, 'getCorrespondingNodeIdsSpy should not be called');
component.siteChanged(<SiteEntry> { entry: { guid: 'namek' } }); component.siteChanged({ entry: { guid: 'namek' } } as SiteEntry);
expect(getCorrespondingNodeIdsSpy).not.toHaveBeenCalled(); expect(getCorrespondingNodeIdsSpy).not.toHaveBeenCalled();
})); }));
@@ -730,7 +728,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
component.queryBuilderService.userQuery = 'search-term*'; component.queryBuilderService.userQuery = 'search-term*';
component.currentFolderId = 'my-root-id'; component.currentFolderId = 'my-root-id';
component.restrictRootToCurrentFolderId = true; component.restrictRootToCurrentFolderId = true;
component.siteChanged(<SiteEntry> { entry: { guid: 'my-site-id' } }); component.siteChanged({ entry: { guid: 'my-site-id' } } as SiteEntry);
const expectedQueryBodyWithSiteChange = mockQueryBody; const expectedQueryBodyWithSiteChange = mockQueryBody;
expectedQueryBodyWithSiteChange.filterQueries = [ expectedQueryBodyWithSiteChange.filterQueries = [
@@ -799,7 +797,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
expect(searchSpy.calls.count()).toBe(1); expect(searchSpy.calls.count()).toBe(1);
component.siteChanged(<SiteEntry> { entry: { guid: 'namek' } }); component.siteChanged({ entry: { guid: 'namek' } } as SiteEntry);
expect(searchSpy.calls.count()).toBe(2); expect(searchSpy.calls.count()).toBe(2);
@@ -833,14 +831,14 @@ describe('ContentNodeSelectorPanelComponent', () => {
}) })
} }
})) }))
.toBe(filter(<ShareDataRow> { .toBe(filter({
node: { node: {
entry: new Node({ entry: new Node({
name: 'impossible-name', name: 'impossible-name',
id: 'name' id: 'name'
}) })
} }
})); } as ShareDataRow));
}); });
it('should pass through the excludeSiteContent to the rowFilter of the documentList', () => { it('should pass through the excludeSiteContent to the rowFilter of the documentList', () => {
@@ -853,7 +851,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
expect(documentList.componentInstance.rowFilter).toBeTruthy('Document list should have had a rowFilter'); expect(documentList.componentInstance.rowFilter).toBeTruthy('Document list should have had a rowFilter');
const testSiteContent = new Node({ id: 'blog-id', properties: { 'st:componentId': 'blog' } }); const testSiteContent = new Node({ id: 'blog-id', properties: { 'st:componentId': 'blog' } });
expect(documentList.componentInstance.rowFilter(<any> { node: { entry: testSiteContent } }, null, null)) expect(documentList.componentInstance.rowFilter({ node: { entry: testSiteContent } }, null, null))
.toBe(false); .toBe(false);
}); });
@@ -948,13 +946,13 @@ describe('ContentNodeSelectorPanelComponent', () => {
})); }));
it('should set the folderIdToShow to the default "currentFolderId" if siteId is undefined', (done) => { it('should set the folderIdToShow to the default "currentFolderId" if siteId is undefined', (done) => {
component.siteChanged(<SiteEntry> { entry: { guid: 'Kame-Sennin Muten Roshi' } }); component.siteChanged({ entry: { guid: 'Kame-Sennin Muten Roshi' } } as SiteEntry);
fixture.detectChanges(); fixture.detectChanges();
let documentList = fixture.debugElement.query(By.css('[data-automation-id="content-node-selector-document-list"]')); let documentList = fixture.debugElement.query(By.css('[data-automation-id="content-node-selector-document-list"]'));
expect(documentList.componentInstance.currentFolderId).toBe('Kame-Sennin Muten Roshi'); expect(documentList.componentInstance.currentFolderId).toBe('Kame-Sennin Muten Roshi');
component.siteChanged(<SiteEntry> { entry: { guid: undefined } }); component.siteChanged({ entry: { guid: undefined } } as SiteEntry);
fixture.detectChanges(); fixture.detectChanges();
documentList = fixture.debugElement.query(By.css('[data-automation-id="content-node-selector-document-list"]')); documentList = fixture.debugElement.query(By.css('[data-automation-id="content-node-selector-document-list"]'));
@@ -1035,18 +1033,16 @@ describe('ContentNodeSelectorPanelComponent', () => {
describe('Chosen node', () => { describe('Chosen node', () => {
const entry: Node = <Node> { id: 'fakeid'}; const entry: Node = { id: 'fakeid'} as Node;
const nodePage: NodePaging = <NodePaging> { list: { pagination: {} } }; const nodePage: NodePaging = { list: { pagination: {} } };
let hasAllowableOperations; let hasAllowableOperations;
const fakeFolderNode = <Node> { id: 'fakeNodeId', isFolder: true }; const fakeFolderNode = { id: 'fakeNodeId', isFolder: true } as Node;
function returnHasPermission(): boolean { const returnHasPermission = (): boolean => hasAllowableOperations;
return hasAllowableOperations;
}
beforeEach(() => { beforeEach(() => {
const schema = [<DataColumn> {}]; const schema = [{}] as DataColumn[];
const rows = [<DataRow> {}, <DataRow> {}]; const rows = [{}, {}] as DataRow[];
component.documentList.data = new ShareDataTableAdapter(thumbnailService, contentService, schema); component.documentList.data = new ShareDataTableAdapter(thumbnailService, contentService, schema);
spyOn(component.documentList.data, 'getRows').and.returnValue(rows); spyOn(component.documentList.data, 'getRows').and.returnValue(rows);
spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } }))); spyOn(sitesService, 'getSites').and.returnValue(of(new SitePaging({ list: { entries: [] } })));
@@ -1186,7 +1182,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
it('should be empty when the chosenNode is reset', async () => { it('should be empty when the chosenNode is reset', async () => {
hasAllowableOperations = true; hasAllowableOperations = true;
component.onCurrentSelection([{ entry: <Node> {} }]); component.onCurrentSelection([{ entry: {} as Node }]);
component.select.subscribe((nodes) => { component.select.subscribe((nodes) => {
expect(nodes).toBeDefined(); expect(nodes).toBeDefined();
@@ -1235,7 +1231,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
it('should be null when the chosenNode is reset', async () => { it('should be null when the chosenNode is reset', async () => {
fixture.detectChanges(); fixture.detectChanges();
component.onCurrentSelection([{ entry: <Node> {} }]); component.onCurrentSelection([{ entry: {} as Node }]);
component.select.subscribe((nodes) => { component.select.subscribe((nodes) => {
expect(nodes).toBeDefined(); expect(nodes).toBeDefined();
@@ -1272,7 +1268,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
it('should be null when the chosenNode is reset', async () => { it('should be null when the chosenNode is reset', async () => {
fixture.detectChanges(); fixture.detectChanges();
component.onCurrentSelection([{ entry: <Node> {} }]); component.onCurrentSelection([{ entry: {} as Node }]);
component.select.subscribe((nodes) => { component.select.subscribe((nodes) => {
expect(nodes).toBeDefined(); expect(nodes).toBeDefined();
@@ -1303,7 +1299,7 @@ describe('ContentNodeSelectorPanelComponent', () => {
const isUploadingSpy = spyOn(uploadService, 'isUploading').and.returnValue(true); const isUploadingSpy = spyOn(uploadService, 'isUploading').and.returnValue(true);
const documentListReloadSpy = spyOn(component.documentList, 'reloadWithoutResettingSelection'); const documentListReloadSpy = spyOn(component.documentList, 'reloadWithoutResettingSelection');
const fakeFileModels = [new FileModel(<File> { name: 'fake-name', size: 100 }), new FileModel(<File> { name: 'fake-name-2', size: 200 })]; const fakeFileModels = [new FileModel({ name: 'fake-name', size: 100 } as File), new FileModel({ name: 'fake-name-2', size: 200 } as File)];
const fileUploadCompleteEvent = new FileUploadCompleteEvent(fakeFileModels[0], 1, fakeFileModels[0], 0); const fileUploadCompleteEvent = new FileUploadCompleteEvent(fakeFileModels[0], 1, fakeFileModels[0], 0);
uploadService.fileUploadComplete.next(fileUploadCompleteEvent); uploadService.fileUploadComplete.next(fileUploadCompleteEvent);
@@ -1330,8 +1326,8 @@ describe('ContentNodeSelectorPanelComponent', () => {
const documentListUnselectRowSpy = spyOn(component.documentList, 'unselectRowFromNodeId'); const documentListUnselectRowSpy = spyOn(component.documentList, 'unselectRowFromNodeId');
const documentListReloadSpy = spyOn(component.documentList, 'reloadWithoutResettingSelection'); const documentListReloadSpy = spyOn(component.documentList, 'reloadWithoutResettingSelection');
const fakeFileModel = new FileModel(<File> { name: 'fake-name', size: 10000000 }); const fakeFileModel = new FileModel({ name: 'fake-name', size: 10000000 } as File);
const fakeNodes = [<Node> { id: 'fakeNodeId' }, <Node> { id: 'fakeNodeId2' }]; const fakeNodes = [{ id: 'fakeNodeId' }, { id: 'fakeNodeId2' }] as Node[];
fakeFileModel.data = { entry: fakeNodes[0] }; fakeFileModel.data = { entry: fakeNodes[0] };
fakeFileModel.status = FileUploadStatus.Deleted; fakeFileModel.status = FileUploadStatus.Deleted;
@@ -62,7 +62,7 @@ export const defaultValidation = () => true;
templateUrl: './content-node-selector-panel.component.html', templateUrl: './content-node-selector-panel.component.html',
styleUrls: ['./content-node-selector-panel.component.scss'], styleUrls: ['./content-node-selector-panel.component.scss'],
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,
host: { 'class': 'adf-content-node-selector-panel' }, host: { class: 'adf-content-node-selector-panel' },
providers: [{ providers: [{
provide: SEARCH_QUERY_SERVICE_TOKEN, provide: SEARCH_QUERY_SERVICE_TOKEN,
useClass: SearchQueryBuilderService useClass: SearchQueryBuilderService
@@ -70,6 +70,7 @@ export const defaultValidation = () => true;
}) })
export class ContentNodeSelectorPanelComponent implements OnInit, OnDestroy { export class ContentNodeSelectorPanelComponent implements OnInit, OnDestroy {
// eslint-disable-next-line @typescript-eslint/naming-convention
DEFAULT_PAGINATION: Pagination = new Pagination({ DEFAULT_PAGINATION: Pagination = new Pagination({
maxItems: 25, maxItems: 25,
skipCount: 0 skipCount: 0
@@ -418,10 +419,8 @@ export class ContentNodeSelectorPanelComponent implements OnInit, OnDestroy {
if (!filter) { if (!filter) {
filter = () => true; filter = () => true;
} }
this._rowFilter = (value: ShareDataRow, index: number, array: ShareDataRow[]) => { this._rowFilter = (value: ShareDataRow, index: number, array: ShareDataRow[]) => filter(value, index, array) &&
return filter(value, index, array) &&
!this.isExcludedSiteContent(value); !this.isExcludedSiteContent(value);
};
} }
private isExcludedSiteContent(row: ShareDataRow): boolean { private isExcludedSiteContent(row: ShareDataRow): boolean {
@@ -26,7 +26,6 @@ import { of } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module'; import { ContentTestingModule } from '../testing/content.testing.module';
import { DocumentListService } from '../document-list/services/document-list.service'; import { DocumentListService } from '../document-list/services/document-list.service';
import { DocumentListComponent } from '../document-list/components/document-list.component'; import { DocumentListComponent } from '../document-list/components/document-list.component';
import { ShareDataRow } from '../document-list';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { UploadModule } from '../upload'; import { UploadModule } from '../upload';
import { ContentNodeSelectorPanelComponent } from './content-node-selector-panel.component'; import { ContentNodeSelectorPanelComponent } from './content-node-selector-panel.component';
@@ -111,19 +110,19 @@ describe('ContentNodeSelectorComponent', () => {
fixture.destroy(); fixture.destroy();
}); });
function enableLocalUpload() { const enableLocalUpload = () => {
component.data.showLocalUploadButton = true; component.data.showLocalUploadButton = true;
component.hasAllowableOperations = true; component.hasAllowableOperations = true;
component.showingSearch = false; component.showingSearch = false;
component.isLoading = false; component.isLoading = false;
} };
function selectTabByIndex(tabIndex: number) { const selectTabByIndex = (tabIndex: number) => {
const uploadFromLocalTab = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[tabIndex]; const uploadFromLocalTab = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[tabIndex];
const attributes = uploadFromLocalTab.nativeNode.attributes as NamedNodeMap; const attributes = uploadFromLocalTab.nativeNode.attributes as NamedNodeMap;
const tabPositionInSet = Number(attributes.getNamedItem('aria-posinset').value) - 1; const tabPositionInSet = Number(attributes.getNamedItem('aria-posinset').value) - 1;
component.onTabSelectionChange(tabPositionInSet); component.onTabSelectionChange(tabPositionInSet);
} };
describe('Data injecting with the "Material dialog way"', () => { describe('Data injecting with the "Material dialog way"', () => {
@@ -157,7 +156,7 @@ describe('ContentNodeSelectorComponent', () => {
}) })
} }
})) }))
.toBe(data.rowFilter(<ShareDataRow> { .toBe(data.rowFilter({
node: { node: {
entry: new Node({ entry: new Node({
name: 'impossible-name', name: 'impossible-name',
@@ -433,7 +432,7 @@ describe('ContentNodeSelectorComponent', () => {
}); });
it('should uploadStarted become true when the first upload gets started', () => { it('should uploadStarted become true when the first upload gets started', () => {
const fileUploadEvent = new FileUploadEvent(new FileModel(<File> { name: 'fake-name', size: 100 })); const fileUploadEvent = new FileUploadEvent(new FileModel({ name: 'fake-name', size: 100 } as File));
uploadService.fileUploadStarting.next(fileUploadEvent); uploadService.fileUploadStarting.next(fileUploadEvent);
expect(component.uploadStarted).toBe(true); expect(component.uploadStarted).toBe(true);
@@ -35,8 +35,8 @@ describe('NameLocationCellComponent', () => {
fixture = TestBed.createComponent(NameLocationCellComponent); fixture = TestBed.createComponent(NameLocationCellComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
rowData = <DataRow> { rowData = {
getValue(key): any { getValue: (key): any => {
if (key === 'name') { if (key === 'name') {
return 'file-name'; return 'file-name';
} else if (key === 'path') { } else if (key === 'path') {
@@ -44,7 +44,7 @@ describe('NameLocationCellComponent', () => {
} }
return undefined; return undefined;
} }
}; } as DataRow;
component.row = rowData; component.row = rowData;
fixture.detectChanges(); fixture.detectChanges();
}); });
@@ -84,7 +84,7 @@ describe('Content Type Dialog Component', () => {
let data: ContentTypeDialogComponentData; let data: ContentTypeDialogComponentData;
beforeEach(async () => { beforeEach(async () => {
data = <ContentTypeDialogComponentData> { data = {
title: 'Title', title: 'Title',
description: 'Description that can be longer or shorter', description: 'Description that can be longer or shorter',
nodeType: 'fk:fakeNode', nodeType: 'fk:fakeNode',
@@ -32,7 +32,7 @@ export interface ConfirmDialogComponentProps {
selector: 'adf-confirm-dialog', selector: 'adf-confirm-dialog',
templateUrl: './confirm.dialog.html', templateUrl: './confirm.dialog.html',
styleUrls: ['./confirm.dialog.scss'], styleUrls: ['./confirm.dialog.scss'],
host: { 'class': 'adf-confirm-dialog' }, host: { class: 'adf-confirm-dialog' },
encapsulation: ViewEncapsulation.None encapsulation: ViewEncapsulation.None
}) })
export class ConfirmDialogComponent { export class ConfirmDialogComponent {
@@ -19,27 +19,27 @@ import { FormControl } from '@angular/forms';
const I18N_ERRORS_PATH = 'CORE.FOLDER_DIALOG.FOLDER_NAME.ERRORS'; const I18N_ERRORS_PATH = 'CORE.FOLDER_DIALOG.FOLDER_NAME.ERRORS';
export function forbidSpecialCharacters({ value }: FormControl) { export const forbidSpecialCharacters = ({ value }: FormControl) => {
const specialCharacters: RegExp = /([\*\"\<\>\\\/\?\:\|])/; const specialCharacters: RegExp = /([\*\"\<\>\\\/\?\:\|])/;
const isValid: boolean = !specialCharacters.test(value); const isValid: boolean = !specialCharacters.test(value);
return (isValid) ? null : { return (isValid) ? null : {
message: `${I18N_ERRORS_PATH}.SPECIAL_CHARACTERS` message: `${I18N_ERRORS_PATH}.SPECIAL_CHARACTERS`
}; };
} };
export function forbidEndingDot({ value }: FormControl) { export const forbidEndingDot = ({ value }: FormControl) => {
const isValid: boolean = ((value || '').trim().split('').pop() !== '.'); const isValid: boolean = ((value || '').trim().split('').pop() !== '.');
return isValid ? null : { return isValid ? null : {
message: `${I18N_ERRORS_PATH}.ENDING_DOT` message: `${I18N_ERRORS_PATH}.ENDING_DOT`
}; };
} };
export function forbidOnlySpaces({ value }: FormControl) { export const forbidOnlySpaces = ({ value }: FormControl) => {
const isValid: boolean = !!((value || '')).trim(); const isValid: boolean = !!((value || '')).trim();
return isValid ? null : { return isValid ? null : {
message: `${I18N_ERRORS_PATH}.ONLY_SPACES` message: `${I18N_ERRORS_PATH}.ONLY_SPACES`
}; };
} };
@@ -60,9 +60,7 @@ describe('LibraryDialogComponent', () => {
it('should set library id automatically on title input', fakeAsync(() => { it('should set library id automatically on title input', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('libraryTitle'); component.form.controls.title.setValue('libraryTitle');
@@ -75,9 +73,7 @@ describe('LibraryDialogComponent', () => {
it('should translate library title space character to dash for library id', fakeAsync(() => { it('should translate library title space character to dash for library id', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('library title'); component.form.controls.title.setValue('library title');
@@ -90,9 +86,7 @@ describe('LibraryDialogComponent', () => {
it('should not change custom library id on title input', fakeAsync(() => { it('should not change custom library id on title input', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.id.setValue('custom-id'); component.form.controls.id.setValue('custom-id');
@@ -129,9 +123,7 @@ describe('LibraryDialogComponent', () => {
spyOn(sitesService, 'createSite').and.returnValue( spyOn(sitesService, 'createSite').and.returnValue(
of({entry: {id: 'fake-id'}} as SiteEntry).pipe(delay(100)) of({entry: {id: 'fake-id'}} as SiteEntry).pipe(delay(100))
); );
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('library title'); component.form.controls.title.setValue('library title');
@@ -196,12 +188,8 @@ describe('LibraryDialogComponent', () => {
it('should notify on 409 conflict error (might be in trash)', fakeAsync(() => { it('should notify on 409 conflict error (might be in trash)', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
const error = { message: '{ "error": { "statusCode": 409 } }' }; const error = { message: '{ "error": { "statusCode": 409 } }' };
spyOn(sitesService, 'createSite').and.callFake(() => { spyOn(sitesService, 'createSite').and.callFake(() => throwError(error));
return throwError(error); spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
});
spyOn(sitesService, 'getSite').and.callFake(() => {
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('test'); component.form.controls.title.setValue('test');
@@ -220,9 +208,7 @@ describe('LibraryDialogComponent', () => {
it('should not translate library title if value is not a valid id', fakeAsync(() => { it('should not translate library title if value is not a valid id', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('@@@####'); component.form.controls.title.setValue('@@@####');
@@ -235,9 +221,7 @@ describe('LibraryDialogComponent', () => {
it('should translate library title partially for library id', fakeAsync(() => { it('should translate library title partially for library id', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('@@@####library'); component.form.controls.title.setValue('@@@####library');
@@ -250,9 +234,7 @@ describe('LibraryDialogComponent', () => {
it('should translate library title multiple space character to one dash for library id', fakeAsync(() => { it('should translate library title multiple space character to one dash for library id', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('library title'); component.form.controls.title.setValue('library title');
@@ -265,9 +247,7 @@ describe('LibraryDialogComponent', () => {
it('should invalidate library title if is too short', fakeAsync(() => { it('should invalidate library title if is too short', fakeAsync(() => {
findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse)); findSitesSpy.and.returnValue(Promise.resolve(findSitesResponse));
spyOn(sitesService, 'getSite').and.callFake(() => { spyOn(sitesService, 'getSite').and.callFake(() => throwError('error'));
return throwError('error');
});
fixture.detectChanges(); fixture.detectChanges();
component.form.controls.title.setValue('l'); component.form.controls.title.setValue('l');
@@ -177,12 +177,12 @@ export class LibraryDialogComponent implements OnInit, OnDestroy {
private create(): Observable<SiteEntry> { private create(): Observable<SiteEntry> {
const { title, id, description, visibility } = this; const { title, id, description, visibility } = this;
const siteBody = <SiteBodyCreate> { const siteBody = {
id, id,
title, title,
description, description,
visibility visibility
}; } as SiteBodyCreate;
return this.sitesService.createSite(siteBody); return this.sitesService.createSite(siteBody);
} }
@@ -206,8 +206,7 @@ export class LibraryDialogComponent implements OnInit, OnDestroy {
message: 'LIBRARY.ERRORS.CONFLICT' message: 'LIBRARY.ERRORS.CONFLICT'
}); });
} }
} catch (error) { } catch {
} }
return error; return error;
@@ -274,12 +273,10 @@ export class LibraryDialogComponent implements OnInit, OnDestroy {
} }
return new Promise((resolve) => { return new Promise((resolve) => {
timer = setTimeout(() => { timer = setTimeout(() => this.sitesService.getSite(control.value).subscribe(
return this.sitesService.getSite(control.value).subscribe(
() => resolve({ message: 'LIBRARY.ERRORS.EXISTENT_SITE' }), () => resolve({ message: 'LIBRARY.ERRORS.EXISTENT_SITE' }),
() => resolve(null) () => resolve(null)
); ), 300);
}, 300);
}); });
}; };
} }
@@ -74,9 +74,9 @@ export class NodeLockDialogComponent implements OnInit {
private get nodeBodyLock(): NodeBodyLock { private get nodeBodyLock(): NodeBodyLock {
return new NodeBodyLock({ return new NodeBodyLock({
'timeToExpire': this.lockTimeInSeconds, timeToExpire: this.lockTimeInSeconds,
'type': this.form.value.allowOwner ? 'ALLOW_OWNER_CHANGES' : 'FULL', type: this.form.value.allowOwner ? 'ALLOW_OWNER_CHANGES' : 'FULL',
'lifetime': 'PERSISTENT' lifetime: 'PERSISTENT'
}); });
} }
@@ -26,11 +26,11 @@ import { setupTestBed } from '@alfresco/adf-core';
import { ContentTestingModule } from '../testing/content.testing.module'; import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
const fakeNode: Node = <Node> { const fakeNode = {
id: 'fake', id: 'fake',
isFile: true, isFile: true,
isLocked: false isLocked: false
}; } as Node;
@Component({ @Component({
template: '<div [adf-node-lock]="node"></div>' template: '<div [adf-node-lock]="node"></div>'
@@ -33,6 +33,7 @@ export class ContentActionListComponent {
/** /**
* Registers action handler within the parent document list component. * Registers action handler within the parent document list component.
*
* @param action Action model to register. * @param action Action model to register.
*/ */
registerAction(action: ContentActionModel): boolean { registerAction(action: ContentActionModel): boolean {
@@ -94,16 +94,14 @@ describe('ContentAction', () => {
action.visible = false; action.visible = false;
action.ngOnChanges({ action.ngOnChanges({
'visible': new SimpleChange(true, false, false) visible: new SimpleChange(true, false, false)
}); });
expect(action.documentActionModel.visible).toBeFalsy(); expect(action.documentActionModel.visible).toBeFalsy();
}); });
it('should get action handler from document actions service', () => { it('should get action handler from document actions service', () => {
const handler = () => {};
const handler = function () {
};
spyOn(documentActions, 'getHandler').and.returnValue(handler); spyOn(documentActions, 'getHandler').and.returnValue(handler);
const action = new ContentActionComponent(actionList, documentActions, null); const action = new ContentActionComponent(actionList, documentActions, null);
@@ -119,8 +117,7 @@ describe('ContentAction', () => {
}); });
it('should get action handler from folder actions service', () => { it('should get action handler from folder actions service', () => {
const handler = function () { const handler = () => {};
};
spyOn(folderActions, 'getHandler').and.returnValue(handler); spyOn(folderActions, 'getHandler').and.returnValue(handler);
const action = new ContentActionComponent(actionList, null, folderActions); const action = new ContentActionComponent(actionList, null, folderActions);
@@ -163,7 +163,7 @@ export class ContentActionComponent implements OnInit, OnChanges, OnDestroy {
icon: this.icon, icon: this.icon,
permission: this.permission, permission: this.permission,
disableWithNoPermission: this.disableWithNoPermission, disableWithNoPermission: this.disableWithNoPermission,
target: target, target,
disabled: this.disabled, disabled: this.disabled,
visible: this.visible visible: this.visible
}); });
@@ -86,8 +86,7 @@ describe('DocumentList', () => {
beforeEach(() => { beforeEach(() => {
eventMock = { eventMock = {
preventDefault: function () { preventDefault: () => {}
}
}; };
fixture = TestBed.createComponent(DocumentListComponent); fixture = TestBed.createComponent(DocumentListComponent);
@@ -237,7 +236,7 @@ describe('DocumentList', () => {
const resetSelectionSpy = spyOn(documentList, 'resetSelection').and.callThrough(); const resetSelectionSpy = spyOn(documentList, 'resetSelection').and.callThrough();
documentList.selection = [{ entry: mockNode3 }]; documentList.selection = [{ entry: mockNode3 }];
const changes: SimpleChanges = { const changes: SimpleChanges = {
'preselectNodes': { preselectNodes: {
previousValue: undefined, previousValue: undefined,
currentValue: mockPreselectedNodes, currentValue: mockPreselectedNodes,
firstChange: true, firstChange: true,
@@ -256,7 +255,7 @@ describe('DocumentList', () => {
const resetSelectionSpy = spyOn(documentList, 'resetSelection').and.callThrough(); const resetSelectionSpy = spyOn(documentList, 'resetSelection').and.callThrough();
documentList.selection = [{ entry: mockNode3 }]; documentList.selection = [{ entry: mockNode3 }];
const changes: SimpleChanges = { const changes: SimpleChanges = {
'mockChange': { mockChange: {
previousValue: undefined, previousValue: undefined,
currentValue: ['mockChangeValue'], currentValue: ['mockChangeValue'],
firstChange: true, firstChange: true,
@@ -303,14 +302,14 @@ describe('DocumentList', () => {
it('should add the custom columns', () => { it('should add the custom columns', () => {
fixture.detectChanges(); fixture.detectChanges();
const column = <DataColumn> { const column = {
title: 'title', title: 'title',
key: 'source', key: 'source',
cssClass: 'css', cssClass: 'css',
srTitle: '', srTitle: '',
type: 'text', type: 'text',
format: '' format: ''
}; } as DataColumn;
const columns = documentList.data.getColumns(); const columns = documentList.data.getColumns();
columns.push(column); columns.push(column);
@@ -456,8 +455,7 @@ describe('DocumentList', () => {
it('should not execute action without node provided', () => { it('should not execute action without node provided', () => {
const action = new ContentActionModel(); const action = new ContentActionModel();
action.handler = function () { action.handler = () => {};
};
spyOn(action, 'handler').and.stub(); spyOn(action, 'handler').and.stub();
documentList.executeContentAction(null, action); documentList.executeContentAction(null, action);
@@ -1167,7 +1165,7 @@ describe('DocumentList', () => {
it('should set row filter and reload contents if currentFolderId is set when setting rowFilter', () => { it('should set row filter and reload contents if currentFolderId is set when setting rowFilter', () => {
fixture.detectChanges(); fixture.detectChanges();
const filter = <RowFilter> {}; const filter = {} as RowFilter;
documentList.currentFolderId = 'id'; documentList.currentFolderId = 'id';
spyOn(documentList.data, 'setFilter').and.callThrough(); spyOn(documentList.data, 'setFilter').and.callThrough();
@@ -1181,14 +1179,14 @@ describe('DocumentList', () => {
spyFolder.calls.reset(); spyFolder.calls.reset();
documentList.currentFolderId = null; documentList.currentFolderId = null;
documentList.ngOnChanges({ rowFilter: new SimpleChange(null, <RowFilter> {}, true) }); documentList.ngOnChanges({ rowFilter: new SimpleChange(null, {} as RowFilter, true) });
expect(spyFolder).not.toHaveBeenCalled(); expect(spyFolder).not.toHaveBeenCalled();
}); });
it('should set image resolver for underlying adapter', () => { it('should set image resolver for underlying adapter', () => {
fixture.detectChanges(); fixture.detectChanges();
const resolver = <ImageResolver> {}; const resolver = {} as ImageResolver;
spyOn(documentList.data, 'setImageResolver').and.callThrough(); spyOn(documentList.data, 'setImageResolver').and.callThrough();
documentList.ngOnChanges({ imageResolver: new SimpleChange(null, resolver, true) }); documentList.ngOnChanges({ imageResolver: new SimpleChange(null, resolver, true) });
@@ -1324,9 +1322,7 @@ describe('DocumentList', () => {
}); });
it('should allow to perform navigation for virtual sources', () => { it('should allow to perform navigation for virtual sources', () => {
spyFolderNode = spyOn(documentListService, 'loadFolderByNodeId').and.callFake(() => { spyFolderNode = spyOn(documentListService, 'loadFolderByNodeId').and.callFake(() => of(new DocumentLoaderNode(null, { list: { pagination: {} } })));
return of(new DocumentLoaderNode(null, { list: { pagination: {} } }));
});
const sources = ['-trashcan-', '-sharedlinks-', '-sites-', '-mysites-', '-favorites-', '-recent-']; const sources = ['-trashcan-', '-sharedlinks-', '-sites-', '-mysites-', '-favorites-', '-recent-'];
const node = new FolderNode('folder'); const node = new FolderNode('folder');
@@ -1725,18 +1721,18 @@ describe('DocumentList', () => {
const fakeDatatableRows = [new ShareDataRow(mockPreselectedNodes[0], contentService, null), new ShareDataRow(mockPreselectedNodes[1], contentService, null)]; const fakeDatatableRows = [new ShareDataRow(mockPreselectedNodes[0], contentService, null), new ShareDataRow(mockPreselectedNodes[1], contentService, null)];
fakeDatatableRows[0].isSelected = true; fakeDatatableRows[0].isSelected = true;
documentList.data.setRows(fakeDatatableRows); documentList.data.setRows(fakeDatatableRows);
let selectedRows = documentList.data.getSelectedRows(); let selection = documentList.data.getSelectedRows();
expect(selectedRows.length).toEqual(1); expect(selection.length).toEqual(1);
documentList.unselectRowFromNodeId(mockPreselectedNodes[0].entry.id); documentList.unselectRowFromNodeId(mockPreselectedNodes[0].entry.id);
selectedRows = documentList.data.getSelectedRows(); selection = documentList.data.getSelectedRows() as ShareDataRow[];
expect(selectedRows).toEqual([]); expect(selection).toEqual([]);
expect(getSelectionSpy).toHaveBeenCalled(); expect(getSelectionSpy).toHaveBeenCalled();
expect(getRowByNodeIdSpy).toHaveBeenCalledWith(mockPreselectedNodes[0].entry.id); expect(getRowByNodeIdSpy).toHaveBeenCalledWith(mockPreselectedNodes[0].entry.id);
expect(datatableSelectRowSpy).toHaveBeenCalledWith(fakeDatatableRows[0], false); expect(datatableSelectRowSpy).toHaveBeenCalledWith(fakeDatatableRows[0], false);
expect(onNodeUnselectSpy).toHaveBeenCalledWith({ row: undefined, selection: <ShareDataRow[]> selectedRows }); expect(onNodeUnselectSpy).toHaveBeenCalledWith({ row: undefined, selection });
}); });
it('should preselect the rows of the preselected nodes', () => { it('should preselect the rows of the preselected nodes', () => {
@@ -1782,16 +1778,16 @@ describe('DocumentList', () => {
documentList.selectionMode = 'multiple'; documentList.selectionMode = 'multiple';
documentList.preselectNodes = mockPreselectedNodes; documentList.preselectNodes = mockPreselectedNodes;
documentList.onPreselectNodes(); documentList.onPreselectNodes();
const selectedRows = documentList.data.getSelectedRows(); const selection = documentList.data.getSelectedRows() as ShareDataRow[];
expect(hasPreselectedNodesSpy).toHaveBeenCalled(); expect(hasPreselectedNodesSpy).toHaveBeenCalled();
expect(preselectRowsOfPreselectedNodesSpy).toHaveBeenCalled(); expect(preselectRowsOfPreselectedNodesSpy).toHaveBeenCalled();
expect(getPreselectedRowsBasedOnSelectionModeSpy).toHaveBeenCalled(); expect(getPreselectedRowsBasedOnSelectionModeSpy).toHaveBeenCalled();
expect(selectedRows.length).toEqual(3); expect(selection.length).toEqual(3);
expect(selectedRows[0].id).toEqual(mockNode1.id); expect(selection[0].id).toEqual(mockNode1.id);
expect(selectedRows[1].id).toEqual(mockNode2.id); expect(selection[1].id).toEqual(mockNode2.id);
expect(selectedRows[2].id).toEqual(mockNode3.id); expect(selection[2].id).toEqual(mockNode3.id);
expect(onNodeSelectSpy).toHaveBeenCalledWith({ row: undefined, selection: <ShareDataRow[]> selectedRows }); expect(onNodeSelectSpy).toHaveBeenCalledWith({ row: undefined, selection });
}); });
}); });
}); });
@@ -16,6 +16,7 @@
*/ */
/* eslint-disable rxjs/no-subject-value */ /* eslint-disable rxjs/no-subject-value */
/* eslint-disable @typescript-eslint/naming-convention */
import { import {
AfterContentInit, Component, ContentChild, ElementRef, EventEmitter, HostListener, Input, NgZone, AfterContentInit, Component, ContentChild, ElementRef, EventEmitter, HostListener, Input, NgZone,
@@ -371,13 +372,11 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
if (node && node.entry) { if (node && node.entry) {
const actions = this.getNodeActions(node); const actions = this.getNodeActions(node);
if (actions && actions.length > 0) { if (actions && actions.length > 0) {
return actions.map((currentAction: ContentActionModel) => { return actions.map((currentAction: ContentActionModel) => ({
return {
model: currentAction, model: currentAction,
node: node, node,
subject: this.contextActionHandler subject: this.contextActionHandler
}; }));
});
} }
} }
return null; return null;
@@ -447,7 +446,7 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
let schema: DataColumn[] = []; let schema: DataColumn[] = [];
if (this.hasCustomLayout) { if (this.hasCustomLayout) {
schema = this.columnList.columns.map((c) => <DataColumn> c); schema = this.columnList.columns.map((c) => c as DataColumn);
} }
if (!this.data) { if (!this.data) {
@@ -614,14 +613,14 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
if (typeof node === 'string') { if (typeof node === 'string') {
this.resetNewFolderPagination(); this.resetNewFolderPagination();
this.currentFolderId = node; this.currentFolderId = node;
this.folderChange.emit(new NodeEntryEvent(<Node> { id: node })); this.folderChange.emit(new NodeEntryEvent({ id: node } as Node));
this.reload(); this.reload();
return true; return true;
} else { } else {
if (this.canNavigateFolder(node)) { if (this.canNavigateFolder(node)) {
this.resetNewFolderPagination(); this.resetNewFolderPagination();
this.currentFolderId = this.getNodeFolderDestinationId(node); this.currentFolderId = this.getNodeFolderDestinationId(node);
this.folderChange.emit(new NodeEntryEvent(<Node> { id: this.currentFolderId })); this.folderChange.emit(new NodeEntryEvent({ id: this.currentFolderId } as Node));
this.reload(); this.reload();
return true; return true;
} }
@@ -644,6 +643,7 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
/** /**
* Invoked when executing content action for a document or folder. * Invoked when executing content action for a document or folder.
*
* @param node Node to be the context of the execution. * @param node Node to be the context of the execution.
* @param action Action to be executed against the context. * @param action Action to be executed against the context.
*/ */
@@ -845,7 +845,7 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
onShowRowContextMenu(event: DataCellEvent) { onShowRowContextMenu(event: DataCellEvent) {
if (this.contextMenuActions) { if (this.contextMenuActions) {
const args = event.value; const args = event.value;
const node = (<ShareDataRow> args.row).node; const node = args.row.node;
if (node) { if (node) {
args.actions = this.getContextActions(node) || []; args.actions = this.getContextActions(node) || [];
} }
@@ -855,7 +855,7 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
onShowRowActionsMenu(event: DataCellEvent) { onShowRowActionsMenu(event: DataCellEvent) {
if (this.contentActions) { if (this.contentActions) {
const args = event.value; const args = event.value;
const node = (<ShareDataRow> args.row).node; const node = args.row.node;
if (node) { if (node) {
args.actions = this.getNodeActions(node) || []; args.actions = this.getNodeActions(node) || [];
} }
@@ -865,8 +865,8 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
onExecuteRowAction(event: DataRowActionEvent) { onExecuteRowAction(event: DataRowActionEvent) {
if (this.contentActions) { if (this.contentActions) {
const args = event.value; const args = event.value;
const node = (<ShareDataRow> args.row).node; const node = args.row.node;
const action = (<ContentActionModel> args.action); const action = args.action;
this.executeContentAction(node, action); this.executeContentAction(node, action);
} }
} }
@@ -952,12 +952,12 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
if (this.hasPreselectedNodes()) { if (this.hasPreselectedNodes()) {
this.preselectRowsOfPreselectedNodes(); this.preselectRowsOfPreselectedNodes();
const preselectedRows = this.getPreselectedRowsBasedOnSelectionMode(); const preselectedRows = this.getPreselectedRowsBasedOnSelectionMode();
const selectedNodes = this.data.getSelectedRows(); const selection = this.data.getSelectedRows() as ShareDataRow[];
for (const node of preselectedRows) { for (const node of preselectedRows) {
this.dataTable.selectRow(node, true); this.dataTable.selectRow(node, true);
} }
this.onNodeSelect({ row: undefined, selection: <ShareDataRow[]> selectedNodes }); this.onNodeSelect({ row: undefined, selection });
} }
} }
@@ -990,8 +990,8 @@ export class DocumentListComponent implements OnInit, OnChanges, OnDestroy, Afte
if (rowToUnselect?.isSelected) { if (rowToUnselect?.isSelected) {
rowToUnselect.isSelected = false; rowToUnselect.isSelected = false;
this.dataTable.selectRow(rowToUnselect, false); this.dataTable.selectRow(rowToUnselect, false);
const selection = this.getSelectionBasedOnSelectionMode(); const selection = this.getSelectionBasedOnSelectionMode() as ShareDataRow[];
this.onNodeUnselect({ row: undefined, selection: <ShareDataRow[]> selection }); this.onNodeUnselect({ row: undefined, selection });
} }
} }
@@ -36,7 +36,7 @@ describe('FilterHeaderComponent', () => {
dataLoaded: new Subject() dataLoaded: new Subject()
}; };
const paginationMock = <Pagination> { maxItems: 10, skipCount: 0 }; const paginationMock = { maxItems: 10, skipCount: 0 };
const documentListMock = { const documentListMock = {
node: 'my-node', node: 'my-node',
@@ -36,7 +36,7 @@ describe('LibraryNameColumnComponent', () => {
}); });
beforeEach(() => { beforeEach(() => {
node = <any> { node = {
id: 'nodeId', id: 'nodeId',
path: { path: {
elements: [] elements: []
@@ -76,8 +76,8 @@ describe('LibraryNameColumnComponent', () => {
node.title = 'title'; node.title = 'title';
const rows = [ const rows = [
<any> { node: { entry: { id: 'some-id', title: 'title' } } } { node: { entry: { id: 'some-id', title: 'title' } } }
]; ] as any[];
const title = component.makeLibraryTitle(node, rows); const title = component.makeLibraryTitle(node, rows);
expect(title).toContain('nodeId'); expect(title).toContain('nodeId');
@@ -87,10 +87,10 @@ describe('LibraryNameColumnComponent', () => {
node.title = 'title'; node.title = 'title';
const rows = [ const rows = [
<any> { {
node: { entry: { id: 'some-id', title: 'title-some-id' } } node: { entry: { id: 'some-id', title: 'title-some-id' } }
} }
]; ] as any[];
const title = component.makeLibraryTitle(node, rows); const title = component.makeLibraryTitle(node, rows);
@@ -89,7 +89,7 @@ export class LibraryNameColumnComponent implements OnInit, OnDestroy {
const rows: Array<ShareDataRow> = this.context.data.rows || []; const rows: Array<ShareDataRow> = this.context.data.rows || [];
if (this.node && this.node.entry) { if (this.node && this.node.entry) {
this.displayText$.next( this.displayText$.next(
this.makeLibraryTitle(<any> this.node.entry, rows) this.makeLibraryTitle(this.node.entry as any, rows)
); );
this.displayTooltip$.next(this.makeLibraryTooltip(this.node.entry)); this.displayTooltip$.next(this.makeLibraryTooltip(this.node.entry));
} }
@@ -119,9 +119,7 @@ export class LibraryNameColumnComponent implements OnInit, OnDestroy {
let isDuplicate = false; let isDuplicate = false;
if (entries) { if (entries) {
isDuplicate = entries.some((entry: any) => { isDuplicate = entries.some((entry: any) => entry.id !== id && entry.title === title);
return entry.id !== id && entry.title === title;
});
} }
return isDuplicate ? `${title} (${id})` : `${title}`; return isDuplicate ? `${title} (${id})` : `${title}`;
@@ -39,9 +39,7 @@ describe('NameColumnComponent', () => {
context = { context = {
row: { row: {
node: {entry: {}}, node: {entry: {}},
getValue(key) { getValue: (key) => key
return key;
}
} }
}; };
@@ -75,9 +75,7 @@ export class TrashcanNameColumnComponent implements OnInit {
let isDuplicate = false; let isDuplicate = false;
if (entries) { if (entries) {
isDuplicate = entries.some((entry: any) => { isDuplicate = entries.some((entry: any) => entry.id !== id && entry.properties['cm:title'] === title);
return entry.id !== id && entry.properties['cm:title'] === title;
});
} }
return isDuplicate return isDuplicate
@@ -19,10 +19,9 @@ import { DataRow, ObjectUtils, ThumbnailService, ContentService } from '@alfresc
import { MinimalNode, NodeEntry } from '@alfresco/js-api'; import { MinimalNode, NodeEntry } from '@alfresco/js-api';
import { PermissionStyleModel } from './../models/permissions-style.model'; import { PermissionStyleModel } from './../models/permissions-style.model';
export const ERR_OBJECT_NOT_FOUND: string = 'Object source not found';
export class ShareDataRow implements DataRow { export class ShareDataRow implements DataRow {
static ERR_OBJECT_NOT_FOUND: string = 'Object source not found';
cache: { [key: string]: any } = {}; cache: { [key: string]: any } = {};
isSelected: boolean = false; isSelected: boolean = false;
isDropTarget: boolean; isDropTarget: boolean;
@@ -44,7 +43,7 @@ export class ShareDataRow implements DataRow {
private thumbnailService?: ThumbnailService, private thumbnailService?: ThumbnailService,
private allowDropFiles?: boolean) { private allowDropFiles?: boolean) {
if (!obj) { if (!obj) {
throw new Error(ShareDataRow.ERR_OBJECT_NOT_FOUND); throw new Error(ERR_OBJECT_NOT_FOUND);
} }
this.isDropTarget = allowDropFiles !== undefined ? this.allowDropFiles && this.checkNodeTypeAndPermissions(obj) : this.checkNodeTypeAndPermissions(obj); this.isDropTarget = allowDropFiles !== undefined ? this.allowDropFiles && this.checkNodeTypeAndPermissions(obj) : this.checkNodeTypeAndPermissions(obj);
@@ -17,8 +17,8 @@
import { DataColumn, DataRow, DataSorting, ContentService, ThumbnailService, setupTestBed } from '@alfresco/adf-core'; import { DataColumn, DataRow, DataSorting, ContentService, ThumbnailService, setupTestBed } from '@alfresco/adf-core';
import { FileNode, FolderNode, SmartFolderNode, RuleFolderNode, LinkFolderNode } from './../../mock'; import { FileNode, FolderNode, SmartFolderNode, RuleFolderNode, LinkFolderNode } from './../../mock';
import { ShareDataRow } from './share-data-row.model'; import { ERR_OBJECT_NOT_FOUND, ShareDataRow } from './share-data-row.model';
import { ShareDataTableAdapter } from './share-datatable-adapter'; import { ERR_COL_NOT_FOUND, ERR_ROW_NOT_FOUND, ShareDataTableAdapter } from './share-datatable-adapter';
import { ContentTestingModule } from '../../testing/content.testing.module'; import { ContentTestingModule } from '../../testing/content.testing.module';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
@@ -70,7 +70,7 @@ describe('ShareDataTableAdapter', () => {
}); });
it('should setup rows and columns with constructor', () => { it('should setup rows and columns with constructor', () => {
const schema = [<DataColumn> {}]; const schema = [{}] as DataColumn[];
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, schema); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, schema);
expect(adapter.getRows()).toEqual([]); expect(adapter.getRows()).toEqual([]);
@@ -83,14 +83,14 @@ describe('ShareDataTableAdapter', () => {
}); });
it('should set new columns', () => { it('should set new columns', () => {
const columns = [<DataColumn> {}, <DataColumn> {}]; const columns = [{}, {}] as DataColumn[];
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
adapter.setColumns(columns); adapter.setColumns(columns);
expect(adapter.getColumns()).toEqual(columns); expect(adapter.getColumns()).toEqual(columns);
}); });
it('should reset columns', () => { it('should reset columns', () => {
const columns = [<DataColumn> {}, <DataColumn> {}]; const columns = [{} as DataColumn, {} as DataColumn];
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, columns); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, columns);
expect(adapter.getColumns()).toEqual(columns); expect(adapter.getColumns()).toEqual(columns);
@@ -99,7 +99,7 @@ describe('ShareDataTableAdapter', () => {
}); });
it('should set new rows', () => { it('should set new rows', () => {
const rows = [<DataRow> {}, <DataRow> {}]; const rows = [{}, {}] as DataRow[];
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
expect(adapter.getRows()).toEqual([]); expect(adapter.getRows()).toEqual([]);
@@ -108,7 +108,7 @@ describe('ShareDataTableAdapter', () => {
}); });
it('should reset rows', () => { it('should reset rows', () => {
const rows = [<DataRow> {}, <DataRow> {}]; const rows = [{}, {}] as DataRow[];
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
adapter.setRows(rows); adapter.setRows(rows);
@@ -122,7 +122,7 @@ describe('ShareDataTableAdapter', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
spyOn(adapter, 'sort').and.callThrough(); spyOn(adapter, 'sort').and.callThrough();
const rows = [<DataRow> {}]; const rows = [{}] as DataRow[];
adapter.setRows(rows); adapter.setRows(rows);
expect(adapter.sort).toHaveBeenCalled(); expect(adapter.sort).toHaveBeenCalled();
@@ -130,18 +130,14 @@ describe('ShareDataTableAdapter', () => {
it('should fail when getting value for missing row', () => { it('should fail when getting value for missing row', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const check = () => { const check = () => adapter.getValue(null, {} as DataColumn);
return adapter.getValue(null, <DataColumn> {}); expect(check).toThrowError(ERR_ROW_NOT_FOUND);
};
expect(check).toThrowError(adapter.ERR_ROW_NOT_FOUND);
}); });
it('should fail when getting value for missing column', () => { it('should fail when getting value for missing column', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const check = () => { const check = () => adapter.getValue({} as DataRow, null);
return adapter.getValue(<DataRow> {}, null); expect(check).toThrowError(ERR_COL_NOT_FOUND);
};
expect(check).toThrowError(adapter.ERR_COL_NOT_FOUND);
}); });
it('should return date value as string', () => { it('should return date value as string', () => {
@@ -150,10 +146,10 @@ describe('ShareDataTableAdapter', () => {
const file = new FileNode(); const file = new FileNode();
file.entry.createdAt = rawValue; file.entry.createdAt = rawValue;
const col = <DataColumn> { const col = {
key: 'createdAt', key: 'createdAt',
type: 'text' type: 'text'
}; } as DataColumn;
const row = new ShareDataRow(file, contentService, null); const row = new ShareDataRow(file, contentService, null);
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
@@ -171,7 +167,7 @@ describe('ShareDataTableAdapter', () => {
file.entry.content.mimeType = null; file.entry.content.mimeType = null;
const row = new ShareDataRow(file, contentService, null); const row = new ShareDataRow(file, contentService, null);
const col = <DataColumn> { type: 'image', key: '$thumbnail' }; const col = { type: 'image', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_miscellaneous`); expect(value).toContain(`assets/images/ft_ic_miscellaneous`);
@@ -187,7 +183,7 @@ describe('ShareDataTableAdapter', () => {
file.entry.content = null; file.entry.content = null;
const row = new ShareDataRow(file, contentService, null); const row = new ShareDataRow(file, contentService, null);
const col = <DataColumn> { type: 'image', key: '$thumbnail' }; const col = { type: 'image', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_miscellaneous`); expect(value).toContain(`assets/images/ft_ic_miscellaneous`);
@@ -202,7 +198,7 @@ describe('ShareDataTableAdapter', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const row = new ShareDataRow(file, contentService, null); const row = new ShareDataRow(file, contentService, null);
const col = <DataColumn> { type: 'image', key: 'icon' }; const col = { type: 'image', key: 'icon' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toBe(imageUrl); expect(value).toBe(imageUrl);
@@ -214,7 +210,7 @@ describe('ShareDataTableAdapter', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const row = new ShareDataRow(new FolderNode(), contentService, null); const row = new ShareDataRow(new FolderNode(), contentService, null);
const col = <DataColumn> { type: 'image', key: '$thumbnail' }; const col = { type: 'image', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_folder`); expect(value).toContain(`assets/images/ft_ic_folder`);
@@ -227,7 +223,7 @@ describe('ShareDataTableAdapter', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const row = new ShareDataRow(new SmartFolderNode(), contentService, null); const row = new ShareDataRow(new SmartFolderNode(), contentService, null);
const col = <DataColumn> { type: 'text', key: '$thumbnail' }; const col = { type: 'text', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_smart_folder`); expect(value).toContain(`assets/images/ft_ic_smart_folder`);
@@ -240,7 +236,7 @@ describe('ShareDataTableAdapter', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const row = new ShareDataRow(new LinkFolderNode(), contentService, null); const row = new ShareDataRow(new LinkFolderNode(), contentService, null);
const col = <DataColumn> { type: 'text', key: '$thumbnail' }; const col = { type: 'text', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_folder_shortcut_link`); expect(value).toContain(`assets/images/ft_ic_folder_shortcut_link`);
@@ -253,7 +249,7 @@ describe('ShareDataTableAdapter', () => {
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, null);
const row = new ShareDataRow(new RuleFolderNode(), contentService, null); const row = new ShareDataRow(new RuleFolderNode(), contentService, null);
const col = <DataColumn> { type: 'text', key: '$thumbnail' }; const col = { type: 'text', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_folder_rule`); expect(value).toContain(`assets/images/ft_ic_folder_rule`);
@@ -267,7 +263,7 @@ describe('ShareDataTableAdapter', () => {
const file = new FileNode(); const file = new FileNode();
const row = new ShareDataRow(file, contentService, null); const row = new ShareDataRow(file, contentService, null);
const col = <DataColumn> { type: 'image', key: '$thumbnail' }; const col = { type: 'image', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toBe(imageUrl); expect(value).toBe(imageUrl);
@@ -285,7 +281,7 @@ describe('ShareDataTableAdapter', () => {
file.entry.content = null; file.entry.content = null;
const row = new ShareDataRow(file, contentService, null); const row = new ShareDataRow(file, contentService, null);
const col = <DataColumn> { type: 'image', key: '$thumbnail' }; const col = { type: 'image', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_miscellaneous`); expect(value).toContain(`assets/images/ft_ic_miscellaneous`);
@@ -302,7 +298,7 @@ describe('ShareDataTableAdapter', () => {
file.entry.content.mimeType = 'image/png'; file.entry.content.mimeType = 'image/png';
const row = new ShareDataRow(file, contentService, null); const row = new ShareDataRow(file, contentService, null);
const col = <DataColumn> { type: 'image', key: '$thumbnail' }; const col = { type: 'image', key: '$thumbnail' } as DataColumn;
const value = adapter.getValue(row, col); const value = adapter.getValue(row, col);
expect(value).toContain(`assets/images/ft_ic_raster_image`); expect(value).toContain(`assets/images/ft_ic_raster_image`);
@@ -314,7 +310,7 @@ describe('ShareDataTableAdapter', () => {
const file2 = new FileNode('file2'); const file2 = new FileNode('file2');
const folder = new FolderNode(); const folder = new FolderNode();
const col = <DataColumn> { key: 'name' }; const col = { key: 'name' } as DataColumn;
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]);
adapter.setSorting(new DataSorting('name', 'asc')); adapter.setSorting(new DataSorting('name', 'asc'));
@@ -325,9 +321,9 @@ describe('ShareDataTableAdapter', () => {
]); ]);
const sorted = adapter.getRows(); const sorted = adapter.getRows();
expect((<ShareDataRow> sorted[0]).node).toBe(folder); expect((sorted[0]).node).toBe(folder);
expect((<ShareDataRow> sorted[1]).node).toBe(file1); expect((sorted[1]).node).toBe(file1);
expect((<ShareDataRow> sorted[2]).node).toBe(file2); expect((sorted[2]).node).toBe(file2);
}); });
it('should sort by dates up to ms', () => { it('should sort by dates up to ms', () => {
@@ -337,7 +333,7 @@ describe('ShareDataTableAdapter', () => {
const file2 = new FileNode('file2'); const file2 = new FileNode('file2');
file2.entry['dateProp'] = new Date(2016, 6, 30, 13, 14, 2); file2.entry['dateProp'] = new Date(2016, 6, 30, 13, 14, 2);
const col = <DataColumn> { key: 'dateProp' }; const col = { key: 'dateProp' } as DataColumn;
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]);
adapter.setRows([ adapter.setRows([
@@ -348,12 +344,12 @@ describe('ShareDataTableAdapter', () => {
adapter.sort('dateProp', 'asc'); adapter.sort('dateProp', 'asc');
const rows = adapter.getRows(); const rows = adapter.getRows();
expect((<ShareDataRow> rows[0]).node).toBe(file1); expect((rows[0]).node).toBe(file1);
expect((<ShareDataRow> rows[1]).node).toBe(file2); expect((rows[1]).node).toBe(file2);
adapter.sort('dateProp', 'desc'); adapter.sort('dateProp', 'desc');
expect((<ShareDataRow> rows[0]).node).toBe(file2); expect((rows[0]).node).toBe(file2);
expect((<ShareDataRow> rows[1]).node).toBe(file1); expect((rows[1]).node).toBe(file1);
}); });
it('should sort by file size', () => { it('should sort by file size', () => {
@@ -367,7 +363,7 @@ describe('ShareDataTableAdapter', () => {
file3.entry.content.sizeInBytes = 4224120; // 4.03 MB file3.entry.content.sizeInBytes = 4224120; // 4.03 MB
file4.entry.content.sizeInBytes = 2852791665; // 2.66 GB file4.entry.content.sizeInBytes = 2852791665; // 2.66 GB
const col = <DataColumn> { key: 'content.sizeInBytes' }; const col = { key: 'content.sizeInBytes' } as DataColumn;
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]);
adapter.setRows([ adapter.setRows([
@@ -380,16 +376,16 @@ describe('ShareDataTableAdapter', () => {
adapter.sort('content.sizeInBytes', 'asc'); adapter.sort('content.sizeInBytes', 'asc');
const rows = adapter.getRows(); const rows = adapter.getRows();
expect((<ShareDataRow> rows[0]).node).toBe(file1); expect((rows[0]).node).toBe(file1);
expect((<ShareDataRow> rows[1]).node).toBe(file2); expect((rows[1]).node).toBe(file2);
expect((<ShareDataRow> rows[2]).node).toBe(file3); expect((rows[2]).node).toBe(file3);
expect((<ShareDataRow> rows[3]).node).toBe(file4); expect((rows[3]).node).toBe(file4);
adapter.sort('content.sizeInBytes', 'desc'); adapter.sort('content.sizeInBytes', 'desc');
expect((<ShareDataRow> rows[0]).node).toBe(file4); expect((rows[0]).node).toBe(file4);
expect((<ShareDataRow> rows[1]).node).toBe(file3); expect((rows[1]).node).toBe(file3);
expect((<ShareDataRow> rows[2]).node).toBe(file2); expect((rows[2]).node).toBe(file2);
expect((<ShareDataRow> rows[3]).node).toBe(file1); expect((rows[3]).node).toBe(file1);
}); });
it('should sort by name', () => { it('should sort by name', () => {
@@ -400,7 +396,7 @@ describe('ShareDataTableAdapter', () => {
const file5 = new FileNode('a'); const file5 = new FileNode('a');
const file6 = new FileNode('b'); const file6 = new FileNode('b');
const col = <DataColumn> { key: 'name' }; const col = { key: 'name' } as DataColumn;
const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]); const adapter = new ShareDataTableAdapter(thumbnailService, contentService, [col]);
adapter.setRows([ adapter.setRows([
@@ -415,20 +411,20 @@ describe('ShareDataTableAdapter', () => {
adapter.sort('name', 'asc'); adapter.sort('name', 'asc');
const rows = adapter.getRows(); const rows = adapter.getRows();
expect((<ShareDataRow> rows[0]).node).toBe(file5); expect((rows[0]).node).toBe(file5);
expect((<ShareDataRow> rows[1]).node).toBe(file6); expect((rows[1]).node).toBe(file6);
expect((<ShareDataRow> rows[2]).node).toBe(file1); expect((rows[2]).node).toBe(file1);
expect((<ShareDataRow> rows[3]).node).toBe(file2); expect((rows[3]).node).toBe(file2);
expect((<ShareDataRow> rows[4]).node).toBe(file4); expect((rows[4]).node).toBe(file4);
expect((<ShareDataRow> rows[5]).node).toBe(file3); expect((rows[5]).node).toBe(file3);
adapter.sort('name', 'desc'); adapter.sort('name', 'desc');
expect((<ShareDataRow> rows[0]).node).toBe(file3); expect((rows[0]).node).toBe(file3);
expect((<ShareDataRow> rows[1]).node).toBe(file4); expect((rows[1]).node).toBe(file4);
expect((<ShareDataRow> rows[2]).node).toBe(file2); expect((rows[2]).node).toBe(file2);
expect((<ShareDataRow> rows[3]).node).toBe(file1); expect((rows[3]).node).toBe(file1);
expect((<ShareDataRow> rows[4]).node).toBe(file6); expect((rows[4]).node).toBe(file6);
expect((<ShareDataRow> rows[5]).node).toBe(file5); expect((rows[5]).node).toBe(file5);
}); });
describe('ShareDataRow', () => { describe('ShareDataRow', () => {
@@ -440,9 +436,7 @@ describe('ShareDataTableAdapter', () => {
}); });
it('should require object source', () => { it('should require object source', () => {
expect(() => { expect(() => new ShareDataRow(null, contentService, null)).toThrowError(ERR_OBJECT_NOT_FOUND);
return new ShareDataRow(null, contentService, null);
}).toThrowError(ShareDataRow.ERR_OBJECT_NOT_FOUND);
}); });
it('should resolve value from node entry', () => { it('should resolve value from node entry', () => {
@@ -28,11 +28,10 @@ import { PermissionStyleModel } from './../models/permissions-style.model';
import { ShareDataRow } from './share-data-row.model'; import { ShareDataRow } from './share-data-row.model';
import { RowFilter } from './row-filter.model'; import { RowFilter } from './row-filter.model';
export const ERR_ROW_NOT_FOUND: string = 'Row not found';
export const ERR_COL_NOT_FOUND: string = 'Column not found';
export class ShareDataTableAdapter implements DataTableAdapter { export class ShareDataTableAdapter implements DataTableAdapter {
ERR_ROW_NOT_FOUND: string = 'Row not found';
ERR_COL_NOT_FOUND: string = 'Column not found';
private _sortingMode: string; private _sortingMode: string;
private sorting: DataSorting; private sorting: DataSorting;
private rows: DataRow[]; private rows: DataRow[];
@@ -91,12 +90,12 @@ export class ShareDataTableAdapter implements DataTableAdapter {
getValue(row: DataRow, col: DataColumn): any { getValue(row: DataRow, col: DataColumn): any {
if (!row) { if (!row) {
throw new Error(this.ERR_ROW_NOT_FOUND); throw new Error(ERR_ROW_NOT_FOUND);
} }
if (!col) { if (!col) {
throw new Error(this.ERR_COL_NOT_FOUND); throw new Error(ERR_COL_NOT_FOUND);
} }
const dataRow: ShareDataRow = <ShareDataRow> row; const dataRow = row as ShareDataRow;
const value: any = row.getValue(col.key); const value: any = row.getValue(col.key);
if (dataRow.cache[col.key] !== undefined) { if (dataRow.cache[col.key] !== undefined) {
return dataRow.cache[col.key]; return dataRow.cache[col.key];
@@ -111,7 +110,7 @@ export class ShareDataTableAdapter implements DataTableAdapter {
} }
} }
const node = (<ShareDataRow> row).node; const node = row.node;
if (node.entry.isFolder) { if (node.entry.isFolder) {
return this.getFolderIcon(node); return this.getFolderIcon(node);
@@ -280,9 +279,7 @@ export class ShareDataTableAdapter implements DataTableAdapter {
if (merge) { if (merge) {
const listPrunedDuplicate = shareDataRows.filter((elementToFilter: any) => { const listPrunedDuplicate = shareDataRows.filter((elementToFilter: any) => {
const isPresent = this.rows.find((currentRow: any) => { const isPresent = this.rows.find((currentRow: any) => currentRow.obj.entry.id === elementToFilter.obj.entry.id);
return currentRow.obj.entry.id === elementToFilter.obj.entry.id;
});
return !isPresent; return !isPresent;
}); });
@@ -15,6 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
/* eslint-disable no-shadow */
/* eslint-disable @typescript-eslint/naming-convention */
export class ContentActionModel { export class ContentActionModel {
icon: string; icon: string;
title: string; title: string;
@@ -15,6 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
/* eslint-disable no-shadow */
/* eslint-disable @typescript-eslint/naming-convention */
export enum NodeAction { export enum NodeAction {
ATTACH = 'ATTACH', ATTACH = 'ATTACH',
CHOOSE = 'CHOOSE', CHOOSE = 'CHOOSE',
@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
export let presetsDefaultModel = { export const presetsDefaultModel = {
'-trashcan-': [ '-trashcan-': [
{ {
key: '$thumbnail', key: '$thumbnail',
@@ -220,7 +220,7 @@ export let presetsDefaultModel = {
sortable: true sortable: true
} }
], ],
'default': [ default: [
{ {
key: '$thumbnail', key: '$thumbnail',
type: 'image', type: 'image',
@@ -36,48 +36,48 @@ import { Injectable } from '@angular/core';
import { Observable, from, of, throwError } from 'rxjs'; import { Observable, from, of, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators'; import { catchError, map } from 'rxjs/operators';
const CREATE_PERMISSION: string = 'create';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class CustomResourcesService { export class CustomResourcesService {
private CREATE_PERMISSION = 'create'; private _peopleApi: PeopleApi;
_peopleApi: PeopleApi;
get peopleApi(): PeopleApi { get peopleApi(): PeopleApi {
this._peopleApi = this._peopleApi ?? new PeopleApi(this.apiService.getInstance()); this._peopleApi = this._peopleApi ?? new PeopleApi(this.apiService.getInstance());
return this._peopleApi; return this._peopleApi;
} }
_sitesApi: SitesApi; private _sitesApi: SitesApi;
get sitesApi(): SitesApi { get sitesApi(): SitesApi {
this._sitesApi = this._sitesApi ?? new SitesApi(this.apiService.getInstance()); this._sitesApi = this._sitesApi ?? new SitesApi(this.apiService.getInstance());
return this._sitesApi; return this._sitesApi;
} }
_trashcanApi: TrashcanApi; private _trashcanApi: TrashcanApi;
get trashcanApi(): TrashcanApi { get trashcanApi(): TrashcanApi {
this._trashcanApi = this._trashcanApi ?? new TrashcanApi(this.apiService.getInstance()); this._trashcanApi = this._trashcanApi ?? new TrashcanApi(this.apiService.getInstance());
return this._trashcanApi; return this._trashcanApi;
} }
_searchApi: SearchApi; private _searchApi: SearchApi;
get searchApi(): SearchApi { get searchApi(): SearchApi {
this._searchApi = this._searchApi ?? new SearchApi(this.apiService.getInstance()); this._searchApi = this._searchApi ?? new SearchApi(this.apiService.getInstance());
return this._searchApi; return this._searchApi;
} }
_sharedLinksApi: SharedlinksApi; private _sharedLinksApi: SharedlinksApi;
get sharedLinksApi(): SharedlinksApi { get sharedLinksApi(): SharedlinksApi {
this._sharedLinksApi = this._sharedLinksApi ?? new SharedlinksApi(this.apiService.getInstance()); this._sharedLinksApi = this._sharedLinksApi ?? new SharedlinksApi(this.apiService.getInstance());
return this._sharedLinksApi; return this._sharedLinksApi;
} }
_favoritesApi: FavoritesApi; private _favoritesApi: FavoritesApi;
get favoritesApi(): FavoritesApi { get favoritesApi(): FavoritesApi {
this._favoritesApi = this._favoritesApi ?? new FavoritesApi(this.apiService.getInstance()); this._favoritesApi = this._favoritesApi ?? new FavoritesApi(this.apiService.getInstance());
return this._favoritesApi; return this._favoritesApi;
} }
_nodesApi: NodesApi; private _nodesApi: NodesApi;
get nodesApi(): NodesApi { get nodesApi(): NodesApi {
this._nodesApi = this._nodesApi ?? new NodesApi(this.apiService.getInstance()); this._nodesApi = this._nodesApi ?? new NodesApi(this.apiService.getInstance());
return this._nodesApi; return this._nodesApi;
@@ -88,6 +88,7 @@ export class CustomResourcesService {
/** /**
* Gets files recently accessed by a user. * Gets files recently accessed by a user.
*
* @param personId ID of the user * @param personId ID of the user
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @param filters Specifies additional filters to apply (joined with **AND**) * @param filters Specifies additional filters to apply (joined with **AND**)
@@ -169,6 +170,7 @@ export class CustomResourcesService {
/** /**
* Gets favorite files for the current user. * Gets favorite files for the current user.
*
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @param includeFields List of data field names to include in the results * @param includeFields List of data field names to include in the results
* @param where A string to restrict the returned objects by using a predicate * @param where A string to restrict the returned objects by using a predicate
@@ -221,6 +223,7 @@ export class CustomResourcesService {
/** /**
* Gets sites that the current user is a member of. * Gets sites that the current user is a member of.
*
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @param where A string to restrict the returned objects by using a predicate * @param where A string to restrict the returned objects by using a predicate
* @returns List of sites * @returns List of sites
@@ -240,7 +243,7 @@ export class CustomResourcesService {
list: { list: {
entries: result.list.entries entries: result.list.entries
.map(({ entry: { site } }: any) => { .map(({ entry: { site } }: any) => {
site.allowableOperations = site.allowableOperations ? site.allowableOperations : [this.CREATE_PERMISSION]; site.allowableOperations = site.allowableOperations ? site.allowableOperations : [CREATE_PERMISSION];
site.name = site.name || site.title; site.name = site.name || site.title;
return { return {
entry: site entry: site
@@ -262,6 +265,7 @@ export class CustomResourcesService {
/** /**
* Gets all sites in the repository. * Gets all sites in the repository.
*
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @param where A string to restrict the returned objects by using a predicate * @param where A string to restrict the returned objects by using a predicate
* @returns List of sites * @returns List of sites
@@ -297,6 +301,7 @@ export class CustomResourcesService {
/** /**
* Gets all items currently in the trash. * Gets all items currently in the trash.
*
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @param includeFields List of data field names to include in the results * @param includeFields List of data field names to include in the results
* @returns List of deleted items * @returns List of deleted items
@@ -317,6 +322,7 @@ export class CustomResourcesService {
/** /**
* Gets shared links for the current user. * Gets shared links for the current user.
*
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @param includeFields List of data field names to include in the results * @param includeFields List of data field names to include in the results
* @param where A string to restrict the returned objects by using a predicate * @param where A string to restrict the returned objects by using a predicate
@@ -338,6 +344,7 @@ export class CustomResourcesService {
/** /**
* Is the folder ID one of the well-known aliases? * Is the folder ID one of the well-known aliases?
*
* @param folderId Folder ID name to check * @param folderId Folder ID name to check
* @returns True if the ID is a well-known name, false otherwise * @returns True if the ID is a well-known name, false otherwise
*/ */
@@ -354,6 +361,7 @@ export class CustomResourcesService {
/** /**
* Is the folder ID a "-my", "-root-", or "-shared-" alias? * Is the folder ID a "-my", "-root-", or "-shared-" alias?
*
* @param folderId Folder ID name to check * @param folderId Folder ID name to check
* @returns True if the ID is one of the supported sources, false otherwise * @returns True if the ID is one of the supported sources, false otherwise
*/ */
@@ -370,6 +378,7 @@ export class CustomResourcesService {
/** /**
* Gets a folder's contents. * Gets a folder's contents.
*
* @param nodeId ID of the target folder node * @param nodeId ID of the target folder node
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @param includeFields List of data field names to include in the results * @param includeFields List of data field names to include in the results
@@ -396,6 +405,7 @@ export class CustomResourcesService {
/** /**
* Gets the contents of one of the well-known aliases in the form of node ID strings. * Gets the contents of one of the well-known aliases in the form of node ID strings.
*
* @param nodeId ID of the target folder node * @param nodeId ID of the target folder node
* @param pagination Specifies how to paginate the results * @param pagination Specifies how to paginate the results
* @returns List of node IDs * @returns List of node IDs
@@ -404,9 +414,7 @@ export class CustomResourcesService {
if (this.isCustomSource(nodeId)) { if (this.isCustomSource(nodeId)) {
return this.loadFolderByNodeId(nodeId, pagination) return this.loadFolderByNodeId(nodeId, pagination)
.pipe(map((result: any): string[] => { .pipe(map((result: any): string[] => result.list.entries.map((node: any): string => this.getIdFromEntry(node, nodeId))));
return result.list.entries.map((node: any): string => this.getIdFromEntry(node, nodeId));
}));
} else if (nodeId) { } else if (nodeId) {
// cases when nodeId is '-my-', '-root-' or '-shared-' // cases when nodeId is '-my-', '-root-' or '-shared-'
@@ -419,6 +427,7 @@ export class CustomResourcesService {
/** /**
* Chooses the correct ID for a node entry. * Chooses the correct ID for a node entry.
*
* @param node Node object * @param node Node object
* @param nodeId ID of the node object * @param nodeId ID of the node object
* @returns ID value * @returns ID value
@@ -437,6 +446,7 @@ export class CustomResourcesService {
/** /**
* Does the well-known alias have a corresponding node ID? * Does the well-known alias have a corresponding node ID?
*
* @param nodeId Node to check * @param nodeId Node to check
* @returns True if the alias has a corresponding node ID, false otherwise * @returns True if the alias has a corresponding node ID, false otherwise
*/ */
@@ -51,8 +51,7 @@ describe('DocumentActionsService', () => {
}); });
it('should register custom action handler', () => { it('should register custom action handler', () => {
const handler: ContentActionHandler = function () { const handler: ContentActionHandler = () => {};
};
service.setHandler('<key>', handler); service.setHandler('<key>', handler);
expect(service.getHandler('<key>')).toBe(handler); expect(service.getHandler('<key>')).toBe(handler);
}); });
@@ -62,8 +61,7 @@ describe('DocumentActionsService', () => {
}); });
it('should be case insensitive for keys', () => { it('should be case insensitive for keys', () => {
const handler: ContentActionHandler = function () { const handler: ContentActionHandler = () => {};
};
service.setHandler('<key>', handler); service.setHandler('<key>', handler);
expect(service.getHandler('<KEY>')).toBe(handler); expect(service.getHandler('<KEY>')).toBe(handler);
}); });
@@ -88,8 +86,7 @@ describe('DocumentActionsService', () => {
}); });
it('should set new handler only by key', () => { it('should set new handler only by key', () => {
const handler: ContentActionHandler = function () { const handler: ContentActionHandler = () => {};
};
expect(service.setHandler(null, handler)).toBeFalsy(); expect(service.setHandler(null, handler)).toBeFalsy();
expect(service.setHandler('', handler)).toBeFalsy(); expect(service.setHandler('', handler)).toBeFalsy();
expect(service.setHandler('my-handler', handler)).toBeTruthy(); expect(service.setHandler('my-handler', handler)).toBeTruthy();
@@ -46,6 +46,7 @@ export class DocumentActionsService {
/** /**
* Gets the handler for an action. * Gets the handler for an action.
*
* @param key Identifier of the action * @param key Identifier of the action
* @returns The handler for the action * @returns The handler for the action
*/ */
@@ -59,6 +60,7 @@ export class DocumentActionsService {
/** /**
* Sets a new handler for an action. * Sets a new handler for an action.
*
* @param key Identifier of the action * @param key Identifier of the action
* @param handler Handler for the action * @param handler Handler for the action
* @returns False if the key was an empty/null string, true otherwise * @returns False if the key was an empty/null string, true otherwise
@@ -74,6 +76,7 @@ export class DocumentActionsService {
/** /**
* Checks if actions can be executed for an item. * Checks if actions can be executed for an item.
*
* @param nodeEntry Item to receive an action * @param nodeEntry Item to receive an action
* @returns True if the action can be executed on this item, false otherwise * @returns True if the action can be executed on this item, false otherwise
*/ */
@@ -134,7 +137,7 @@ export class DocumentActionsService {
this.permissionEvent.next(new PermissionModel({ this.permissionEvent.next(new PermissionModel({
type: 'content', type: 'content',
action: 'delete', action: 'delete',
permission: permission permission
})); }));
return throwError(new Error('No permission to delete')); return throwError(new Error('No permission to delete'));
} }
@@ -28,34 +28,34 @@ describe('DocumentListService', () => {
let service: DocumentListService; let service: DocumentListService;
const fakeFolder = { const fakeFolder = {
'list': { list: {
'pagination': { 'count': 1, 'hasMoreItems': false, 'totalItems': 1, 'skipCount': 0, 'maxItems': 20 }, pagination: { count: 1, hasMoreItems: false, totalItems: 1, skipCount: 0, maxItems: 20 },
'entries': [{ entries: [{
'entry': { entry: {
'createdAt': '2016-12-06T13:03:14.880+0000', createdAt: '2016-12-06T13:03:14.880+0000',
'path': { path: {
'name': '/Company Home/Sites/swsdp/documentLibrary/empty', name: '/Company Home/Sites/swsdp/documentLibrary/empty',
'isComplete': true, isComplete: true,
'elements': [{ elements: [{
'id': 'ed7ab80e-b398-4bed-b38d-139ae4cc592a', id: 'ed7ab80e-b398-4bed-b38d-139ae4cc592a',
'name': 'Company Home' name: 'Company Home'
}, { 'id': '99e1368f-e816-47fc-a8bf-3b358feaf31e', 'name': 'Sites' }, { }, { id: '99e1368f-e816-47fc-a8bf-3b358feaf31e', name: 'Sites' }, {
'id': 'b4cff62a-664d-4d45-9302-98723eac1319', id: 'b4cff62a-664d-4d45-9302-98723eac1319',
'name': 'swsdp' name: 'swsdp'
}, { }, {
'id': '8f2105b4-daaf-4874-9e8a-2152569d109b', id: '8f2105b4-daaf-4874-9e8a-2152569d109b',
'name': 'documentLibrary' name: 'documentLibrary'
}, { 'id': '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32', 'name': 'empty' }] }, { id: '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32', name: 'empty' }]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { 'id': 'admin', 'displayName': 'Administrator' }, createdByUser: { id: 'admin', displayName: 'Administrator' },
'modifiedAt': '2016-12-06T13:03:14.880+0000', modifiedAt: '2016-12-06T13:03:14.880+0000',
'modifiedByUser': { 'id': 'admin', 'displayName': 'Administrator' }, modifiedByUser: { id: 'admin', displayName: 'Administrator' },
'name': 'fake-name', name: 'fake-name',
'id': 'aac546f6-1525-46ff-bf6b-51cb85f3cda7', id: 'aac546f6-1525-46ff-bf6b-51cb85f3cda7',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'parentId': '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32' parentId: '17fa78d2-4d6b-4a46-876b-4b0ea07f7f32'
} }
}] }]
} }
@@ -27,14 +27,14 @@ import { catchError, map } from 'rxjs/operators';
import { DocumentListLoader } from '../interfaces/document-list-loader.interface'; import { DocumentListLoader } from '../interfaces/document-list-loader.interface';
import { CustomResourcesService } from './custom-resources.service'; import { CustomResourcesService } from './custom-resources.service';
const ROOT_ID = '-root-';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class DocumentListService implements DocumentListLoader { export class DocumentListService implements DocumentListLoader {
static ROOT_ID = '-root-'; private _nodesApi: NodesApi;
_nodesApi: NodesApi;
get nodes(): NodesApi { get nodes(): NodesApi {
this._nodesApi = this._nodesApi ?? new NodesApi(this.apiService.getInstance()); this._nodesApi = this._nodesApi ?? new NodesApi(this.apiService.getInstance());
return this._nodesApi; return this._nodesApi;
@@ -48,6 +48,7 @@ export class DocumentListService implements DocumentListLoader {
/** /**
* Deletes a node. * Deletes a node.
*
* @param nodeId ID of the node to delete * @param nodeId ID of the node to delete
* @returns Empty response when the operation is complete * @returns Empty response when the operation is complete
*/ */
@@ -83,13 +84,14 @@ export class DocumentListService implements DocumentListLoader {
/** /**
* Gets the folder node with the specified relative name path below the root node. * Gets the folder node with the specified relative name path below the root node.
*
* @param folder Path to folder. * @param folder Path to folder.
* @param opts Options. * @param opts Options.
* @param includeFields Extra information to include (available options are "aspectNames", "isLink" and "association") * @param includeFields Extra information to include (available options are "aspectNames", "isLink" and "association")
* @returns Details of the folder * @returns Details of the folder
*/ */
getFolder(folder: string, opts?: any, includeFields: string[] = []): Observable<NodePaging> { getFolder(folder: string, opts?: any, includeFields: string[] = []): Observable<NodePaging> {
let rootNodeId = DocumentListService.ROOT_ID; let rootNodeId = ROOT_ID;
if (opts && opts.rootFolderId) { if (opts && opts.rootFolderId) {
rootNodeId = opts.rootFolderId; rootNodeId = opts.rootFolderId;
} }
@@ -128,6 +130,7 @@ export class DocumentListService implements DocumentListLoader {
/** /**
* Gets a node via its node ID. * Gets a node via its node ID.
*
* @param nodeId ID of the target node * @param nodeId ID of the target node
* @param includeFields Extra information to include (available options are "aspectNames", "isLink" and "association") * @param includeFields Extra information to include (available options are "aspectNames", "isLink" and "association")
* @returns Details of the folder * @returns Details of the folder
@@ -146,6 +149,7 @@ export class DocumentListService implements DocumentListLoader {
/** /**
* Gets a folder node via its node ID. * Gets a folder node via its node ID.
*
* @param nodeId ID of the folder node * @param nodeId ID of the folder node
* @param includeFields Extra information to include (available options are "aspectNames", "isLink" and "association") * @param includeFields Extra information to include (available options are "aspectNames", "isLink" and "association")
* @returns Details of the folder * @returns Details of the folder
@@ -170,6 +174,7 @@ export class DocumentListService implements DocumentListLoader {
/** /**
* Load a folder by Node Id. * Load a folder by Node Id.
*
* @param nodeId ID of the folder node * @param nodeId ID of the folder node
* @param pagination * @param pagination
* @param includeFields List of data field names to include in the results * @param includeFields List of data field names to include in the results
@@ -193,9 +198,9 @@ export class DocumentListService implements DocumentListLoader {
this.getFolder(null, { this.getFolder(null, {
maxItems: pagination.maxItems, maxItems: pagination.maxItems,
skipCount: pagination.skipCount, skipCount: pagination.skipCount,
orderBy: orderBy, orderBy,
rootFolderId: nodeId, rootFolderId: nodeId,
where: where where
}, includeFields)]).pipe( }, includeFields)]).pipe(
map((results) => new DocumentLoaderNode(results[0], results[1])) map((results) => new DocumentLoaderNode(results[0], results[1]))
); );
@@ -46,8 +46,7 @@ describe('FolderActionsService', () => {
}); });
it('should register custom action handler', () => { it('should register custom action handler', () => {
const handler: ContentActionHandler = function () { const handler: ContentActionHandler = () => {};
};
service.setHandler('<key>', handler); service.setHandler('<key>', handler);
expect(service.getHandler('<key>')).toBe(handler); expect(service.getHandler('<key>')).toBe(handler);
}); });
@@ -57,8 +56,7 @@ describe('FolderActionsService', () => {
}); });
it('should be case insensitive for keys', () => { it('should be case insensitive for keys', () => {
const handler: ContentActionHandler = function () { const handler: ContentActionHandler = () => {};
};
service.setHandler('<key>', handler); service.setHandler('<key>', handler);
expect(service.getHandler('<KEY>')).toBe(handler); expect(service.getHandler('<KEY>')).toBe(handler);
}); });
@@ -80,8 +78,7 @@ describe('FolderActionsService', () => {
}); });
it('should set new handler only by key', () => { it('should set new handler only by key', () => {
const handler: ContentActionHandler = function () { const handler: ContentActionHandler = () => {};
};
expect(service.setHandler(null, handler)).toBeFalsy(); expect(service.setHandler(null, handler)).toBeFalsy();
expect(service.setHandler('', handler)).toBeFalsy(); expect(service.setHandler('', handler)).toBeFalsy();
expect(service.setHandler('my-handler', handler)).toBeTruthy(); expect(service.setHandler('my-handler', handler)).toBeTruthy();
@@ -106,12 +103,10 @@ describe('FolderActionsService', () => {
}); });
it('should delete the folder node if there is the delete permission', () => { it('should delete the folder node if there is the delete permission', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
const permission = 'delete'; const permission = 'delete';
const folder = new FolderNode(); const folder = new FolderNode();
@@ -124,12 +119,10 @@ describe('FolderActionsService', () => {
}); });
it('should not delete the folder node if there is no delete permission', (done) => { it('should not delete the folder node if there is no delete permission', (done) => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
service.permissionEvent.subscribe((permission) => { service.permissionEvent.subscribe((permission) => {
expect(permission).toBeDefined(); expect(permission).toBeDefined();
@@ -145,12 +138,10 @@ describe('FolderActionsService', () => {
}); });
it('should call the error on the returned Observable if there is no delete permission', (done) => { it('should call the error on the returned Observable if there is no delete permission', (done) => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
const folder = new FolderNode(); const folder = new FolderNode();
const folderWithPermission: any = folder; const folderWithPermission: any = folder;
@@ -166,12 +157,10 @@ describe('FolderActionsService', () => {
}); });
it('should delete the folder node if there is the delete and others permission ', () => { it('should delete the folder node if there is the delete and others permission ', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
const permission = 'delete'; const permission = 'delete';
const folder = new FolderNode(); const folder = new FolderNode();
@@ -183,12 +172,10 @@ describe('FolderActionsService', () => {
}); });
it('should support deletion only folder node', () => { it('should support deletion only folder node', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
const permission = 'delete'; const permission = 'delete';
const file = new FileNode(); const file = new FileNode();
@@ -203,12 +190,10 @@ describe('FolderActionsService', () => {
}); });
it('should require node id to delete', () => { it('should require node id to delete', () => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
const folder = new FolderNode(); const folder = new FolderNode();
folder.entry.id = null; folder.entry.id = null;
@@ -218,12 +203,10 @@ describe('FolderActionsService', () => {
}); });
it('should reload target upon node deletion', (done) => { it('should reload target upon node deletion', (done) => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
const permission = 'delete'; const permission = 'delete';
const target = jasmine.createSpyObj('obj', ['reload']); const target = jasmine.createSpyObj('obj', ['reload']);
@@ -242,12 +225,10 @@ describe('FolderActionsService', () => {
}); });
it('should emit success event upon node deletion', (done) => { it('should emit success event upon node deletion', (done) => {
spyOn(documentListService, 'deleteNode').and.callFake(() => { spyOn(documentListService, 'deleteNode').and.callFake(() => new Observable<any>((observer) => {
return new Observable<any>((observer) => {
observer.next(); observer.next();
observer.complete(); observer.complete();
}); }));
});
service.success.subscribe((nodeId) => { service.success.subscribe((nodeId) => {
expect(nodeId).not.toBeNull(); expect(nodeId).not.toBeNull();
@@ -44,6 +44,7 @@ export class FolderActionsService {
/** /**
* Gets the handler function for an action. * Gets the handler function for an action.
*
* @param key Identifier for the action * @param key Identifier for the action
* @returns The handler function * @returns The handler function
*/ */
@@ -57,6 +58,7 @@ export class FolderActionsService {
/** /**
* Sets a new handler function for an action. * Sets a new handler function for an action.
*
* @param key Identifier for the action * @param key Identifier for the action
* @param handler The new handler function * @param handler The new handler function
* @returns True if the key was a valid action identifier, false otherwise * @returns True if the key was a valid action identifier, false otherwise
@@ -72,6 +74,7 @@ export class FolderActionsService {
/** /**
* Checks if an action is available for a particular item. * Checks if an action is available for a particular item.
*
* @param nodeEntry Item to check * @param nodeEntry Item to check
* @returns True if the action is available, false otherwise * @returns True if the action is available, false otherwise
*/ */
@@ -132,7 +135,7 @@ export class FolderActionsService {
return handlerObservable; return handlerObservable;
} else { } else {
this.permissionEvent.next(new PermissionModel({type: 'folder', action: 'delete', permission: permission})); this.permissionEvent.next(new PermissionModel({type: 'folder', action: 'delete', permission}));
return throwError(new Error('No permission to delete')); return throwError(new Error('No permission to delete'));
} }
} }
@@ -26,9 +26,9 @@ import { MatDialogRef } from '@angular/material/dialog';
import { ContentTestingModule } from '../../testing/content.testing.module'; import { ContentTestingModule } from '../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
const fakeNode: Node = <Node> { const fakeNode: Node = {
id: 'fake' id: 'fake'
}; } as Node;
describe('NodeActionsService', () => { describe('NodeActionsService', () => {
@@ -113,7 +113,7 @@ describe('FolderCreateDirective', () => {
}); });
it('should emit success event with node if the folder creation was successful', async () => { it('should emit success event with node if the folder creation was successful', async () => {
const testNode = <Node> {}; const testNode = {};
element.triggerEventHandler('click', event); element.triggerEventHandler('click', event);
dialogRefMock.componentInstance.success.next(testNode); dialogRefMock.componentInstance.success.next(testNode);
@@ -24,13 +24,12 @@ import { FolderDialogComponent } from '../dialogs/folder.dialog';
import { ContentService } from '@alfresco/adf-core'; import { ContentService } from '@alfresco/adf-core';
const DEFAULT_FOLDER_PARENT_ID = '-my-'; const DEFAULT_FOLDER_PARENT_ID = '-my-';
const DIALOG_WIDTH: number = 400;
@Directive({ @Directive({
selector: '[adf-create-folder]' selector: '[adf-create-folder]'
}) })
export class FolderCreateDirective { export class FolderCreateDirective {
static DIALOG_WIDTH: number = 400;
/** Parent folder where the new folder will be located after creation. */ /** Parent folder where the new folder will be located after creation. */
@Input('adf-create-folder') @Input('adf-create-folder')
parentNodeId: string = DEFAULT_FOLDER_PARENT_ID; parentNodeId: string = DEFAULT_FOLDER_PARENT_ID;
@@ -63,12 +62,11 @@ export class FolderCreateDirective {
) {} ) {}
private get dialogConfig() { private get dialogConfig() {
const { DIALOG_WIDTH: width } = FolderCreateDirective;
const { parentNodeId, title: createTitle, nodeType } = this; const { parentNodeId, title: createTitle, nodeType } = this;
return { return {
data: { parentNodeId, createTitle, nodeType }, data: { parentNodeId, createTitle, nodeType },
width: `${width}px` width: `${DIALOG_WIDTH}px`
}; };
} }
@@ -93,7 +93,7 @@ describe('FolderEditDirective', () => {
it('should emit success event with node if the folder creation was successful', async () => { it('should emit success event with node if the folder creation was successful', async () => {
fixture.detectChanges(); fixture.detectChanges();
const testNode = <Node> {}; const testNode: any = {};
element.triggerEventHandler('click', event); element.triggerEventHandler('click', event);
dialogRefMock.componentInstance.success.next(testNode); dialogRefMock.componentInstance.success.next(testNode);
@@ -19,25 +19,23 @@
import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core'; import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { Node } from '@alfresco/js-api'; import { Node } from '@alfresco/js-api';
import { FolderDialogComponent } from '../dialogs/folder.dialog'; import { FolderDialogComponent } from '../dialogs/folder.dialog';
import { ContentService } from '@alfresco/adf-core'; import { ContentService } from '@alfresco/adf-core';
const DIALOG_WIDTH: number = 400;
@Directive({ @Directive({
selector: '[adf-edit-folder]' selector: '[adf-edit-folder]'
}) })
export class FolderEditDirective { export class FolderEditDirective {
static DIALOG_WIDTH: number = 400;
/** Folder node to edit. */ /** Folder node to edit. */
@Input('adf-edit-folder') @Input('adf-edit-folder')
folder: Node; folder: Node;
/** Emitted when an error occurs (eg, a folder with same name already exists). */ /** Emitted when an error occurs (eg, a folder with same name already exists). */
@Output() @Output()
error: EventEmitter<any> = new EventEmitter<any>(); error = new EventEmitter<any>();
/** Title of folder edit dialog. */ /** Title of folder edit dialog. */
@Input() @Input()
@@ -45,7 +43,7 @@ export class FolderEditDirective {
/** Emitted when the folder has been edited successfully. */ /** Emitted when the folder has been edited successfully. */
@Output() @Output()
success: EventEmitter<Node> = new EventEmitter<Node>(); success = new EventEmitter<Node>();
@HostListener('click', [ '$event' ]) @HostListener('click', [ '$event' ])
onClick(event) { onClick(event) {
@@ -62,7 +60,6 @@ export class FolderEditDirective {
) {} ) {}
private get dialogConfig() { private get dialogConfig() {
const { DIALOG_WIDTH: width } = FolderEditDirective;
const { folder } = this; const { folder } = this;
return { return {
@@ -70,7 +67,7 @@ export class FolderEditDirective {
folder, folder,
editTitle: this.title editTitle: this.title
}, },
width: `${width}px` width: `${DIALOG_WIDTH}px`
}; };
} }
@@ -18,48 +18,48 @@
/* spellchecker: disable */ /* spellchecker: disable */
export const fakeAuthorityResults: any[] = [{ export const fakeAuthorityResults: any[] = [{
'entry': { entry: {
'aspectNames': [ aspectNames: [
'cm:personDisabled', 'cm:personDisabled',
'cm:ownable', 'cm:ownable',
'cm:preferences' 'cm:preferences'
], ],
'isFolder': false, isFolder: false,
'search': { search: {
'score': 4.014668 score: 4.014668
}, },
'isFile': false, isFile: false,
'name': 'dc103838-645f-43c1-8a2a-bc187e13c343', name: 'dc103838-645f-43c1-8a2a-bc187e13c343',
'location': 'nodes', location: 'nodes',
'id': 'dc103838-645f-43c1-8a2a-bc187e13c343', id: 'dc103838-645f-43c1-8a2a-bc187e13c343',
'nodeType': 'cm:person', nodeType: 'cm:person',
'properties': { properties: {
'cm:location': 'Tilbury, UK', 'cm:location': 'Tilbury, UK',
'cm:persondescription': { 'cm:persondescription': {
'contentUrl': 'store://2018/4/18/9/30/514bb261-bc61-4502-ad2f-dfafec9ae4eb.bin', contentUrl: 'store://2018/4/18/9/30/514bb261-bc61-4502-ad2f-dfafec9ae4eb.bin',
'mimetype': 'application/octet-stream', mimetype: 'application/octet-stream',
'size': 55, size: 55,
'encoding': 'UTF-8', encoding: 'UTF-8',
'locale': 'en_US', locale: 'en_US',
'id': 148, id: 148,
'infoUrl': 'contentUrl=store://2018/4/18/9/30/514bb261-bc61-4502-ad2f-dfafec9ae4eb.bin|mimetype=application/octet-stream|size=55|encoding=UTF-8|locale=en_US_' infoUrl: 'contentUrl=store://2018/4/18/9/30/514bb261-bc61-4502-ad2f-dfafec9ae4eb.bin|mimetype=application/octet-stream|size=55|encoding=UTF-8|locale=en_US_'
}, },
'cm:owner': { 'cm:owner': {
'id': 'abeecher', id: 'abeecher',
'displayName': 'Alice Beecher' displayName: 'Alice Beecher'
}, },
'cm:companyaddress2': 'Tilbury', 'cm:companyaddress2': 'Tilbury',
'cm:userStatus': 'Helping to design the look and feel of the new web site', 'cm:userStatus': 'Helping to design the look and feel of the new web site',
'cm:companyaddress1': '200 Butterwick Street', 'cm:companyaddress1': '200 Butterwick Street',
'cm:telephone': '0112211001100', 'cm:telephone': '0112211001100',
'cm:preferenceValues': { 'cm:preferenceValues': {
'contentUrl': 'store://2018/4/18/9/30/afc39bc9-6bac-4f24-8730-9d9f617a322e.bin', contentUrl: 'store://2018/4/18/9/30/afc39bc9-6bac-4f24-8730-9d9f617a322e.bin',
'mimetype': 'text/plain', mimetype: 'text/plain',
'size': 709, size: 709,
'encoding': 'UTF-8', encoding: 'UTF-8',
'locale': 'en_US', locale: 'en_US',
'id': 147, id: 147,
'infoUrl': 'contentUrl=store://2018/4/18/9/30/afc39bc9-6bac-4f24-8730-9d9f617a322e.bin|mimetype=text/plain|size=709|encoding=UTF-8|locale=en_US_' infoUrl: 'contentUrl=store://2018/4/18/9/30/afc39bc9-6bac-4f24-8730-9d9f617a322e.bin|mimetype=text/plain|size=709|encoding=UTF-8|locale=en_US_'
}, },
'cm:userName': 'abeecher', 'cm:userName': 'abeecher',
'cm:companyaddress3': 'UK', 'cm:companyaddress3': 'UK',
@@ -79,34 +79,34 @@ export const fakeAuthorityResults: any[] = [{
'cm:organization': 'Moresby, Garland and Wedge', 'cm:organization': 'Moresby, Garland and Wedge',
'cm:companypostcode': 'ALF1 SAM1' 'cm:companypostcode': 'ALF1 SAM1'
}, },
'parentId': '063f5d48-a0b3-4cbf-826c-88a4fbfa3336' parentId: '063f5d48-a0b3-4cbf-826c-88a4fbfa3336'
} }
}, },
{ {
'entry': { entry: {
'aspectNames': [ aspectNames: [
'cm:ownable', 'cm:ownable',
'cm:preferences' 'cm:preferences'
], ],
'isFolder': false, isFolder: false,
'search': { search: {
'score': 4.014668 score: 4.014668
}, },
'isFile': false, isFile: false,
'name': 'e320c16b-a763-4a4e-9f22-286ff5d8dca2', name: 'e320c16b-a763-4a4e-9f22-286ff5d8dca2',
'location': 'nodes', location: 'nodes',
'id': 'e320c16b-a763-4a4e-9f22-286ff5d8dca2', id: 'e320c16b-a763-4a4e-9f22-286ff5d8dca2',
'nodeType': 'cm:person', nodeType: 'cm:person',
'properties': { properties: {
'cm:homeFolderProvider': 'bootstrapHomeFolderProvider', 'cm:homeFolderProvider': 'bootstrapHomeFolderProvider',
'cm:preferenceValues': { 'cm:preferenceValues': {
'contentUrl': 'store://2018/4/23/14/42/92bb4aa9-db27-41a4-9804-ddab3cc83d3e.bin', contentUrl: 'store://2018/4/23/14/42/92bb4aa9-db27-41a4-9804-ddab3cc83d3e.bin',
'mimetype': 'text/plain', mimetype: 'text/plain',
'size': 102, size: 102,
'encoding': 'UTF-8', encoding: 'UTF-8',
'locale': 'en', locale: 'en',
'id': 313, id: 313,
'infoUrl': 'contentUrl=store://2018/4/23/14/42/92bb4aa9-db27-41a4-9804-ddab3cc83d3e.bin|mimetype=text/plain|size=102|encoding=UTF-8|locale=en_' infoUrl: 'contentUrl=store://2018/4/23/14/42/92bb4aa9-db27-41a4-9804-ddab3cc83d3e.bin|mimetype=text/plain|size=102|encoding=UTF-8|locale=en_'
}, },
'cm:authorizationStatus': 'AUTHORIZED', 'cm:authorizationStatus': 'AUTHORIZED',
'cm:homeFolder': 'a20cd541-4ada-4525-9807-9fa0a047d9f4', 'cm:homeFolder': 'a20cd541-4ada-4525-9807-9fa0a047d9f4',
@@ -115,72 +115,72 @@ export const fakeAuthorityResults: any[] = [{
'cm:email': 'admin@alfresco.com', 'cm:email': 'admin@alfresco.com',
'cm:firstName': 'Administrator', 'cm:firstName': 'Administrator',
'cm:owner': { 'cm:owner': {
'id': 'admin', id: 'admin',
'displayName': 'Administrator' displayName: 'Administrator'
} }
}, },
'parentId': '063f5d48-a0b3-4cbf-826c-88a4fbfa3336' parentId: '063f5d48-a0b3-4cbf-826c-88a4fbfa3336'
} }
}, },
{ {
'entry': { entry: {
'isFolder': false, isFolder: false,
'search': { search: {
'score': 0.3541112 score: 0.3541112
}, },
'isFile': false, isFile: false,
'name': 'GROUP_ALFRESCO_ADMINISTRATORS', name: 'GROUP_ALFRESCO_ADMINISTRATORS',
'location': 'nodes', location: 'nodes',
'id': 'GROUP_ALFRESCO_ADMINISTRATORS', id: 'GROUP_ALFRESCO_ADMINISTRATORS',
'nodeType': 'cm:authorityContainer', nodeType: 'cm:authorityContainer',
'properties': { properties: {
'cm:authorityName': 'GROUP_ALFRESCO_ADMINISTRATORS' 'cm:authorityName': 'GROUP_ALFRESCO_ADMINISTRATORS'
}, },
'parentId': '030d833e-da8e-4f5c-8ef9-d809638bd04b' parentId: '030d833e-da8e-4f5c-8ef9-d809638bd04b'
} }
}]; }];
export const fakeAuthorityListResult: any = { export const fakeAuthorityListResult: any = {
'list': { list: {
'pagination': { pagination: {
'count': 0, count: 0,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 0, totalItems: 0,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'context': {}, context: {},
'entries': fakeAuthorityResults entries: fakeAuthorityResults
} }
}; };
export const fakeNameListResult: any = { export const fakeNameListResult: any = {
'list': { list: {
'pagination': { pagination: {
'count': 2, count: 2,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 2, totalItems: 2,
'skipCount': 0, skipCount: 0,
'maxItems': 20 maxItems: 20
}, },
'context': { context: {
'consistency': { consistency: {
'lastTxId': 5496 lastTxId: 5496
} }
}, },
'entries': [{ entries: [{
'entry': { entry: {
'aspectNames': ['cm:ownable'], aspectNames: ['cm:ownable'],
'isFolder': false, isFolder: false,
'search': { search: {
'score': 1.0 score: 1.0
}, },
'isFile': false, isFile: false,
'name': '730cd9b0-5617-4865-aee8-90de1d596997', name: '730cd9b0-5617-4865-aee8-90de1d596997',
'location': 'nodes', location: 'nodes',
'id': '730cd9b0-5617-4865-aee8-90de1d596997', id: '730cd9b0-5617-4865-aee8-90de1d596997',
'nodeType': 'cm:person', nodeType: 'cm:person',
'properties': { properties: {
'cm:homeFolderProvider': 'userHomesHomeFolderProvider', 'cm:homeFolderProvider': 'userHomesHomeFolderProvider',
'cm:authorizationStatus': 'NEVER_AUTHORIZED', 'cm:authorizationStatus': 'NEVER_AUTHORIZED',
'cm:homeFolder': '277f505d-6526-45b1-a7b3-c9bdd66f17f6', 'cm:homeFolder': '277f505d-6526-45b1-a7b3-c9bdd66f17f6',
@@ -191,25 +191,25 @@ export const fakeNameListResult: any = {
'cm:sizeQuota': 1073741824, 'cm:sizeQuota': 1073741824,
'cm:firstName': 'firstName', 'cm:firstName': 'firstName',
'cm:owner': { 'cm:owner': {
'id': 'test1', id: 'test1',
'displayName': 'firstName lastName1' displayName: 'firstName lastName1'
} }
}, },
'parentId': '3e9ce910-a4a0-4531-8f80-7734bece6342' parentId: '3e9ce910-a4a0-4531-8f80-7734bece6342'
} }
}, { }, {
'entry': { entry: {
'aspectNames': ['cm:ownable'], aspectNames: ['cm:ownable'],
'isFolder': false, isFolder: false,
'search': { search: {
'score': 1.0 score: 1.0
}, },
'isFile': false, isFile: false,
'name': '3d1e9e57-505f-431e-bb2b-38ad8d5d2d15', name: '3d1e9e57-505f-431e-bb2b-38ad8d5d2d15',
'location': 'nodes', location: 'nodes',
'id': '3d1e9e57-505f-431e-bb2b-38ad8d5d2d15', id: '3d1e9e57-505f-431e-bb2b-38ad8d5d2d15',
'nodeType': 'cm:person', nodeType: 'cm:person',
'properties': { properties: {
'cm:homeFolderProvider': 'userHomesHomeFolderProvider', 'cm:homeFolderProvider': 'userHomesHomeFolderProvider',
'cm:authorizationStatus': 'NEVER_AUTHORIZED', 'cm:authorizationStatus': 'NEVER_AUTHORIZED',
'cm:homeFolder': '81a07ff0-82fb-4bbb-b869-d5fd92e71e17', 'cm:homeFolder': '81a07ff0-82fb-4bbb-b869-d5fd92e71e17',
@@ -220,11 +220,11 @@ export const fakeNameListResult: any = {
'cm:sizeQuota': -1, 'cm:sizeQuota': -1,
'cm:firstName': 'firstName', 'cm:firstName': 'firstName',
'cm:owner': { 'cm:owner': {
'id': 'test11', id: 'test11',
'displayName': 'firstName lastName2' displayName: 'firstName lastName2'
} }
}, },
'parentId': '3e9ce910-a4a0-4531-8f80-7734bece6342' parentId: '3e9ce910-a4a0-4531-8f80-7734bece6342'
} }
}] }]
} }
@@ -64,131 +64,131 @@ export const fakeNodeWithNoPermission = new Node({
}); });
export const fakeNodeAnswerWithEntries = { export const fakeNodeAnswerWithEntries = {
'list': { list: {
'pagination': { pagination: {
'count': 4, count: 4,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 14, totalItems: 14,
'skipCount': 10, skipCount: 10,
'maxItems': 10 maxItems: 10
}, },
'entries': [{ entries: [{
'entry': { entry: {
'isFile': true, isFile: true,
'createdByUser': { 'id': 'admin', 'displayName': 'Administrator' }, createdByUser: { id: 'admin', displayName: 'Administrator' },
'modifiedAt': '2017-05-24T15:08:55.640Z', modifiedAt: '2017-05-24T15:08:55.640Z',
'nodeType': 'cm:content', nodeType: 'cm:content',
'content': { content: {
'mimeType': 'application/rtf', mimeType: 'application/rtf',
'mimeTypeName': 'Rich Text Format', mimeTypeName: 'Rich Text Format',
'sizeInBytes': 14530, sizeInBytes: 14530,
'encoding': 'UTF-8' encoding: 'UTF-8'
}, },
'parentId': 'd124de26-6ba0-4f40-8d98-4907da2d337a', parentId: 'd124de26-6ba0-4f40-8d98-4907da2d337a',
'createdAt': '2017-05-24T15:08:55.640Z', createdAt: '2017-05-24T15:08:55.640Z',
'path': { path: {
'name': '/Company Home/Guest Home', name: '/Company Home/Guest Home',
'isComplete': true, isComplete: true,
'elements': [{ elements: [{
'id': '94acfc73-7014-4475-9bd9-93a2162f0f8c', id: '94acfc73-7014-4475-9bd9-93a2162f0f8c',
'name': 'Company Home' name: 'Company Home'
}, { 'id': 'd124de26-6ba0-4f40-8d98-4907da2d337a', 'name': 'Guest Home' }] }, { id: 'd124de26-6ba0-4f40-8d98-4907da2d337a', name: 'Guest Home' }]
}, },
'isFolder': false, isFolder: false,
'modifiedByUser': { 'id': 'admin', 'displayName': 'Administrator' }, modifiedByUser: { id: 'admin', displayName: 'Administrator' },
'name': 'b_txt_file.rtf', name: 'b_txt_file.rtf',
'id': '67b80f77-dbca-4f58-be6c-71b9dd61ea53', id: '67b80f77-dbca-4f58-be6c-71b9dd61ea53',
'properties': { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' }, properties: { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' },
'allowableOperations': ['delete', 'update'] allowableOperations: ['delete', 'update']
} }
}] }]
} }
}; };
export const fakeNodeAnswerWithNOEntries = { export const fakeNodeAnswerWithNOEntries = {
'list': { list: {
'pagination': { pagination: {
'count': 4, count: 4,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 14, totalItems: 14,
'skipCount': 10, skipCount: 10,
'maxItems': 10 maxItems: 10
}, },
'entries': [] entries: []
} }
}; };
export const fakeGetSitesAnswer = { export const fakeGetSitesAnswer = {
'list': { list: {
'pagination': { pagination: {
'count': 3, count: 3,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 3, totalItems: 3,
'skipCount': 0, skipCount: 0,
'maxItems': 20 maxItems: 20
}, },
'entries': [{ entries: [{
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PRIVATE', visibility: 'PRIVATE',
'guid': 'ac65fdbe-0c79-4f67-bd6a-b89a2768561b', guid: 'ac65fdbe-0c79-4f67-bd6a-b89a2768561b',
'id': 'admin-site', id: 'admin-site',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'Admin Site' title: 'Admin Site'
} }
}, { }, {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319', guid: 'b4cff62a-664d-4d45-9302-98723eac1319',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'swsdp', id: 'swsdp',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'Sample: Web Site Design Project' title: 'Sample: Web Site Design Project'
} }
}, { }, {
'entry': { entry: {
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'af36cf8f-d43c-4a4b-84e6-d1b03e3a2ce5', guid: 'af36cf8f-d43c-4a4b-84e6-d1b03e3a2ce5',
'id': 'test-site', id: 'test-site',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'Test Site' title: 'Test Site'
} }
}] }]
} }
}; };
export const fakeGetSiteMembership = { export const fakeGetSiteMembership = {
'list': { list: {
'pagination': { pagination: {
'count': 2, count: 2,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 2, totalItems: 2,
'skipCount': 0, skipCount: 0,
'maxItems': 20 maxItems: 20
}, },
'entries': [{ entries: [{
'entry': { entry: {
'site': { site: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PRIVATE', visibility: 'PRIVATE',
'guid': 'ac65fdbe-0c79-4f67-bd6a-b89a2768561b', guid: 'ac65fdbe-0c79-4f67-bd6a-b89a2768561b',
'id': 'admin-site', id: 'admin-site',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'Admin Site' title: 'Admin Site'
}, 'role': 'SiteManager', 'guid': 'ac65fdbe-0c79-4f67-bd6a-b89a2768561b', 'id': 'admin-site' }, role: 'SiteManager', guid: 'ac65fdbe-0c79-4f67-bd6a-b89a2768561b', id: 'admin-site'
} }
}, { }, {
'entry': { entry: {
'site': { site: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319', guid: 'b4cff62a-664d-4d45-9302-98723eac1319',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'swsdp', id: 'swsdp',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'Sample: Web Site Design Project' title: 'Sample: Web Site Design Project'
}, 'role': 'SiteManager', 'guid': 'b4cff62a-664d-4d45-9302-98723eac1319', 'id': 'swsdp' }, role: 'SiteManager', guid: 'b4cff62a-664d-4d45-9302-98723eac1319', id: 'swsdp'
} }
}] }]
} }
@@ -217,90 +217,90 @@ export const fakeNodePaging: NodePaging = {
}; };
export const mockNode1 = new Node({ export const mockNode1 = new Node({
'isFile': true, isFile: true,
'createdByUser': { 'id': 'admin', 'displayName': 'Administrator' }, createdByUser: { id: 'admin', displayName: 'Administrator' },
'modifiedAt': '2017-05-24T15:08:55.640Z', modifiedAt: '2017-05-24T15:08:55.640Z',
'nodeType': 'cm:content', nodeType: 'cm:content',
'content': { content: {
'mimeType': 'application/rtf', mimeType: 'application/rtf',
'mimeTypeName': 'Rich Text Format', mimeTypeName: 'Rich Text Format',
'sizeInBytes': 14530, sizeInBytes: 14530,
'encoding': 'UTF-8' encoding: 'UTF-8'
}, },
'parentId': 'd124de26-6ba0-4f40-8d98-4907da2d337a', parentId: 'd124de26-6ba0-4f40-8d98-4907da2d337a',
'createdAt': '2017-05-24T15:08:55.640Z', createdAt: '2017-05-24T15:08:55.640Z',
'path': { path: {
'name': '/Company Home/Guest Home', name: '/Company Home/Guest Home',
'isComplete': true, isComplete: true,
'elements': [{ elements: [{
'id': '94acfc73-7014-4475-9bd9-93a2162f0f8c', id: '94acfc73-7014-4475-9bd9-93a2162f0f8c',
'name': 'Company Home' name: 'Company Home'
}, { 'id': 'd124de26-6ba0-4f40-8d98-4907da2d337a', 'name': 'Guest Home' }] }, { id: 'd124de26-6ba0-4f40-8d98-4907da2d337a', name: 'Guest Home' }]
}, },
'isFolder': false, isFolder: false,
'modifiedByUser': { 'id': 'admin', 'displayName': 'Administrator' }, modifiedByUser: { id: 'admin', displayName: 'Administrator' },
'name': 'b_txt_file.rtf', name: 'b_txt_file.rtf',
'id': '70e1cc6a-6918-468a-b84a-1048093b06fd', id: '70e1cc6a-6918-468a-b84a-1048093b06fd',
'properties': { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' }, properties: { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' },
'allowableOperations': ['delete', 'update'] allowableOperations: ['delete', 'update']
}); });
export const mockNode2 = new Node({ export const mockNode2 = new Node({
'isFile': true, isFile: true,
'createdByUser': { 'id': 'admin', 'displayName': 'Administrator' }, createdByUser: { id: 'admin', displayName: 'Administrator' },
'modifiedAt': '2017-05-24T15:08:55.640Z', modifiedAt: '2017-05-24T15:08:55.640Z',
'nodeType': 'cm:content', nodeType: 'cm:content',
'content': { content: {
'mimeType': 'application/rtf', mimeType: 'application/rtf',
'mimeTypeName': 'Rich Text Format', mimeTypeName: 'Rich Text Format',
'sizeInBytes': 14530, sizeInBytes: 14530,
'encoding': 'UTF-8' encoding: 'UTF-8'
}, },
'parentId': 'd124de26-6ba0-4f40-8d98-4907da2d337a', parentId: 'd124de26-6ba0-4f40-8d98-4907da2d337a',
'createdAt': '2017-05-24T15:08:55.640Z', createdAt: '2017-05-24T15:08:55.640Z',
'path': { path: {
'name': '/Company Home/Guest Home', name: '/Company Home/Guest Home',
'isComplete': true, isComplete: true,
'elements': [{ elements: [{
'id': '94acfc73-7014-4475-9bd9-93a2162f0f8c', id: '94acfc73-7014-4475-9bd9-93a2162f0f8c',
'name': 'Company Home' name: 'Company Home'
}, { 'id': 'd124de26-6ba0-4f40-8d98-4907da2d337a', 'name': 'Guest Home' }] }, { id: 'd124de26-6ba0-4f40-8d98-4907da2d337a', name: 'Guest Home' }]
}, },
'isFolder': false, isFolder: false,
'modifiedByUser': { 'id': 'admin', 'displayName': 'Administrator' }, modifiedByUser: { id: 'admin', displayName: 'Administrator' },
'name': 'b_txt_file.rtf', name: 'b_txt_file.rtf',
'id': '67b80f77-dbca-4f58-be6c-71b9dd61e554', id: '67b80f77-dbca-4f58-be6c-71b9dd61e554',
'properties': { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' }, properties: { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' },
'allowableOperations': ['delete', 'update'] allowableOperations: ['delete', 'update']
}); });
export const mockNode3 = new Node({ export const mockNode3 = new Node({
'isFile': true, isFile: true,
'createdByUser': { 'id': 'admin', 'displayName': 'Administrator' }, createdByUser: { id: 'admin', displayName: 'Administrator' },
'modifiedAt': '2017-05-24T15:08:55.640Z', modifiedAt: '2017-05-24T15:08:55.640Z',
'nodeType': 'cm:content', nodeType: 'cm:content',
'content': { content: {
'mimeType': 'application/rtf', mimeType: 'application/rtf',
'mimeTypeName': 'Rich Text Format', mimeTypeName: 'Rich Text Format',
'sizeInBytes': 14530, sizeInBytes: 14530,
'encoding': 'UTF-8' encoding: 'UTF-8'
}, },
'parentId': 'd124de26-6ba0-4f40-8d98-4907da2d337a', parentId: 'd124de26-6ba0-4f40-8d98-4907da2d337a',
'createdAt': '2017-05-24T15:08:55.640Z', createdAt: '2017-05-24T15:08:55.640Z',
'path': { path: {
'name': '/Company Home/Guest Home', name: '/Company Home/Guest Home',
'isComplete': true, isComplete: true,
'elements': [{ elements: [{
'id': '94acfc73-7014-4475-9bd9-93a2162f0f8c', id: '94acfc73-7014-4475-9bd9-93a2162f0f8c',
'name': 'Company Home' name: 'Company Home'
}, { 'id': 'd124de26-6ba0-4f40-8d98-4907da2d337a', 'name': 'Guest Home' }] }, { id: 'd124de26-6ba0-4f40-8d98-4907da2d337a', name: 'Guest Home' }]
}, },
'isFolder': false, isFolder: false,
'modifiedByUser': { 'id': 'admin', 'displayName': 'Administrator' }, modifiedByUser: { id: 'admin', displayName: 'Administrator' },
'name': 'c_txt_file.rtf', name: 'c_txt_file.rtf',
'id': '67b80f77-dbca-4f58-be6c-71b9dd61e555', id: '67b80f77-dbca-4f58-be6c-71b9dd61e555',
'properties': { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' }, properties: { 'cm:versionLabel': '1.0', 'cm:versionType': 'MAJOR' },
'allowableOperations': ['delete', 'update'] allowableOperations: ['delete', 'update']
}); });
export const mockPreselectedNodes: NodeEntry[] = [ export const mockPreselectedNodes: NodeEntry[] = [
@@ -16,80 +16,80 @@
*/ */
export const fakeNodeWithPermissions: any = { export const fakeNodeWithPermissions: any = {
'aspectNames': [ aspectNames: [
'cm:auditable', 'cm:auditable',
'cm:taggable', 'cm:taggable',
'cm:author', 'cm:author',
'cm:titled', 'cm:titled',
'app:uifacets' 'app:uifacets'
], ],
'createdAt': '2017-11-16T16:29:38.638+0000', createdAt: '2017-11-16T16:29:38.638+0000',
'path': { path: {
'name': '/Company Home/Sites/testsite/documentLibrary', name: '/Company Home/Sites/testsite/documentLibrary',
'isComplete': true, isComplete: true,
'elements': [ elements: [
{ {
'id': '2be275a1-b00d-4e45-83d8-66af43ac2252', id: '2be275a1-b00d-4e45-83d8-66af43ac2252',
'name': 'Company Home' name: 'Company Home'
}, },
{ {
'id': '1be10a97-6eb9-4b60-b6c6-1673900e9631', id: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'name': 'Sites' name: 'Sites'
}, },
{ {
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'name': 'testsite' name: 'testsite'
}, },
{ {
'id': '71626fae-0c04-4d0c-a129-20fa4c178716', id: '71626fae-0c04-4d0c-a129-20fa4c178716',
'name': 'documentLibrary' name: 'documentLibrary'
} }
] ]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'System', id: 'System',
'displayName': 'System' displayName: 'System'
}, },
'modifiedAt': '2018-03-21T03:17:58.783+0000', modifiedAt: '2018-03-21T03:17:58.783+0000',
'permissions': { permissions: {
'inherited': [ inherited: [
{ {
'authorityId': 'guest', authorityId: 'guest',
'name': 'Read', name: 'Read',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
}, },
{ {
'authorityId': 'GROUP_EVERYONE', authorityId: 'GROUP_EVERYONE',
'name': 'Read', name: 'Read',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
} }
], ],
'locallySet': [ locallySet: [
{ {
'authorityId': 'GROUP_EVERYONE', authorityId: 'GROUP_EVERYONE',
'name': 'Contributor', name: 'Contributor',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
} }
], ],
'settable': [ settable: [
'Contributor', 'Contributor',
'Collaborator', 'Collaborator',
'Coordinator', 'Coordinator',
'Editor', 'Editor',
'Consumer' 'Consumer'
], ],
'isInheritanceEnabled': true isInheritanceEnabled: true
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'PedroH Hernandez' displayName: 'PedroH Hernandez'
}, },
'name': 'test', name: 'test',
'id': 'f472543f-7218-403d-917b-7a5861257244', id: 'f472543f-7218-403d-917b-7a5861257244',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'properties': { properties: {
'cm:title': 'test', 'cm:title': 'test',
'cm:author': 'yagud', 'cm:author': 'yagud',
'cm:taggable': [ 'cm:taggable': [
@@ -101,75 +101,75 @@ export const fakeNodeWithPermissions: any = {
}; };
export const fakeNodeInheritedOnly = { export const fakeNodeInheritedOnly = {
'allowableOperations': [ 'updatePermissions' ], allowableOperations: [ 'updatePermissions' ],
'aspectNames': [ aspectNames: [
'cm:auditable', 'cm:auditable',
'cm:taggable', 'cm:taggable',
'cm:author', 'cm:author',
'cm:titled', 'cm:titled',
'app:uifacets' 'app:uifacets'
], ],
'createdAt': '2017-11-16T16:29:38.638+0000', createdAt: '2017-11-16T16:29:38.638+0000',
'path': { path: {
'name': '/Company Home/Sites/testsite/documentLibrary', name: '/Company Home/Sites/testsite/documentLibrary',
'isComplete': true, isComplete: true,
'elements': [ elements: [
{ {
'id': '2be275a1-b00d-4e45-83d8-66af43ac2252', id: '2be275a1-b00d-4e45-83d8-66af43ac2252',
'name': 'Company Home' name: 'Company Home'
}, },
{ {
'id': '1be10a97-6eb9-4b60-b6c6-1673900e9631', id: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'name': 'Sites' name: 'Sites'
}, },
{ {
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'name': 'testsite', name: 'testsite',
'nodeType': 'st:site' nodeType: 'st:site'
}, },
{ {
'id': '71626fae-0c04-4d0c-a129-20fa4c178716', id: '71626fae-0c04-4d0c-a129-20fa4c178716',
'name': 'documentLibrary' name: 'documentLibrary'
} }
] ]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'System', id: 'System',
'displayName': 'System' displayName: 'System'
}, },
'modifiedAt': '2018-03-21T03:17:58.783+0000', modifiedAt: '2018-03-21T03:17:58.783+0000',
'permissions': { permissions: {
'inherited': [ inherited: [
{ {
'authorityId': 'guest', authorityId: 'guest',
'name': 'Read', name: 'Read',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
}, },
{ {
'authorityId': 'GROUP_EVERYONE', authorityId: 'GROUP_EVERYONE',
'name': 'Read', name: 'Read',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
} }
], ],
'settable': [ settable: [
'Contributor', 'Contributor',
'Collaborator', 'Collaborator',
'Coordinator', 'Coordinator',
'Editor', 'Editor',
'Consumer' 'Consumer'
], ],
'isInheritanceEnabled': true isInheritanceEnabled: true
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'PedroH Hernandez' displayName: 'PedroH Hernandez'
}, },
'name': 'test', name: 'test',
'id': 'f472543f-7218-403d-917b-7a5861257244', id: 'f472543f-7218-403d-917b-7a5861257244',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'properties': { properties: {
'cm:title': 'test', 'cm:title': 'test',
'cm:author': 'yagud', 'cm:author': 'yagud',
'cm:taggable': [ 'cm:taggable': [
@@ -181,73 +181,73 @@ export const fakeNodeInheritedOnly = {
}; };
export const fakeReadOnlyNodeInherited = { export const fakeReadOnlyNodeInherited = {
'aspectNames': [ aspectNames: [
'cm:auditable', 'cm:auditable',
'cm:taggable', 'cm:taggable',
'cm:author', 'cm:author',
'cm:titled', 'cm:titled',
'app:uifacets' 'app:uifacets'
], ],
'createdAt': '2017-11-16T16:29:38.638+0000', createdAt: '2017-11-16T16:29:38.638+0000',
'path': { path: {
'name': '/Company Home/Sites/testsite/documentLibrary', name: '/Company Home/Sites/testsite/documentLibrary',
'isComplete': true, isComplete: true,
'elements': [ elements: [
{ {
'id': '2be275a1-b00d-4e45-83d8-66af43ac2252', id: '2be275a1-b00d-4e45-83d8-66af43ac2252',
'name': 'Company Home' name: 'Company Home'
}, },
{ {
'id': '1be10a97-6eb9-4b60-b6c6-1673900e9631', id: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'name': 'Sites' name: 'Sites'
}, },
{ {
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'name': 'testsite' name: 'testsite'
}, },
{ {
'id': '71626fae-0c04-4d0c-a129-20fa4c178716', id: '71626fae-0c04-4d0c-a129-20fa4c178716',
'name': 'documentLibrary' name: 'documentLibrary'
} }
] ]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'System', id: 'System',
'displayName': 'System' displayName: 'System'
}, },
'modifiedAt': '2018-03-21T03:17:58.783+0000', modifiedAt: '2018-03-21T03:17:58.783+0000',
'permissions': { permissions: {
'inherited': [ inherited: [
{ {
'authorityId': 'guest', authorityId: 'guest',
'name': 'Read', name: 'Read',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
}, },
{ {
'authorityId': 'GROUP_EVERYONE', authorityId: 'GROUP_EVERYONE',
'name': 'Read', name: 'Read',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
} }
], ],
'settable': [ settable: [
'Contributor', 'Contributor',
'Collaborator', 'Collaborator',
'Coordinator', 'Coordinator',
'Editor', 'Editor',
'Consumer' 'Consumer'
], ],
'isInheritanceEnabled': true isInheritanceEnabled: true
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'PedroH Hernandez' displayName: 'PedroH Hernandez'
}, },
'name': 'test', name: 'test',
'id': 'f472543f-7218-403d-917b-7a5861257244', id: 'f472543f-7218-403d-917b-7a5861257244',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'properties': { properties: {
'cm:title': 'test', 'cm:title': 'test',
'cm:author': 'yagud', 'cm:author': 'yagud',
'cm:taggable': [ 'cm:taggable': [
@@ -259,68 +259,68 @@ export const fakeReadOnlyNodeInherited = {
}; };
export const fakeNodeWithOnlyLocally: any = { export const fakeNodeWithOnlyLocally: any = {
'aspectNames': [ aspectNames: [
'cm:auditable', 'cm:auditable',
'cm:taggable', 'cm:taggable',
'cm:author', 'cm:author',
'cm:titled', 'cm:titled',
'app:uifacets' 'app:uifacets'
], ],
'createdAt': '2017-11-16T16:29:38.638+0000', createdAt: '2017-11-16T16:29:38.638+0000',
'path': { path: {
'name': '/Company Home/Sites/testsite/documentLibrary', name: '/Company Home/Sites/testsite/documentLibrary',
'isComplete': true, isComplete: true,
'elements': [ elements: [
{ {
'id': '2be275a1-b00d-4e45-83d8-66af43ac2252', id: '2be275a1-b00d-4e45-83d8-66af43ac2252',
'name': 'Company Home' name: 'Company Home'
}, },
{ {
'id': '1be10a97-6eb9-4b60-b6c6-1673900e9631', id: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'name': 'Sites' name: 'Sites'
}, },
{ {
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'name': 'testsite' name: 'testsite'
}, },
{ {
'id': '71626fae-0c04-4d0c-a129-20fa4c178716', id: '71626fae-0c04-4d0c-a129-20fa4c178716',
'name': 'documentLibrary' name: 'documentLibrary'
} }
] ]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'System', id: 'System',
'displayName': 'System' displayName: 'System'
}, },
'modifiedAt': '2018-03-21T03:17:58.783+0000', modifiedAt: '2018-03-21T03:17:58.783+0000',
'permissions': { permissions: {
'locallySet': [ locallySet: [
{ {
'authorityId': 'GROUP_EVERYONE', authorityId: 'GROUP_EVERYONE',
'name': 'Contributor', name: 'Contributor',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
} }
], ],
'settable': [ settable: [
'Contributor', 'Contributor',
'Collaborator', 'Collaborator',
'Coordinator', 'Coordinator',
'Editor', 'Editor',
'Consumer' 'Consumer'
], ],
'isInheritanceEnabled': false isInheritanceEnabled: false
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'PedroH Hernandez' displayName: 'PedroH Hernandez'
}, },
'name': 'test', name: 'test',
'id': 'f472543f-7218-403d-917b-7a5861257244', id: 'f472543f-7218-403d-917b-7a5861257244',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'properties': { properties: {
'cm:title': 'test', 'cm:title': 'test',
'cm:author': 'yagud', 'cm:author': 'yagud',
'cm:taggable': [ 'cm:taggable': [
@@ -332,78 +332,78 @@ export const fakeNodeWithOnlyLocally: any = {
}; };
export const fakeNodeToRemovePermission: any = { export const fakeNodeToRemovePermission: any = {
'aspectNames': [ aspectNames: [
'cm:auditable', 'cm:auditable',
'cm:taggable', 'cm:taggable',
'cm:author', 'cm:author',
'cm:titled', 'cm:titled',
'app:uifacets' 'app:uifacets'
], ],
'createdAt': '2017-11-16T16:29:38.638+0000', createdAt: '2017-11-16T16:29:38.638+0000',
'path': { path: {
'name': '/Company Home/Sites/testsite/documentLibrary', name: '/Company Home/Sites/testsite/documentLibrary',
'isComplete': true, isComplete: true,
'elements': [ elements: [
{ {
'id': '2be275a1-b00d-4e45-83d8-66af43ac2252', id: '2be275a1-b00d-4e45-83d8-66af43ac2252',
'name': 'Company Home' name: 'Company Home'
}, },
{ {
'id': '1be10a97-6eb9-4b60-b6c6-1673900e9631', id: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'name': 'Sites' name: 'Sites'
}, },
{ {
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'name': 'testsite' name: 'testsite'
}, },
{ {
'id': '71626fae-0c04-4d0c-a129-20fa4c178716', id: '71626fae-0c04-4d0c-a129-20fa4c178716',
'name': 'documentLibrary' name: 'documentLibrary'
} }
] ]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'System', id: 'System',
'displayName': 'System' displayName: 'System'
}, },
'modifiedAt': '2018-03-21T03:17:58.783+0000', modifiedAt: '2018-03-21T03:17:58.783+0000',
'permissions': { permissions: {
'locallySet': [ locallySet: [
{ {
'authorityId': 'GROUP_EVERYONE', authorityId: 'GROUP_EVERYONE',
'name': 'Contributor', name: 'Contributor',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
}, },
{ {
'authorityId': 'GROUP_FAKE_1', authorityId: 'GROUP_FAKE_1',
'name': 'Contributor', name: 'Contributor',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
}, },
{ {
'authorityId': 'FAKE_PERSON_1', authorityId: 'FAKE_PERSON_1',
'name': 'Contributor', name: 'Contributor',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
} }
], ],
'settable': [ settable: [
'Contributor', 'Contributor',
'Collaborator', 'Collaborator',
'Coordinator', 'Coordinator',
'Editor', 'Editor',
'Consumer' 'Consumer'
], ],
'isInheritanceEnabled': true isInheritanceEnabled: true
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'PedroH Hernandez' displayName: 'PedroH Hernandez'
}, },
'name': 'test', name: 'test',
'id': 'f472543f-7218-403d-917b-7a5861257244', id: 'f472543f-7218-403d-917b-7a5861257244',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'properties': { properties: {
'cm:title': 'test', 'cm:title': 'test',
'cm:author': 'yagud', 'cm:author': 'yagud',
'cm:taggable': [ 'cm:taggable': [
@@ -415,56 +415,56 @@ export const fakeNodeToRemovePermission: any = {
}; };
export const fakeNodeWithoutPermissions: any = { export const fakeNodeWithoutPermissions: any = {
'aspectNames': [ aspectNames: [
'cm:auditable', 'cm:auditable',
'cm:taggable', 'cm:taggable',
'cm:author', 'cm:author',
'cm:titled', 'cm:titled',
'app:uifacets' 'app:uifacets'
], ],
'createdAt': '2017-11-16T16:29:38.638+0000', createdAt: '2017-11-16T16:29:38.638+0000',
'path': { path: {
'name': '/Company Home/Sites/testsite/documentLibrary', name: '/Company Home/Sites/testsite/documentLibrary',
'isComplete': true, isComplete: true,
'elements': [ elements: [
{ {
'id': '2be275a1-b00d-4e45-83d8-66af43ac2252', id: '2be275a1-b00d-4e45-83d8-66af43ac2252',
'name': 'Company Home' name: 'Company Home'
}, },
{ {
'id': '1be10a97-6eb9-4b60-b6c6-1673900e9631', id: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'name': 'Sites' name: 'Sites'
}, },
{ {
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'name': 'testsite' name: 'testsite'
}, },
{ {
'id': '71626fae-0c04-4d0c-a129-20fa4c178716', id: '71626fae-0c04-4d0c-a129-20fa4c178716',
'name': 'documentLibrary' name: 'documentLibrary'
} }
] ]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'System', id: 'System',
'displayName': 'System' displayName: 'System'
}, },
'modifiedAt': '2018-03-21T03:17:58.783+0000', modifiedAt: '2018-03-21T03:17:58.783+0000',
'permissions': { permissions: {
'locallySet': [], locallySet: [],
'settable': [], settable: [],
'isInheritanceEnabled': false isInheritanceEnabled: false
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'PedroH Hernandez' displayName: 'PedroH Hernandez'
}, },
'name': 'test', name: 'test',
'id': 'f472543f-7218-403d-917b-7a5861257244', id: 'f472543f-7218-403d-917b-7a5861257244',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'properties': { properties: {
'cm:title': 'test', 'cm:title': 'test',
'cm:author': 'yagud', 'cm:author': 'yagud',
'cm:taggable': [ 'cm:taggable': [
@@ -476,45 +476,45 @@ export const fakeNodeWithoutPermissions: any = {
}; };
export const fakeSiteNodeResponse: any = { export const fakeSiteNodeResponse: any = {
'list': { list: {
'pagination': { pagination: {
'count': 1, count: 1,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 1, totalItems: 1,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'context': {}, context: {},
'entries': [ entries: [
{ {
'entry': { entry: {
'isLink': false, isLink: false,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'admin', id: 'admin',
'displayName': 'Administrator' displayName: 'Administrator'
}, },
'modifiedAt': '2018-03-22T15:40:10.093+0000', modifiedAt: '2018-03-22T15:40:10.093+0000',
'nodeType': 'st:site', nodeType: 'st:site',
'parentId': '1be10a97-6eb9-4b60-b6c6-1673900e9631', parentId: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'aspectNames': [ aspectNames: [
'cm:tagscope', 'cm:tagscope',
'cm:titled', 'cm:titled',
'cm:auditable' 'cm:auditable'
], ],
'createdAt': '2018-03-22T15:39:50.821+0000', createdAt: '2018-03-22T15:39:50.821+0000',
'isFolder': true, isFolder: true,
'search': { search: {
'score': 10.292057 score: 10.292057
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'Administrator' displayName: 'Administrator'
}, },
'name': 'testsite', name: 'testsite',
'location': 'nodes', location: 'nodes',
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'properties': { properties: {
'st:siteVisibility': 'PUBLIC', 'st:siteVisibility': 'PUBLIC',
'cm:title': 'TEST_SITE', 'cm:title': 'TEST_SITE',
'st:sitePreset': 'site-dashboard' 'st:sitePreset': 'site-dashboard'
@@ -526,41 +526,41 @@ export const fakeSiteNodeResponse: any = {
}; };
export const fakeSiteRoles: any = { export const fakeSiteRoles: any = {
'list': { list: {
'pagination': { pagination: {
'count': 4, count: 4,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 4, totalItems: 4,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'displayName': 'site_testsite_SiteCollaborator', displayName: 'site_testsite_SiteCollaborator',
'id': 'GROUP_site_testsite_SiteCollaborator', id: 'GROUP_site_testsite_SiteCollaborator',
'memberType': 'GROUP' memberType: 'GROUP'
} }
}, },
{ {
'entry': { entry: {
'displayName': 'site_testsite_SiteConsumer', displayName: 'site_testsite_SiteConsumer',
'id': 'GROUP_site_testsite_SiteConsumer', id: 'GROUP_site_testsite_SiteConsumer',
'memberType': 'GROUP' memberType: 'GROUP'
} }
}, },
{ {
'entry': { entry: {
'displayName': 'site_testsite_SiteContributor', displayName: 'site_testsite_SiteContributor',
'id': 'GROUP_site_testsite_SiteContributor', id: 'GROUP_site_testsite_SiteContributor',
'memberType': 'GROUP' memberType: 'GROUP'
} }
}, },
{ {
'entry': { entry: {
'displayName': 'site_testsite_SiteManager', displayName: 'site_testsite_SiteManager',
'id': 'GROUP_site_testsite_SiteManager', id: 'GROUP_site_testsite_SiteManager',
'memberType': 'GROUP' memberType: 'GROUP'
} }
} }
] ]
@@ -568,89 +568,89 @@ export const fakeSiteRoles: any = {
}; };
export const fakeEmptyResponse: any = { export const fakeEmptyResponse: any = {
'list': { list: {
'pagination': { pagination: {
'count': 0, count: 0,
'hasMoreItems': false, hasMoreItems: false,
'totalItems': 0, totalItems: 0,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'context': {}, context: {},
'entries': [] entries: []
} }
}; };
export const fakeNodeLocalSiteManager = { export const fakeNodeLocalSiteManager = {
'allowableOperations': [ 'updatePermissions' ], allowableOperations: [ 'updatePermissions' ],
'aspectNames': [ aspectNames: [
'cm:auditable', 'cm:auditable',
'cm:taggable', 'cm:taggable',
'cm:author', 'cm:author',
'cm:titled', 'cm:titled',
'app:uifacets' 'app:uifacets'
], ],
'createdAt': '2017-11-16T16:29:38.638+0000', createdAt: '2017-11-16T16:29:38.638+0000',
'path': { path: {
'name': '/Company Home/Sites/testsite/documentLibrary', name: '/Company Home/Sites/testsite/documentLibrary',
'isComplete': true, isComplete: true,
'elements': [ elements: [
{ {
'id': '2be275a1-b00d-4e45-83d8-66af43ac2252', id: '2be275a1-b00d-4e45-83d8-66af43ac2252',
'name': 'Company Home' name: 'Company Home'
}, },
{ {
'id': '1be10a97-6eb9-4b60-b6c6-1673900e9631', id: '1be10a97-6eb9-4b60-b6c6-1673900e9631',
'name': 'Sites' name: 'Sites'
}, },
{ {
'id': 'e002c740-b8f9-482a-a554-8fff4e4c9dc0', id: 'e002c740-b8f9-482a-a554-8fff4e4c9dc0',
'name': 'testsite', name: 'testsite',
'nodeType': 'st:site' nodeType: 'st:site'
}, },
{ {
'id': '71626fae-0c04-4d0c-a129-20fa4c178716', id: '71626fae-0c04-4d0c-a129-20fa4c178716',
'name': 'documentLibrary' name: 'documentLibrary'
} }
] ]
}, },
'isFolder': true, isFolder: true,
'isFile': false, isFile: false,
'createdByUser': { createdByUser: {
'id': 'System', id: 'System',
'displayName': 'System' displayName: 'System'
}, },
'modifiedAt': '2018-03-21T03:17:58.783+0000', modifiedAt: '2018-03-21T03:17:58.783+0000',
'permissions': { permissions: {
'locallySet': [ locallySet: [
{ {
'authorityId': 'GROUP_site_testsite_SiteManager', authorityId: 'GROUP_site_testsite_SiteManager',
'name': 'SiteManager', name: 'SiteManager',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
}, },
{ {
'authorityId': 'superadminuser', authorityId: 'superadminuser',
'name': 'SiteCollaborator', name: 'SiteCollaborator',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
} }
], ],
'settable': [ settable: [
'Contributor', 'Contributor',
'Collaborator', 'Collaborator',
'Coordinator', 'Coordinator',
'Editor', 'Editor',
'Consumer' 'Consumer'
], ],
'isInheritanceEnabled': false isInheritanceEnabled: false
}, },
'modifiedByUser': { modifiedByUser: {
'id': 'admin', id: 'admin',
'displayName': 'PedroH Hernandez' displayName: 'PedroH Hernandez'
}, },
'name': 'test', name: 'test',
'id': 'f472543f-7218-403d-917b-7a5861257244', id: 'f472543f-7218-403d-917b-7a5861257244',
'nodeType': 'cm:folder', nodeType: 'cm:folder',
'properties': { properties: {
'cm:title': 'test', 'cm:title': 'test',
'cm:author': 'yagud', 'cm:author': 'yagud',
'cm:taggable': [ 'cm:taggable': [
@@ -39,11 +39,11 @@ export const disabledCategories = [
component: { component: {
selector: 'check-list', selector: 'check-list',
settings: { settings: {
'field': null, field: null,
'pageSize': 5, pageSize: 5,
'options': [ options: [
{ 'name': 'Folder', 'value': `TYPE:'cm:folder'` }, { name: 'Folder', value: `TYPE:'cm:folder'` },
{ 'name': 'Document', 'value': `TYPE:'cm:content'` } { name: 'Document', value: `TYPE:'cm:content'` }
] ]
} }
} }
@@ -59,11 +59,11 @@ export const expandedCategories = [
component: { component: {
selector: 'check-list', selector: 'check-list',
settings: { settings: {
'field': null, field: null,
'pageSize': 5, pageSize: 5,
'options': [ options: [
{ 'name': 'Folder', 'value': `TYPE:'cm:folder'` }, { name: 'Folder', value: `TYPE:'cm:folder'` },
{ 'name': 'Document', 'value': `TYPE:'cm:content'` } { name: 'Document', value: `TYPE:'cm:content'` }
] ]
} }
} }
@@ -91,11 +91,11 @@ export const simpleCategories: SearchCategory[] = [
component: { component: {
selector: 'check-list', selector: 'check-list',
settings: { settings: {
'field': 'check-list', field: 'check-list',
'pageSize': 5, pageSize: 5,
'options': [ options: [
{ 'name': 'Folder', 'value': `TYPE:'cm:folder'` }, { name: 'Folder', value: `TYPE:'cm:folder'` },
{ 'name': 'Document', 'value': `TYPE:'cm:content'` } { name: 'Document', value: `TYPE:'cm:content'` }
] ]
} }
} }
@@ -107,288 +107,288 @@ export const searchFilter = {
'app:fields': [ 'app:fields': [
'cm:name' 'cm:name'
], ],
'include': [ include: [
'allowableOperations' 'allowableOperations'
], ],
'sorting': { sorting: {
'options': [ options: [
{ {
'key': 'name', key: 'name',
'label': 'Name', label: 'Name',
'type': 'FIELD', type: 'FIELD',
'field': 'cm:name', field: 'cm:name',
'ascending': true ascending: true
} }
], ],
'defaults': [ defaults: [
{ {
'key': 'score', key: 'score',
'type': 'FIELD', type: 'FIELD',
'field': 'score', field: 'score',
'ascending': false ascending: false
} }
] ]
}, },
'resetButton': true, resetButton: true,
'filterQueries': [ filterQueries: [
{ {
'query': `TYPE:'cm:folder' OR TYPE:'cm:content'` query: `TYPE:'cm:folder' OR TYPE:'cm:content'`
}, },
{ {
'query': 'NOT cm:creator:System' query: 'NOT cm:creator:System'
} }
], ],
'facetFields': { facetFields: {
'expanded': true, expanded: true,
'fields': [ fields: [
{ {
'field': 'content.mimetype', field: 'content.mimetype',
'mincount': 1, mincount: 1,
'label': 'SEARCH.FACET_FIELDS.TYPE' label: 'SEARCH.FACET_FIELDS.TYPE'
}, },
{ {
'field': 'content.size', field: 'content.size',
'mincount': 1, mincount: 1,
'label': 'SEARCH.FACET_FIELDS.SIZE' label: 'SEARCH.FACET_FIELDS.SIZE'
}, },
{ {
'field': 'creator', field: 'creator',
'mincount': 1, mincount: 1,
'label': 'SEARCH.FACET_FIELDS.CREATOR' label: 'SEARCH.FACET_FIELDS.CREATOR'
}, },
{ {
'field': 'modifier', field: 'modifier',
'mincount': 1, mincount: 1,
'label': 'SEARCH.FACET_FIELDS.MODIFIER' label: 'SEARCH.FACET_FIELDS.MODIFIER'
}, },
{ {
'field': 'created', field: 'created',
'mincount': 1, mincount: 1,
'label': 'SEARCH.FACET_FIELDS.CREATED' label: 'SEARCH.FACET_FIELDS.CREATED'
} }
] ]
}, },
'facetQueries': { facetQueries: {
'label': 'SEARCH.FACET_QUERIES.MY_FACET_QUERIES', label: 'SEARCH.FACET_QUERIES.MY_FACET_QUERIES',
'pageSize': 5, pageSize: 5,
'expanded': true, expanded: true,
'mincount': 1, mincount: 1,
'queries': [ queries: [
{ {
'query': 'created:2019', query: 'created:2019',
'label': 'SEARCH.FACET_QUERIES.CREATED_THIS_YEAR' label: 'SEARCH.FACET_QUERIES.CREATED_THIS_YEAR'
}, },
{ {
'query': 'content.mimetype:text/html', query: 'content.mimetype:text/html',
'label': 'SEARCH.FACET_QUERIES.MIMETYPE', label: 'SEARCH.FACET_QUERIES.MIMETYPE',
'group': 'Type facet queries' group: 'Type facet queries'
}, },
{ {
'query': 'content.size:[0 TO 10240]', query: 'content.size:[0 TO 10240]',
'label': 'Extra Small', label: 'Extra Small',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[10240 TO 102400]', query: 'content.size:[10240 TO 102400]',
'label': 'SEARCH.FACET_QUERIES.SMALL', label: 'SEARCH.FACET_QUERIES.SMALL',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[102400 TO 1048576]', query: 'content.size:[102400 TO 1048576]',
'label': 'SEARCH.FACET_QUERIES.MEDIUM', label: 'SEARCH.FACET_QUERIES.MEDIUM',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[1048576 TO 16777216]', query: 'content.size:[1048576 TO 16777216]',
'label': 'SEARCH.FACET_QUERIES.LARGE', label: 'SEARCH.FACET_QUERIES.LARGE',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[16777216 TO 134217728]', query: 'content.size:[16777216 TO 134217728]',
'label': 'SEARCH.FACET_QUERIES.XTRALARGE', label: 'SEARCH.FACET_QUERIES.XTRALARGE',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[134217728 TO MAX]', query: 'content.size:[134217728 TO MAX]',
'label': 'SEARCH.FACET_QUERIES.XXTRALARGE', label: 'SEARCH.FACET_QUERIES.XXTRALARGE',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[111111 TO MAX]', query: 'content.size:[111111 TO MAX]',
'label': 'my1', label: 'my1',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[222222 TO MAX]', query: 'content.size:[222222 TO MAX]',
'label': 'my2', label: 'my2',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[333333 TO MAX]', query: 'content.size:[333333 TO MAX]',
'label': 'my3', label: 'my3',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[444444 TO MAX]', query: 'content.size:[444444 TO MAX]',
'label': 'my4', label: 'my4',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[5555 TO MAX]', query: 'content.size:[5555 TO MAX]',
'label': 'my5', label: 'my5',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[666666 TO MAX]', query: 'content.size:[666666 TO MAX]',
'label': 'my6', label: 'my6',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[777777 TO MAX]', query: 'content.size:[777777 TO MAX]',
'label': 'my7', label: 'my7',
'group': 'Size facet queries' group: 'Size facet queries'
}, },
{ {
'query': 'content.size:[888888 TO MAX]', query: 'content.size:[888888 TO MAX]',
'label': 'my8', label: 'my8',
'group': 'Size facet queries' group: 'Size facet queries'
} }
] ]
}, },
'facetIntervals': { facetIntervals: {
'expanded': true, expanded: true,
'intervals': [ intervals: [
{ {
'label': 'The Created', label: 'The Created',
'field': 'cm:created', field: 'cm:created',
'sets': [ sets: [
{ {
'label': 'lastYear', label: 'lastYear',
'start': '2018', start: '2018',
'end': '2019', end: '2019',
'endInclusive': false endInclusive: false
}, },
{ {
'label': 'currentYear', label: 'currentYear',
'start': 'NOW/YEAR', start: 'NOW/YEAR',
'end': 'NOW/YEAR+1YEAR' end: 'NOW/YEAR+1YEAR'
}, },
{ {
'label': 'earlier', label: 'earlier',
'start': '*', start: '*',
'end': '2018', end: '2018',
'endInclusive': false endInclusive: false
} }
] ]
}, },
{ {
'label': 'TheModified', label: 'TheModified',
'field': 'cm:modified', field: 'cm:modified',
'sets': [ sets: [
{ {
'label': '2017', label: '2017',
'start': '2017', start: '2017',
'end': '2018', end: '2018',
'endInclusive': false endInclusive: false
}, },
{ {
'label': '2017-2018', label: '2017-2018',
'start': '2017', start: '2017',
'end': '2018', end: '2018',
'endInclusive': true endInclusive: true
}, },
{ {
'label': 'currentYear', label: 'currentYear',
'start': 'NOW/YEAR', start: 'NOW/YEAR',
'end': 'NOW/YEAR+1YEAR' end: 'NOW/YEAR+1YEAR'
}, },
{ {
'label': 'earlierThan2017', label: 'earlierThan2017',
'start': '*', start: '*',
'end': '2017', end: '2017',
'endInclusive': false endInclusive: false
} }
] ]
} }
] ]
}, },
'categories': [ categories: [
{ {
'id': 'queryName', id: 'queryName',
'name': 'Name', name: 'Name',
'enabled': true, enabled: true,
'expanded': true, expanded: true,
'component': { component: {
'selector': 'text', selector: 'text',
'settings': { settings: {
'pattern': `cm:name:'(.*?)'`, pattern: `cm:name:'(.*?)'`,
'field': 'cm:name', field: 'cm:name',
'placeholder': 'Enter the name' placeholder: 'Enter the name'
} }
} }
}, },
{ {
'id': 'checkList', id: 'checkList',
'name': 'Check List', name: 'Check List',
'enabled': true, enabled: true,
'component': { component: {
'selector': 'check-list', selector: 'check-list',
'settings': { settings: {
'pageSize': 5, pageSize: 5,
'operator': 'OR', operator: 'OR',
'options': [] options: []
} }
} }
}, },
{ {
'id': 'contentSize', id: 'contentSize',
'name': 'Content Size', name: 'Content Size',
'enabled': true, enabled: true,
'component': { component: {
'selector': 'slider', selector: 'slider',
'settings': { settings: {
'field': 'cm:content.size', field: 'cm:content.size',
'min': 0, min: 0,
'max': 18, max: 18,
'step': 1, step: 1,
'thumbLabel': true thumbLabel: true
} }
} }
}, },
{ {
'id': 'contentSizeRange', id: 'contentSizeRange',
'name': 'Content Size (range)', name: 'Content Size (range)',
'enabled': true, enabled: true,
'component': { component: {
'selector': 'number-range', selector: 'number-range',
'settings': { settings: {
'field': 'cm:content.size', field: 'cm:content.size',
'format': '[{FROM} TO {TO}]' format: '[{FROM} TO {TO}]'
} }
} }
}, },
{ {
'id': 'createdDateRange', id: 'createdDateRange',
'name': 'Created Date (range)', name: 'Created Date (range)',
'enabled': true, enabled: true,
'component': { component: {
'selector': 'date-range', selector: 'date-range',
'settings': { settings: {
'field': 'cm:created', field: 'cm:created',
'dateFormat': 'DD-MMM-YY' dateFormat: 'DD-MMM-YY'
} }
} }
}, },
{ {
'id': 'queryType', id: 'queryType',
'name': 'Type', name: 'Type',
'enabled': true, enabled: true,
'component': { component: {
'selector': 'radio', selector: 'radio',
'settings': { settings: {
'field': null, field: null,
'pageSize': 5, pageSize: 5,
'options': [] options: []
} }
} }
} }
@@ -396,119 +396,119 @@ export const searchFilter = {
}; };
export const mockSearchResult = { export const mockSearchResult = {
'list': { list: {
'pagination': { 'count': 20, 'hasMoreItems': true, 'totalItems': 20284, 'skipCount': 0, 'maxItems': 20 }, pagination: { count: 20, hasMoreItems: true, totalItems: 20284, skipCount: 0, maxItems: 20 },
'context': { context: {
'consistency': { 'lastTxId': 122854 }, consistency: { lastTxId: 122854 },
'facets': [ facets: [
{ {
'type': 'query', type: 'query',
'label': 'Type facet queries', label: 'Type facet queries',
'buckets': [ buckets: [
{ {
'label': 'SEARCH.FACET_QUERIES.MIMETYPE', label: 'SEARCH.FACET_QUERIES.MIMETYPE',
'filterQuery': 'content.mimetype:text/html', filterQuery: 'content.mimetype:text/html',
'metrics': [{ 'type': 'count', 'value': { 'count': 13 } }] metrics: [{ type: 'count', value: { count: 13 } }]
}] }]
}, { }, {
'type': 'query', type: 'query',
'label': 'Size facet queries', label: 'Size facet queries',
'buckets': [ buckets: [
{ {
'label': 'my1', label: 'my1',
'filterQuery': 'content.size:[111111 TO MAX]', filterQuery: 'content.size:[111111 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 806 } }] metrics: [{ type: 'count', value: { count: 806 } }]
}, { }, {
'label': 'my3', label: 'my3',
'filterQuery': 'content.size:[333333 TO MAX]', filterQuery: 'content.size:[333333 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 669 } }] metrics: [{ type: 'count', value: { count: 669 } }]
}, { }, {
'label': 'my2', label: 'my2',
'filterQuery': 'content.size:[222222 TO MAX]', filterQuery: 'content.size:[222222 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 691 } }] metrics: [{ type: 'count', value: { count: 691 } }]
}, { }, {
'label': 'my5', label: 'my5',
'filterQuery': 'content.size:[5555 TO MAX]', filterQuery: 'content.size:[5555 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 1866 } }] metrics: [{ type: 'count', value: { count: 1866 } }]
}, { }, {
'label': 'my4', label: 'my4',
'filterQuery': 'content.size:[444444 TO MAX]', filterQuery: 'content.size:[444444 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 665 } }] metrics: [{ type: 'count', value: { count: 665 } }]
}, { }, {
'label': 'my7', label: 'my7',
'filterQuery': 'content.size:[777777 TO MAX]', filterQuery: 'content.size:[777777 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 641 } }] metrics: [{ type: 'count', value: { count: 641 } }]
}, { }, {
'label': 'SEARCH.FACET_QUERIES.SMALL', label: 'SEARCH.FACET_QUERIES.SMALL',
'filterQuery': 'content.size:[10240 TO 102400]', filterQuery: 'content.size:[10240 TO 102400]',
'metrics': [{ 'type': 'count', 'value': { 'count': 526 } }] metrics: [{ type: 'count', value: { count: 526 } }]
}, { }, {
'label': 'my6', label: 'my6',
'filterQuery': 'content.size:[666666 TO MAX]', filterQuery: 'content.size:[666666 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 652 } }] metrics: [{ type: 'count', value: { count: 652 } }]
}, { }, {
'label': 'SEARCH.FACET_QUERIES.XTRALARGE', label: 'SEARCH.FACET_QUERIES.XTRALARGE',
'filterQuery': 'content.size:[16777216 TO 134217728]', filterQuery: 'content.size:[16777216 TO 134217728]',
'metrics': [{ 'type': 'count', 'value': { 'count': 617 } }] metrics: [{ type: 'count', value: { count: 617 } }]
}, { }, {
'label': 'my8', label: 'my8',
'filterQuery': 'content.size:[888888 TO MAX]', filterQuery: 'content.size:[888888 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 641 } }] metrics: [{ type: 'count', value: { count: 641 } }]
}, { }, {
'label': 'SEARCH.FACET_QUERIES.XXTRALARGE', label: 'SEARCH.FACET_QUERIES.XXTRALARGE',
'filterQuery': 'content.size:[134217728 TO MAX]', filterQuery: 'content.size:[134217728 TO MAX]',
'metrics': [{ 'type': 'count', 'value': { 'count': 0 } }] metrics: [{ type: 'count', value: { count: 0 } }]
}, { }, {
'label': 'SEARCH.FACET_QUERIES.MEDIUM', label: 'SEARCH.FACET_QUERIES.MEDIUM',
'filterQuery': 'content.size:[102400 TO 1048576]', filterQuery: 'content.size:[102400 TO 1048576]',
'metrics': [{ 'type': 'count', 'value': { 'count': 630 } }] metrics: [{ type: 'count', value: { count: 630 } }]
}, { }, {
'label': 'SEARCH.FACET_QUERIES.LARGE', label: 'SEARCH.FACET_QUERIES.LARGE',
'filterQuery': 'content.size:[1048576 TO 16777216]', filterQuery: 'content.size:[1048576 TO 16777216]',
'metrics': [{ 'type': 'count', 'value': { 'count': 23 } }] metrics: [{ type: 'count', value: { count: 23 } }]
}, { }, {
'label': 'Extra Small', label: 'Extra Small',
'filterQuery': 'content.size:[0 TO 10240]', filterQuery: 'content.size:[0 TO 10240]',
'metrics': [{ 'type': 'count', 'value': { 'count': 10239 } }] metrics: [{ type: 'count', value: { count: 10239 } }]
}] }]
}, { }, {
'type': 'query', type: 'query',
'label': 'SEARCH.FACET_QUERIES.MY_FACET_QUERIES', label: 'SEARCH.FACET_QUERIES.MY_FACET_QUERIES',
'buckets': [ buckets: [
{ {
'label': 'SEARCH.FACET_QUERIES.CREATED_THIS_YEAR', label: 'SEARCH.FACET_QUERIES.CREATED_THIS_YEAR',
'filterQuery': 'created:2019', filterQuery: 'created:2019',
'metrics': [{ 'type': 'count', 'value': { 'count': 0 } }] metrics: [{ type: 'count', value: { count: 0 } }]
}] }]
}, },
{ {
'type': 'field', type: 'field',
'label': 'SEARCH.FACET_FIELDS.SIZE', label: 'SEARCH.FACET_FIELDS.SIZE',
'buckets': [] buckets: []
}, { }, {
'type': 'field', type: 'field',
'label': 'SEARCH.FACET_FIELDS.CREATED', label: 'SEARCH.FACET_FIELDS.CREATED',
'buckets': [] buckets: []
}, { }, {
'type': 'field', type: 'field',
'label': 'SEARCH.FACET_FIELDS.TYPE', label: 'SEARCH.FACET_FIELDS.TYPE',
'buckets': [] buckets: []
}, { }, {
'type': 'field', type: 'field',
'label': 'SEARCH.FACET_FIELDS.MODIFIER', label: 'SEARCH.FACET_FIELDS.MODIFIER',
'buckets': [] buckets: []
}, { }, {
'type': 'field', type: 'field',
'label': 'SEARCH.FACET_FIELDS.CREATOR', label: 'SEARCH.FACET_FIELDS.CREATOR',
'buckets': [] buckets: []
}, { }, {
'type': 'interval', type: 'interval',
'label': 'TheModified', label: 'TheModified',
'buckets': [] buckets: []
}, { }, {
'type': 'interval', type: 'interval',
'label': 'The Created', label: 'The Created',
'buckets': [] buckets: []
}] }]
} }
} }
@@ -553,56 +553,56 @@ export const stepThree = [
export const sizeOptions = [ export const sizeOptions = [
{ {
'name': 'Extra Small (10239)', name: 'Extra Small (10239)',
'value': 'Extra Small (10239)' value: 'Extra Small (10239)'
}, },
{ {
'name': 'SEARCH.FACET_QUERIES.SMALL (526)', name: 'SEARCH.FACET_QUERIES.SMALL (526)',
'value': 'SEARCH.FACET_QUERIES.SMALL (526)' value: 'SEARCH.FACET_QUERIES.SMALL (526)'
}, },
{ {
'name': 'SEARCH.FACET_QUERIES.MEDIUM (630)', name: 'SEARCH.FACET_QUERIES.MEDIUM (630)',
'value': 'SEARCH.FACET_QUERIES.MEDIUM (630)' value: 'SEARCH.FACET_QUERIES.MEDIUM (630)'
}, },
{ {
'name': 'SEARCH.FACET_QUERIES.LARGE (23)', name: 'SEARCH.FACET_QUERIES.LARGE (23)',
'value': 'SEARCH.FACET_QUERIES.LARGE (23)' value: 'SEARCH.FACET_QUERIES.LARGE (23)'
}, },
{ {
'name': 'SEARCH.FACET_QUERIES.XTRALARGE (617)', name: 'SEARCH.FACET_QUERIES.XTRALARGE (617)',
'value': 'SEARCH.FACET_QUERIES.XTRALARGE (617)' value: 'SEARCH.FACET_QUERIES.XTRALARGE (617)'
}, },
{ {
'name': 'my1 (806)', name: 'my1 (806)',
'group': 'my1 (806)' group: 'my1 (806)'
}, },
{ {
'name': 'my2 (691)', name: 'my2 (691)',
'value': 'my2 (691)' value: 'my2 (691)'
}, },
{ {
'name': 'my3 (669)', name: 'my3 (669)',
'value': 'my3 (669)' value: 'my3 (669)'
}, },
{ {
'name': 'my4 (665)', name: 'my4 (665)',
'value': 'my4 (665)' value: 'my4 (665)'
}, },
{ {
'name': 'my5 (1866)', name: 'my5 (1866)',
'group': 'my5 (1866)' group: 'my5 (1866)'
}, },
{ {
'name': 'my6 (652)', name: 'my6 (652)',
'group': 'my6 (652)' group: 'my6 (652)'
}, },
{ {
'name': 'my7 (641)', name: 'my7 (641)',
'value': 'my7 (641)' value: 'my7 (641)'
}, },
{ {
'name': 'my8 (641)', name: 'my8 (641)',
'value': 'my8 (641)' value: 'my8 (641)'
} }
]; ];
@@ -615,20 +615,20 @@ export const filteredResult = [
]; ];
export const mockContentSizeResponseBucket = { export const mockContentSizeResponseBucket = {
'label': '5875', label: '5875',
'filterQuery': 'content.size:5875', filterQuery: 'content.size:5875',
'metrics': [ metrics: [
{ {
'type': 'count', type: 'count',
'value': { value: {
'count': 364 count: 364
} }
} }
] ]
}; };
export function getMockSearchResultWithResponseBucket() { export const getMockSearchResultWithResponseBucket = () => {
const cloneResult = JSON.parse(JSON.stringify( mockSearchResult)); const cloneResult = JSON.parse(JSON.stringify( mockSearchResult));
cloneResult.list.context.facets[3].buckets.push(mockContentSizeResponseBucket); cloneResult.list.context.facets[3].buckets.push(mockContentSizeResponseBucket);
return cloneResult; return cloneResult;
} };
@@ -17,7 +17,7 @@
import { QueryBody } from '@alfresco/js-api'; import { QueryBody } from '@alfresco/js-api';
export const mockQueryBody: QueryBody = <QueryBody> { export const mockQueryBody: QueryBody = {
query: { query: {
query: '(search-term*)', query: '(search-term*)',
language: 'afts' language: 'afts'
@@ -38,4 +38,4 @@ export const mockQueryBody: QueryBody = <QueryBody> {
}, },
highlight: null, highlight: null,
facetFormat: 'V2' facetFormat: 'V2'
}; } as QueryBody;
@@ -53,7 +53,7 @@ const entryDifferentItem = {
} }
}; };
export let result = new ResultSetPaging({ export const result = new ResultSetPaging({
list: { list: {
entries: [ entries: [
entryItem entryItem
@@ -61,7 +61,7 @@ export let result = new ResultSetPaging({
} }
}); });
export let differentResult = new ResultSetPaging({ export const differentResult = new ResultSetPaging({
list: { list: {
entries: [ entries: [
entryDifferentItem entryDifferentItem
@@ -69,7 +69,7 @@ export let differentResult = new ResultSetPaging({
} }
}); });
export let results = { export const results = {
list: { list: {
entries: [ entries: [
entryItem, entryItem,
@@ -79,7 +79,7 @@ export let results = {
} }
}; };
export let folderResult = { export const folderResult = {
list: { list: {
entries: [ entries: [
{ {
@@ -100,13 +100,13 @@ export let folderResult = {
} }
}; };
export let noResult = { export const noResult = {
list: { list: {
entries: [] entries: []
} }
}; };
export let errorJson = { export const errorJson = {
error: { error: {
errorKey: 'Search failed', errorKey: 'Search failed',
statusCode: 400, statusCode: 400,
@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
export let fakeSearch = { export const fakeSearch = {
list: { list: {
pagination: { pagination: {
count: 1, count: 1,
@@ -44,7 +44,7 @@ export let fakeSearch = {
} }
}; };
export let mockError = { export const mockError = {
error: { error: {
errorKey: 'Search failed', errorKey: 'Search failed',
statusCode: 400, statusCode: 400,
@@ -54,7 +54,7 @@ export let mockError = {
} }
}; };
export let searchMockApi = { export const searchMockApi = {
core: { core: {
queriesApi: { queriesApi: {
findNodes: () => Promise.resolve(fakeSearch) findNodes: () => Promise.resolve(fakeSearch)
@@ -18,222 +18,213 @@
import { SitePaging } from '@alfresco/js-api'; import { SitePaging } from '@alfresco/js-api';
/* We are using functions instead of constants here to pass a new instance of the object each time */ /* We are using functions instead of constants here to pass a new instance of the object each time */
export function getFakeSitePaging(): SitePaging { export const getFakeSitePaging = (): SitePaging => ({
return { list: {
'list': { pagination: {
'pagination': { count: 2,
'count': 2, hasMoreItems: true,
'hasMoreItems': true, totalItems: 2,
'totalItems': 2, skipCount: 0,
'skipCount': 0, maxItems: 100
'maxItems': 100
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-1', guid: 'fake-1',
'description': 'fake-test-site', description: 'fake-test-site',
'id': 'fake-test-site', id: 'fake-test-site',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-site' title: 'fake-test-site'
} }
}, },
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-2', guid: 'fake-2',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'swsdp', id: 'swsdp',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-2' title: 'fake-test-2'
} }
} }
] ]
} }
}; });
}
export function getFakeSitePagingNoMoreItems(): SitePaging { export const getFakeSitePagingNoMoreItems = (): SitePaging => ({
return { list: {
'list': { pagination: {
'pagination': { count: 2,
'count': 2, hasMoreItems: false,
'hasMoreItems': false, totalItems: 2,
'totalItems': 2, skipCount: 0,
'skipCount': 0, maxItems: 100
'maxItems': 100
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-1', guid: 'fake-1',
'description': 'fake-test-site', description: 'fake-test-site',
'id': 'fake-test-site', id: 'fake-test-site',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-site' title: 'fake-test-site'
} }
}, },
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-2', guid: 'fake-2',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'swsdp', id: 'swsdp',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-2' title: 'fake-test-2'
} }
} }
] ]
} }
}; });
}
export function getFakeSitePagingFirstPage(): SitePaging { export const getFakeSitePagingFirstPage = (): SitePaging => ({
return { list: {
'list': { pagination: {
'pagination': { count: 2,
'count': 2, hasMoreItems: true,
'hasMoreItems': true, totalItems: 2,
'totalItems': 2, skipCount: 0,
'skipCount': 0, maxItems: 4
'maxItems': 4
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-1', guid: 'fake-1',
'description': 'fake-test-site', description: 'fake-test-site',
'id': 'fake-test-site', id: 'fake-test-site',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-site' title: 'fake-test-site'
} }
}, },
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-2', guid: 'fake-2',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'swsdp', id: 'swsdp',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-2' title: 'fake-test-2'
} }
} }
] ]
} }
}; });
}
export function getFakeSitePagingLastPage(): SitePaging { export const getFakeSitePagingLastPage = (): SitePaging => ({
return { list: {
'list': { pagination: {
'pagination': { count: 4,
'count': 4, hasMoreItems: false,
'hasMoreItems': false, totalItems: 2,
'totalItems': 2, skipCount: 2,
'skipCount': 2, maxItems: 4
'maxItems': 4
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-3', guid: 'fake-3',
'description': 'fake-test-3', description: 'fake-test-3',
'id': 'fake-test-3', id: 'fake-test-3',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-3' title: 'fake-test-3'
} }
}, },
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'fake-test-4', guid: 'fake-test-4',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'fake-test-4', id: 'fake-test-4',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'fake-test-4' title: 'fake-test-4'
} }
} }
] ]
} }
}; });
}
export function getFakeSitePagingWithMembers() { export const getFakeSitePagingWithMembers = () => new SitePaging({
return new SitePaging({ list: {
'list': { entries: [{
'entries': [{ entry: {
'entry': { visibility: 'MODERATED',
'visibility': 'MODERATED', guid: 'b4cff62a-664d-4d45-9302-98723eac1319',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319', description: 'This is a Sample Alfresco Team site.',
'description': 'This is a Sample Alfresco Team site.', id: 'MODERATED-SITE',
'id': 'MODERATED-SITE', preset: 'site-dashboard',
'preset': 'site-dashboard', title: 'FAKE-MODERATED-SITE'
'title': 'FAKE-MODERATED-SITE'
}, },
'relations': { relations: {
'members': { members: {
'list': { list: {
'pagination': { pagination: {
'count': 3, count: 3,
'hasMoreItems': false, hasMoreItems: false,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'person': { person: {
'firstName': 'Administrator', firstName: 'Administrator',
'emailNotificationsEnabled': true, emailNotificationsEnabled: true,
'company': {}, company: {},
'id': 'admin', id: 'admin',
'enabled': true, enabled: true,
'email': 'admin@alfresco.com' email: 'admin@alfresco.com'
}, },
'id': 'admin' id: 'admin'
} }
}, },
{ {
'entry': { entry: {
'role': 'SiteCollaborator', role: 'SiteCollaborator',
'person': { person: {
'lastName': 'Beecher', lastName: 'Beecher',
'userStatus': 'Helping to design the look and feel of the new web site', userStatus: 'Helping to design the look and feel of the new web site',
'jobTitle': 'Graphic Designer', jobTitle: 'Graphic Designer',
'statusUpdatedAt': '2011-02-15T20:20:13.432+0000', statusUpdatedAt: '2011-02-15T20:20:13.432+0000',
'mobile': '0112211001100', mobile: '0112211001100',
'emailNotificationsEnabled': true, emailNotificationsEnabled: true,
'description': 'Alice is a demo user for the sample Alfresco Team site.', description: 'Alice is a demo user for the sample Alfresco Team site.',
'telephone': '0112211001100', telephone: '0112211001100',
'enabled': false, enabled: false,
'firstName': 'Alice', firstName: 'Alice',
'skypeId': 'abeecher', skypeId: 'abeecher',
'avatarId': '198500fc-1e99-4f5f-8926-248cea433366', avatarId: '198500fc-1e99-4f5f-8926-248cea433366',
'location': 'Tilbury, UK', location: 'Tilbury, UK',
'company': { company: {
'organization': 'Moresby, Garland and Wedge', organization: 'Moresby, Garland and Wedge',
'address1': '200 Butterwick Street', address1: '200 Butterwick Street',
'address2': 'Tilbury', address2: 'Tilbury',
'address3': 'UK', address3: 'UK',
'postcode': 'ALF1 SAM1' postcode: 'ALF1 SAM1'
}, },
'id': 'abeecher', id: 'abeecher',
'email': 'abeecher@example.com' email: 'abeecher@example.com'
}, },
'id': 'abeecher' id: 'abeecher'
} }
} }
] ]
@@ -241,45 +232,45 @@ export function getFakeSitePagingWithMembers() {
} }
} }
}, { }, {
'entry': { entry: {
'visibility': 'PUBLIC', visibility: 'PUBLIC',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319', guid: 'b4cff62a-664d-4d45-9302-98723eac1319',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'PUBLIC-SITE', id: 'PUBLIC-SITE',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'FAKE-SITE-PUBLIC' title: 'FAKE-SITE-PUBLIC'
} }
}, { }, {
'entry': { entry: {
'visibility': 'PRIVATE', visibility: 'PRIVATE',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319', guid: 'b4cff62a-664d-4d45-9302-98723eac1319',
'description': 'This is a Sample Alfresco Team site.', description: 'This is a Sample Alfresco Team site.',
'id': 'MEMBER-SITE', id: 'MEMBER-SITE',
'preset': 'site-dashboard', preset: 'site-dashboard',
'title': 'FAKE-PRIVATE-SITE-MEMBER' title: 'FAKE-PRIVATE-SITE-MEMBER'
}, },
'relations': { relations: {
'members': { members: {
'list': { list: {
'pagination': { pagination: {
'count': 3, count: 3,
'hasMoreItems': false, hasMoreItems: false,
'skipCount': 0, skipCount: 0,
'maxItems': 100 maxItems: 100
}, },
'entries': [ entries: [
{ {
'entry': { entry: {
'role': 'SiteManager', role: 'SiteManager',
'person': { person: {
'firstName': 'Administrator', firstName: 'Administrator',
'emailNotificationsEnabled': true, emailNotificationsEnabled: true,
'company': {}, company: {},
'id': 'admin', id: 'admin',
'enabled': true, enabled: true,
'email': 'admin@alfresco.com' email: 'admin@alfresco.com'
}, },
'id': 'test' id: 'test'
} }
} }
] ]
@@ -290,4 +281,3 @@ export function getFakeSitePagingWithMembers() {
] ]
} }
}); });
}
@@ -16,42 +16,42 @@
*/ */
export const mockUploadSuccessPromise = { export const mockUploadSuccessPromise = {
on: function (event, callback) { on(event, callback) {
if (event === 'success') { if (event === 'success') {
callback(); callback();
} }
return this; return this;
}, },
catch: function (callback) { catch(callback) {
callback(); callback();
return this; return this;
}, },
then: function (callback) { then(callback) {
callback(); callback();
return this; return this;
}, },
next: function (callback) { next(callback) {
callback(); callback();
return this; return this;
} }
}; };
export const mockUploadErrorPromise = { export const mockUploadErrorPromise = {
on: function (event, callback) { on(event, callback) {
if (event === 'error') { if (event === 'error') {
callback(); callback();
} }
return this; return this;
}, },
catch: function (callback) { catch(callback) {
callback(); callback();
return this; return this;
}, },
then: function (callback) { then(callback) {
callback(); callback();
return this; return this;
}, },
next: function (callback) { next(callback) {
callback(); callback();
return this; return this;
} }
@@ -96,8 +96,8 @@ export class AddPermissionDialogComponent {
} }
onMemberUpdate(role: string, member: MemberModel) { onMemberUpdate(role: string, member: MemberModel) {
const _member = this.selectedMembers.find(({ id }) => id === member.id); const memberInstance = this.selectedMembers.find(({ id }) => id === member.id);
_member.role = role; memberInstance.role = role;
} }
isValid(): boolean { isValid(): boolean {
@@ -55,12 +55,12 @@ describe('AddPermissionPanelComponent', () => {
fixture.destroy(); fixture.destroy();
}); });
function typeWordIntoSearchInput(word: string): void { const typeWordIntoSearchInput = (word: string): void => {
const inputDebugElement = debugElement.query(By.css('#searchInput')); const inputDebugElement = debugElement.query(By.css('#searchInput'));
inputDebugElement.nativeElement.value = word; inputDebugElement.nativeElement.value = word;
inputDebugElement.nativeElement.focus(); inputDebugElement.nativeElement.focus();
inputDebugElement.nativeElement.dispatchEvent(new Event('input')); inputDebugElement.nativeElement.dispatchEvent(new Event('input'));
} };
it('should be able to render the component', () => { it('should be able to render the component', () => {
expect(element.querySelector('#adf-add-permission-type-search')).not.toBeNull(); expect(element.querySelector('#adf-add-permission-type-search')).not.toBeNull();
@@ -52,6 +52,7 @@ export class AddPermissionPanelComponent {
selectedItems: NodeEntry[] = []; selectedItems: NodeEntry[] = [];
// eslint-disable-next-line @typescript-eslint/naming-convention
EVERYONE: NodeEntry = new NodeEntry({ entry: { nodeType: 'cm:authorityContainer', properties: {'cm:authorityName': 'GROUP_EVERYONE'}}}); EVERYONE: NodeEntry = new NodeEntry({ entry: { nodeType: 'cm:authorityContainer', properties: {'cm:authorityName': 'GROUP_EVERYONE'}}});
constructor() { constructor() {
@@ -57,7 +57,7 @@ describe('AddPermissionComponent', () => {
expect(element.querySelector('#adf-add-permission-type-search')).not.toBeNull(); expect(element.querySelector('#adf-add-permission-type-search')).not.toBeNull();
expect(element.querySelector('#searchInput')).not.toBeNull(); expect(element.querySelector('#searchInput')).not.toBeNull();
expect(element.querySelector('#adf-add-permission-actions')).not.toBeNull(); expect(element.querySelector('#adf-add-permission-actions')).not.toBeNull();
const addButton: HTMLButtonElement = <HTMLButtonElement> element.querySelector('#adf-add-permission-action-button'); const addButton = element.querySelector<HTMLButtonElement>('#adf-add-permission-action-button');
expect(addButton.disabled).toBeTruthy(); expect(addButton.disabled).toBeTruthy();
}); });
@@ -81,12 +81,10 @@ export class AddPermissionComponent implements OnInit {
} }
private transformNodeToPermissionElement(nodes: NodeEntry[], role: string): PermissionElement[] { private transformNodeToPermissionElement(nodes: NodeEntry[], role: string): PermissionElement[] {
return nodes.map((node) => { return nodes.map((node) => ({
return { authorityId: node.entry.properties['cm:authorityName'] ?? node.entry.properties['cm:userName'],
'authorityId': node.entry.properties['cm:authorityName'] ?? node.entry.properties['cm:userName'], name: role,
'name': role, accessStatus: 'ALLOWED'
'accessStatus': 'ALLOWED' }));
};
});
} }
} }
@@ -41,7 +41,7 @@ export class SearchPermissionConfigurationService implements SearchConfiguration
include: ['properties', 'aspectNames'], include: ['properties', 'aspectNames'],
paging: { paging: {
maxItems: maxResults, maxItems: maxResults,
skipCount: skipCount skipCount
}, },
filterQueries: [ filterQueries: [
/* eslint-disable-next-line */ /* eslint-disable-next-line */
@@ -70,7 +70,7 @@ describe('InheritPermissionDirective', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const buttonPermission: HTMLButtonElement = <HTMLButtonElement> element.querySelector('#sample-button-permission'); const buttonPermission = element.querySelector<HTMLButtonElement>('#sample-button-permission');
expect(buttonPermission).not.toBeNull(); expect(buttonPermission).not.toBeNull();
expect(element.querySelector('#update-notification')).toBeNull(); expect(element.querySelector('#update-notification')).toBeNull();
buttonPermission.click(); buttonPermission.click();
@@ -95,7 +95,7 @@ describe('InheritPermissionDirective', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const buttonPermission: HTMLButtonElement = <HTMLButtonElement> element.querySelector('#sample-button-permission'); const buttonPermission = element.querySelector<HTMLButtonElement>('#sample-button-permission');
expect(buttonPermission).not.toBeNull(); expect(buttonPermission).not.toBeNull();
expect(element.querySelector('#update-notification')).not.toBeNull(); expect(element.querySelector('#update-notification')).not.toBeNull();
buttonPermission.click(); buttonPermission.click();
@@ -114,7 +114,7 @@ describe('InheritPermissionDirective', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const buttonPermission: HTMLButtonElement = <HTMLButtonElement> element.querySelector('#sample-button-permission'); const buttonPermission = element.querySelector<HTMLButtonElement>('#sample-button-permission');
expect(buttonPermission).not.toBeNull(); expect(buttonPermission).not.toBeNull();
expect(element.querySelector('#update-notification')).not.toBeNull(); expect(element.querySelector('#update-notification')).not.toBeNull();
buttonPermission.click(); buttonPermission.click();
@@ -23,7 +23,7 @@ import { Node } from '@alfresco/js-api';
@Directive({ @Directive({
selector: 'button[adf-inherit-permission], mat-button-toggle[adf-inherit-permission]', selector: 'button[adf-inherit-permission], mat-button-toggle[adf-inherit-permission]',
host: { host: {
'role': 'button', role: 'button',
'(click)': 'onInheritPermissionClicked()' '(click)': 'onInheritPermissionClicked()'
} }
}) })
@@ -110,9 +110,9 @@ describe('PermissionListService', () => {
const event = { source: { checked: false } }; const event = { source: { checked: false } };
const updateNode = JSON.parse(JSON.stringify(fakeNodeInheritedOnly)); const updateNode = JSON.parse(JSON.stringify(fakeNodeInheritedOnly));
node.permissions.locallySet = [{ node.permissions.locallySet = [{
'authorityId': 'GROUP_site_testsite_SiteManager', authorityId: 'GROUP_site_testsite_SiteManager',
'name': 'SiteManager', name: 'SiteManager',
'accessStatus': 'ALLOWED' accessStatus: 'ALLOWED'
}]; }];
updateNode.permissions.isInheritanceEnabled = false; updateNode.permissions.isInheritanceEnabled = false;
spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []})); spyOn(nodePermissionService, 'getNodeWithRoles').and.returnValue(of({node , roles: []}));
@@ -27,6 +27,8 @@ import { NodePermissionsModel } from '../../models/member.model';
import { NodePermissionService } from '../../services/node-permission.service'; import { NodePermissionService } from '../../services/node-permission.service';
import { NodePermissionDialogService } from '../../services/node-permission-dialog.service'; import { NodePermissionDialogService } from '../../services/node-permission-dialog.service';
const SITE_MANAGER_ROLE = 'SiteManager';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
@@ -52,7 +54,6 @@ export class PermissionListService {
private node: Node; private node: Node;
private roles: RoleModel[]; private roles: RoleModel[];
private SITE_MANAGER_ROLE = 'SiteManager';
constructor( constructor(
private nodeService: NodesApiService, private nodeService: NodesApiService,
@@ -89,7 +90,7 @@ export class PermissionListService {
if (authorityId) { if (authorityId) {
const permissions = [ const permissions = [
...(this.node.permissions.locallySet || []), ...(this.node.permissions.locallySet || []),
{ authorityId, name: this.SITE_MANAGER_ROLE, accessStatus: 'ALLOWED' } { authorityId, name: SITE_MANAGER_ROLE, accessStatus: 'ALLOWED' }
]; ];
updateLocalPermission$ = this.nodePermissionService.updatePermissions(this.node, permissions); updateLocalPermission$ = this.nodePermissionService.updatePermissions(this.node, permissions);
} }
@@ -223,8 +224,8 @@ export class PermissionListService {
let hasLocalManagerPermission = false; let hasLocalManagerPermission = false;
let authorityId: string; let authorityId: string;
if (sitePath) { if (sitePath) {
authorityId = `GROUP_site_${sitePath.name}_${this.SITE_MANAGER_ROLE}`; authorityId = `GROUP_site_${sitePath.name}_${SITE_MANAGER_ROLE}`;
hasLocalManagerPermission = !!node.permissions.locallySet?.find((permission) => permission.authorityId === authorityId && permission.name === this.SITE_MANAGER_ROLE); hasLocalManagerPermission = !!node.permissions.locallySet?.find((permission) => permission.authorityId === authorityId && permission.name === SITE_MANAGER_ROLE);
} }
if (!hasLocalManagerPermission && authorityId) { if (!hasLocalManagerPermission && authorityId) {
@@ -245,8 +246,8 @@ export class PermissionListService {
canUpdateThePermission(node: Node, permission: PermissionElement): boolean { canUpdateThePermission(node: Node, permission: PermissionElement): boolean {
const sitePath = node.path.elements.find((path) => path.nodeType === 'st:site'); const sitePath = node.path.elements.find((path) => path.nodeType === 'st:site');
if (!node.permissions.isInheritanceEnabled && sitePath) { if (!node.permissions.isInheritanceEnabled && sitePath) {
const authorityId = `GROUP_site_${sitePath.name}_${this.SITE_MANAGER_ROLE}`; const authorityId = `GROUP_site_${sitePath.name}_${SITE_MANAGER_ROLE}`;
return !(permission.authorityId === authorityId && permission.name === this.SITE_MANAGER_ROLE); return !(permission.authorityId === authorityId && permission.name === SITE_MANAGER_ROLE);
} }
return true; return true;
} }
@@ -61,7 +61,7 @@ describe('NodePermissionDialogService', () => {
let fakePermissionNode = new Node({}); let fakePermissionNode = new Node({});
beforeEach(() => { beforeEach(() => {
fakePermissionNode = <Node> { id: 'fake-permission-node', allowableOperations: ['updatePermissions']}; fakePermissionNode = { id: 'fake-permission-node', allowableOperations: ['updatePermissions']} as Node;
}); });
it('should be able to open the dialog showing node permissions', () => { it('should be able to open the dialog showing node permissions', () => {
@@ -97,7 +97,7 @@ describe('NodePermissionDialogService', () => {
let fakeForbiddenNode = new Node({}); let fakeForbiddenNode = new Node({});
beforeEach(() => { beforeEach(() => {
fakeForbiddenNode = <Node> { id: 'fake-permission-node', allowableOperations: ['update']}; fakeForbiddenNode = { id: 'fake-permission-node', allowableOperations: ['update']} as Node;
}); });
it('should not be able to open the dialog showing node permissions', () => { it('should not be able to open the dialog showing node permissions', () => {
@@ -38,6 +38,7 @@ export class NodePermissionDialogService {
/** /**
* Opens a dialog to add permissions to a node. * Opens a dialog to add permissions to a node.
*
* @param node target node * @param node target node
* @param roles settable roles for the node * @param roles settable roles for the node
* @param title Dialog title * @param title Dialog title
@@ -52,9 +53,9 @@ export class NodePermissionDialogService {
}); });
const data: AddPermissionDialogData = { const data: AddPermissionDialogData = {
node: node, node,
title: title, title,
confirm: confirm, confirm,
roles roles
}; };
@@ -80,6 +81,7 @@ export class NodePermissionDialogService {
/** /**
* Opens a dialog to update permissions for a node. * Opens a dialog to update permissions for a node.
*
* @param nodeId ID of the target node * @param nodeId ID of the target node
* @param title Dialog title * @param title Dialog title
* @returns Node with updated permissions * @returns Node with updated permissions
@@ -87,14 +89,10 @@ export class NodePermissionDialogService {
updateNodePermissionByDialog(nodeId?: string, title?: string): Observable<Node> { updateNodePermissionByDialog(nodeId?: string, title?: string): Observable<Node> {
return this.nodePermissionService.getNodeWithRoles(nodeId) return this.nodePermissionService.getNodeWithRoles(nodeId)
.pipe( .pipe(
switchMap(({node, roles}) => { switchMap(({node, roles}) => this.openAddPermissionDialog(node, roles, title)
return this.openAddPermissionDialog(node, roles, title)
.pipe( .pipe(
switchMap((selection) => { switchMap((selection) => this.nodePermissionService.updateNodePermissions(nodeId, selection))
return this.nodePermissionService.updateNodePermissions(nodeId, selection); ))
})
);
})
); );
} }
} }
@@ -62,12 +62,10 @@ describe('NodePermissionService', () => {
nodeService = TestBed.inject(NodesApiService); nodeService = TestBed.inject(NodesApiService);
}); });
function returnUpdatedNode(nodeBody: Node) { const returnUpdatedNode = (nodeBody: Node) => of(new Node({
return of(new Node({
id: 'fake-updated-node', id: 'fake-updated-node',
permissions: nodeBody.permissions permissions: nodeBody.permissions
})); }));
}
it('should return a list of roles taken from the site groups', (done) => { it('should return a list of roles taken from the site groups', (done) => {
spyOn(searchApiService, 'searchByQueryBody').and.returnValue(of(fakeSiteNodeResponse)); spyOn(searchApiService, 'searchByQueryBody').and.returnValue(of(fakeSiteNodeResponse));
@@ -95,9 +93,9 @@ describe('NodePermissionService', () => {
it('should be able to update a locally set permission role', (done) => { it('should be able to update a locally set permission role', (done) => {
const fakeAccessStatus: any = 'DENIED'; const fakeAccessStatus: any = 'DENIED';
const fakePermission: PermissionElement = { const fakePermission: PermissionElement = {
'authorityId': 'GROUP_EVERYONE', authorityId: 'GROUP_EVERYONE',
'name': 'Contributor', name: 'Contributor',
'accessStatus' : fakeAccessStatus accessStatus : fakeAccessStatus
}; };
spyOn(nodeService, 'updateNode').and.callFake((_, permissionBody) => returnUpdatedNode(permissionBody)); spyOn(nodeService, 'updateNode').and.callFake((_, permissionBody) => returnUpdatedNode(permissionBody));
@@ -114,11 +112,11 @@ describe('NodePermissionService', () => {
}); });
it('should be able to remove a locally set permission', (done) => { it('should be able to remove a locally set permission', (done) => {
const fakePermission = <PermissionElement> { const fakePermission = {
'authorityId': 'FAKE_PERSON_1', authorityId: 'FAKE_PERSON_1',
'name': 'Contributor', name: 'Contributor',
'accessStatus' : 'ALLOWED' accessStatus : 'ALLOWED'
}; } as PermissionElement;
spyOn(nodeService, 'updateNode').and.callFake((_, permissionBody) => returnUpdatedNode(permissionBody)); spyOn(nodeService, 'updateNode').and.callFake((_, permissionBody) => returnUpdatedNode(permissionBody));
const fakeNodeCopy = JSON.parse(JSON.stringify(fakeNodeToRemovePermission)); const fakeNodeCopy = JSON.parse(JSON.stringify(fakeNodeToRemovePermission));
@@ -56,6 +56,7 @@ export class NodePermissionService {
/** /**
* Gets a list of roles for the current node. * Gets a list of roles for the current node.
*
* @param node The target node * @param node The target node
* @returns Array of strings representing the roles * @returns Array of strings representing the roles
*/ */
@@ -95,6 +96,7 @@ export class NodePermissionService {
/** /**
* Updates the permission role for a node. * Updates the permission role for a node.
*
* @param node Target node * @param node Target node
* @param updatedPermissionRole Permission role to update or add * @param updatedPermissionRole Permission role to update or add
* @returns Node with updated permission * @returns Node with updated permission
@@ -113,6 +115,7 @@ export class NodePermissionService {
/** /**
* Update permissions for a node. * Update permissions for a node.
*
* @param nodeId ID of the target node * @param nodeId ID of the target node
* @param permissionList New permission settings * @param permissionList New permission settings
* @returns Node with updated permissions * @returns Node with updated permissions
@@ -125,6 +128,7 @@ export class NodePermissionService {
/** /**
* Updates the locally set permissions for a node. * Updates the locally set permissions for a node.
*
* @param node ID of the target node * @param node ID of the target node
* @param permissions Permission settings * @param permissions Permission settings
* @returns Node with updated permissions * @returns Node with updated permissions
@@ -163,6 +167,7 @@ export class NodePermissionService {
/** /**
* Removes a permission setting from a node. * Removes a permission setting from a node.
*
* @param node ID of the target node * @param node ID of the target node
* @param permissionToRemove Permission setting to remove * @param permissionToRemove Permission setting to remove
* @returns Node with modified permissions * @returns Node with modified permissions
@@ -196,6 +201,7 @@ export class NodePermissionService {
/** /**
* Gets all members related to a group name. * Gets all members related to a group name.
*
* @param groupName Name of group to look for members * @param groupName Name of group to look for members
* @param opts Extra options supported by JS-API * @param opts Extra options supported by JS-API
* @returns List of members * @returns List of members
@@ -213,17 +219,17 @@ export class NodePermissionService {
const builtPathNames = pathNames.join(' OR '); const builtPathNames = pathNames.join(' OR ');
return { return {
'query': { query: {
'query': builtPathNames query: builtPathNames
}, },
'paging': { paging: {
'maxItems': 100, maxItems: 100,
'skipCount': 0 skipCount: 0
}, },
'include': ['aspectNames', 'properties'], include: ['aspectNames', 'properties'],
'filterQueries': [ filterQueries: [
{ {
'query': query:
`TYPE:'st:site'` `TYPE:'st:site'`
} }
] ]
@@ -257,6 +263,7 @@ export class NodePermissionService {
/** /**
* Removes permissions setting from a node. * Removes permissions setting from a node.
*
* @param node target node with permission * @param node target node with permission
* @param permissions Permissions to remove * @param permissions Permissions to remove
* @returns Node with modified permissions * @returns Node with modified permissions
@@ -276,6 +283,7 @@ export class NodePermissionService {
/** /**
* updates permissions setting from a node. * updates permissions setting from a node.
*
* @param node target node with permission * @param node target node with permission
* @param permissions Permissions to update * @param permissions Permissions to update
* @returns Node with modified permissions * @returns Node with modified permissions
@@ -288,13 +296,13 @@ export class NodePermissionService {
/** /**
* Gets all node detail for nodeId along with settable permissions. * Gets all node detail for nodeId along with settable permissions.
*
* @param nodeId Id of the node * @param nodeId Id of the node
* @returns node and it's associated roles { node: Node; roles: RoleModel[] } * @returns node and it's associated roles { node: Node; roles: RoleModel[] }
*/ */
getNodeWithRoles(nodeId: string): Observable<{ node: Node; roles: RoleModel[] }> { getNodeWithRoles(nodeId: string): Observable<{ node: Node; roles: RoleModel[] }> {
return this.nodeService.getNode(nodeId).pipe( return this.nodeService.getNode(nodeId).pipe(
switchMap(node => { switchMap(node => forkJoin({
return forkJoin({
node: of(node), node: of(node),
roles: this.getNodeRoles(node) roles: this.getNodeRoles(node)
.pipe( .pipe(
@@ -302,8 +310,7 @@ export class NodePermissionService {
map(_roles => _roles.map(role => ({ role, label: role })) map(_roles => _roles.map(role => ({ role, label: role }))
) )
) )
}); }))
})
); );
} }
@@ -42,10 +42,10 @@ describe('SearchCheckListComponent', () => {
it('should setup options from settings', () => { it('should setup options from settings', () => {
const options: any = [ const options: any = [
{ 'name': 'Folder', 'value': `TYPE:'cm:folder'` }, { name: 'Folder', value: `TYPE:'cm:folder'` },
{ 'name': 'Document', 'value': `TYPE:'cm:content'` } { name: 'Document', value: `TYPE:'cm:content'` }
]; ];
component.settings = <any> { options: options }; component.settings = { options } as any;
component.ngOnInit(); component.ngOnInit();
expect(component.options.items).toEqual(options); expect(component.options.items).toEqual(options);
@@ -70,13 +70,13 @@ describe('SearchCheckListComponent', () => {
}); });
it('should setup operator from the settings', () => { it('should setup operator from the settings', () => {
component.settings = <any> { operator: 'AND' }; component.settings = { operator: 'AND' } as any;
component.ngOnInit(); component.ngOnInit();
expect(component.operator).toBe('AND'); expect(component.operator).toBe('AND');
}); });
it('should use OR operator by default', () => { it('should use OR operator by default', () => {
component.settings = <any> { operator: null }; component.settings = { operator: null } as any;
component.ngOnInit(); component.ngOnInit();
expect(component.operator).toBe('OR'); expect(component.operator).toBe('OR');
}); });
@@ -88,24 +88,24 @@ describe('SearchCheckListComponent', () => {
]); ]);
component.id = 'checklist'; component.id = 'checklist';
component.context = <any> { component.context = {
queryFragments: {}, queryFragments: {},
update() {} update: () => {}
}; } as any;
component.ngOnInit(); component.ngOnInit();
spyOn(component.context, 'update').and.stub(); spyOn(component.context, 'update').and.stub();
component.changeHandler( component.changeHandler(
<any> { checked: true }, { checked: true } as any,
component.options.items[0] component.options.items[0]
); );
expect(component.context.queryFragments[component.id]).toEqual(`TYPE:'cm:folder'`); expect(component.context.queryFragments[component.id]).toEqual(`TYPE:'cm:folder'`);
component.changeHandler( component.changeHandler(
<any> { checked: true }, { checked: true } as any,
component.options.items[1] component.options.items[1]
); );
@@ -128,12 +128,12 @@ describe('SearchCheckListComponent', () => {
it('should update query builder on reset', () => { it('should update query builder on reset', () => {
component.id = 'checklist'; component.id = 'checklist';
component.context = <any> { component.context = {
queryFragments: { queryFragments: {
'checklist': 'query' checklist: 'query'
}, },
update() {} update: () => {}
}; } as any;
spyOn(component.context, 'update').and.stub(); spyOn(component.context, 'update').and.stub();
component.ngOnInit(); component.ngOnInit();
@@ -151,13 +151,13 @@ describe('SearchCheckListComponent', () => {
describe('Pagination', () => { describe('Pagination', () => {
it('should show 5 items when pageSize not defined', () => { it('should show 5 items when pageSize not defined', () => {
component.id = 'checklist'; component.id = 'checklist';
component.context = <any> { component.context = {
queryFragments: { queryFragments: {
'checklist': 'query' checklist: 'query'
}, },
update() {} update: () => {}
}; } as any;
component.settings = <any> { options: sizeOptions }; component.settings = { options: sizeOptions } as any;
component.ngOnInit(); component.ngOnInit();
fixture.detectChanges(); fixture.detectChanges();
@@ -170,13 +170,13 @@ describe('SearchCheckListComponent', () => {
it('should show all items when pageSize is high', () => { it('should show all items when pageSize is high', () => {
component.id = 'checklist'; component.id = 'checklist';
component.context = <any> { component.context = {
queryFragments: { queryFragments: {
'checklist': 'query' checklist: 'query'
}, },
update() {} update: () => {}
}; } as any;
component.settings = <any> { pageSize: 15, options: sizeOptions }; component.settings = { pageSize: 15, options: sizeOptions } as any;
component.ngOnInit(); component.ngOnInit();
fixture.detectChanges(); fixture.detectChanges();
@@ -189,13 +189,13 @@ describe('SearchCheckListComponent', () => {
it('should able to check/reset the checkbox', () => { it('should able to check/reset the checkbox', () => {
component.id = 'checklist'; component.id = 'checklist';
component.context = <any> { component.context = {
queryFragments: { queryFragments: {
'checklist': 'query' checklist: 'query'
}, },
update: () => {} update: () => {}
}; } as any;
component.settings = <any> { options: sizeOptions }; component.settings = { options: sizeOptions } as any;
spyOn(component, 'submitValues').and.stub(); spyOn(component, 'submitValues').and.stub();
component.ngOnInit(); component.ngOnInit();
fixture.detectChanges(); fixture.detectChanges();
@@ -18,7 +18,7 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { SearchFacetFiltersService, SelectedBucket } from '../../services/search-facet-filters.service'; import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { ContentTestingModule } from '../../../testing/content.testing.module'; import { ContentTestingModule } from '../../../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
@@ -34,8 +34,8 @@ import { TranslateModule } from '@ngx-translate/core';
class TestComponent { class TestComponent {
allowClear = true; allowClear = true;
searchFilter = { searchFilter = {
selectedBuckets: <SelectedBucket[]> [], selectedBuckets: [],
unselectFacetBucket() {} unselectFacetBucket: () => {}
}; };
} }
@@ -92,12 +92,12 @@ describe('SearchControlComponent', () => {
fixture.destroy(); fixture.destroy();
}); });
function typeWordIntoSearchInput(word: string): void { const typeWordIntoSearchInput = (word: string): void => {
const inputDebugElement = debugElement.query(By.css('#adf-control-input')); const inputDebugElement = debugElement.query(By.css('#adf-control-input'));
inputDebugElement.nativeElement.value = word; inputDebugElement.nativeElement.value = word;
inputDebugElement.nativeElement.focus(); inputDebugElement.nativeElement.focus();
inputDebugElement.nativeElement.dispatchEvent(new Event('input')); inputDebugElement.nativeElement.dispatchEvent(new Event('input'));
} };
describe('when input values are inserted', () => { describe('when input values are inserted', () => {
@@ -242,7 +242,7 @@ describe('SearchControlComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
const resultElement: HTMLElement = <HTMLElement> element.querySelector('#result_option_0'); const resultElement = element.querySelector<HTMLElement>('#result_option_0');
resultElement.focus(); resultElement.focus();
expect(resultElement).not.toBe(null); expect(resultElement).not.toBe(null);
inputDebugElement.nativeElement.dispatchEvent(new KeyboardEvent('keypress', { key: 'TAB' })); inputDebugElement.nativeElement.dispatchEvent(new KeyboardEvent('keypress', { key: 'TAB' }));
@@ -264,14 +264,14 @@ describe('SearchControlComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
let resultElement: HTMLElement = <HTMLElement> element.querySelector('#result_option_0'); let resultElement = element.querySelector<HTMLElement>('#result_option_0');
expect(resultElement).not.toBeNull(); expect(resultElement).not.toBeNull();
const escapeEvent: any = new Event('ESCAPE'); const escapeEvent: any = new Event('ESCAPE');
escapeEvent.keyCode = 27; escapeEvent.keyCode = 27;
inputDebugElement.triggerEventHandler('keydown', escapeEvent); inputDebugElement.triggerEventHandler('keydown', escapeEvent);
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
resultElement = <HTMLElement> element.querySelector('#result_option_0'); resultElement = element.querySelector<HTMLElement>('#result_option_0');
expect(resultElement).toBeNull(); expect(resultElement).toBeNull();
done(); done();
}); });
@@ -289,14 +289,14 @@ describe('SearchControlComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
let resultElement: HTMLElement = <HTMLElement> element.querySelector('#result_option_0'); let resultElement = element.querySelector<HTMLElement>('#result_option_0');
expect(resultElement).not.toBeNull(); expect(resultElement).not.toBeNull();
const escapeEvent: any = new Event('ENTER'); const escapeEvent: any = new Event('ENTER');
escapeEvent.keyCode = 13; escapeEvent.keyCode = 13;
inputDebugElement.triggerEventHandler('keydown', escapeEvent); inputDebugElement.triggerEventHandler('keydown', escapeEvent);
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
fixture.detectChanges(); fixture.detectChanges();
resultElement = <HTMLElement> element.querySelector('#result_option_0'); resultElement = element.querySelector<HTMLElement>('#result_option_0');
expect(resultElement).toBeNull(); expect(resultElement).toBeNull();
done(); done();
}); });
@@ -147,7 +147,7 @@ export class SearchControlComponent implements OnDestroy {
} }
onBlur(event: FocusEvent): void { onBlur(event: FocusEvent): void {
const nextElement: any = this.getNextElementSibling(<Element> event.target); const nextElement: any = this.getNextElementSibling(event.target as Element);
if (!nextElement && !this.isListElement(event)) { if (!nextElement && !this.isListElement(event)) {
this.focusSubject.next(event); this.focusSubject.next(event);
} }
@@ -155,20 +155,21 @@ export class SearchControlComponent implements OnDestroy {
onSelectFirstResult() { onSelectFirstResult() {
if ( this.listResultElement && this.listResultElement.length > 0) { if ( this.listResultElement && this.listResultElement.length > 0) {
const firstElement: MatListItem = <MatListItem> this.listResultElement.first; const firstElement = this.listResultElement.first as MatListItem;
// eslint-disable-next-line no-underscore-dangle
firstElement._getHostElement().focus(); firstElement._getHostElement().focus();
} }
} }
onRowArrowDown(event: Event): void { onRowArrowDown(event: Event): void {
const nextElement: any = this.getNextElementSibling(<Element> event.target); const nextElement: any = this.getNextElementSibling(event.target as Element);
if (nextElement) { if (nextElement) {
nextElement.focus(); nextElement.focus();
} }
} }
onRowArrowUp(event: Event): void { onRowArrowUp(event: Event): void {
const previousElement: any = this.getPreviousElementSibling(<Element> event.target); const previousElement: any = this.getPreviousElementSibling(event.target as Element);
if (previousElement) { if (previousElement) {
previousElement.focus(); previousElement.focus();
} else { } else {
@@ -125,8 +125,7 @@ describe('SearchDateRangeComponent', () => {
queryFragments: { queryFragments: {
createdDateRange: 'query' createdDateRange: 'query'
}, },
update() { update: () => {}
}
}; };
component.id = 'createdDateRange'; component.id = 'createdDateRange';
@@ -144,8 +143,7 @@ describe('SearchDateRangeComponent', () => {
it('should update query builder on value changes', () => { it('should update query builder on value changes', () => {
const context: any = { const context: any = {
queryFragments: {}, queryFragments: {},
update() { update: () => {}
}
}; };
component.id = 'createdDateRange'; component.id = 'createdDateRange';
@@ -203,7 +201,7 @@ describe('SearchDateRangeComponent', () => {
}); });
it('should be able to set a fixed maximum date', async () => { it('should be able to set a fixed maximum date', async () => {
component.settings = { field: 'cm:created', dateFormat: dateFormatFixture, maxDate: maxDate }; component.settings = { field: 'cm:created', dateFormat: dateFormatFixture, maxDate };
fixture.detectChanges(); fixture.detectChanges();
const inputs = fixture.debugElement.nativeElement.querySelectorAll('input[ng-reflect-max="Tue Mar 10 2020 23:59:59 GMT+0"]'); const inputs = fixture.debugElement.nativeElement.querySelectorAll('input[ng-reflect-max="Tue Mar 10 2020 23:59:59 GMT+0"]');
@@ -96,7 +96,7 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
ngOnInit() { ngOnInit() {
this.datePickerFormat = this.settings?.dateFormat ? this.settings.dateFormat : DEFAULT_FORMAT_DATE; this.datePickerFormat = this.settings?.dateFormat ? this.settings.dateFormat : DEFAULT_FORMAT_DATE;
const customDateAdapter = <MomentDateAdapter> <any> this.dateAdapter; const customDateAdapter = this.dateAdapter as MomentDateAdapter;
customDateAdapter.overrideDisplayFormat = this.datePickerFormat; customDateAdapter.overrideDisplayFormat = this.datePickerFormat;
this.userPreferencesService this.userPreferencesService
@@ -226,7 +226,7 @@ export class SearchDateRangeComponent implements SearchWidget, OnInit, OnDestroy
formControl.setValue(formatDate); formControl.setValue(formatDate);
} else if (formatDate) { } else if (formatDate) {
formControl.setErrors({ formControl.setErrors({
'invalidOnChange': true invalidOnChange: true
}); });
} }
@@ -117,8 +117,7 @@ describe('SearchDatetimeRangeComponent', () => {
queryFragments: { queryFragments: {
createdDatetimeRange: 'query' createdDatetimeRange: 'query'
}, },
update() { update: () => {}
}
}; };
component.id = 'createdDatetimeRange'; component.id = 'createdDatetimeRange';
@@ -138,8 +137,7 @@ describe('SearchDatetimeRangeComponent', () => {
it('should update the query in UTC format when values change', async () => { it('should update the query in UTC format when values change', async () => {
const context: any = { const context: any = {
queryFragments: {}, queryFragments: {},
update() { update: () => {}
}
}; };
component.id = 'createdDateRange'; component.id = 'createdDateRange';
@@ -165,8 +163,7 @@ describe('SearchDatetimeRangeComponent', () => {
it('should be able to update the query in UTC format from a GMT format', async () => { it('should be able to update the query in UTC format from a GMT format', async () => {
const context: any = { const context: any = {
queryFragments: {}, queryFragments: {},
update() { update: () => {}
}
}; };
const fromInGmt = '2021-02-24T17:00:00+02:00'; const fromInGmt = '2021-02-24T17:00:00+02:00';
const toInGmt = '2021-02-28T15:00:00+02:00'; const toInGmt = '2021-02-28T15:00:00+02:00';
@@ -225,7 +222,7 @@ describe('SearchDatetimeRangeComponent', () => {
}); });
it('should be able to set a fixed maximum datetime', async () => { it('should be able to set a fixed maximum datetime', async () => {
component.settings = { field: 'cm:created', datetimeFormat: datetimeFormatFixture, maxDatetime: maxDatetime }; component.settings = { field: 'cm:created', datetimeFormat: datetimeFormatFixture, maxDatetime };
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
@@ -214,7 +214,7 @@ export class SearchDatetimeRangeComponent implements SearchWidget, OnInit, OnDes
formControl.setValue(formatDate); formControl.setValue(formatDate);
} else if (formatDate) { } else if (formatDate) {
formControl.setErrors({ formControl.setErrors({
'invalidOnChange': true invalidOnChange: true
}); });
} }

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