diff --git a/demo-shell-ng2/app/components/files/files.component.html b/demo-shell-ng2/app/components/files/files.component.html index 1f218c0a18..290b3c41cc 100644 --- a/demo-shell-ng2/app/components/files/files.component.html +++ b/demo-shell-ng2/app/components/files/files.component.html @@ -47,6 +47,14 @@ [adf-nodes]="documentList.selection"> delete + + + + + ... + +``` + +```ts +@Component({ + selector: 'my-component' +}) +export class MyComponent { + + done() { + // ... + } + +} +``` + +### Properties + +| Name | Type | Default | Description | +| ----------------- | ------------------- | ------- | --------------------------- | +| adf-node-favorite | MinimalNodeEntity[] | [] | Nodes to toggle as favorite | + +### Events + +| Name | Description | +| ------------------------- | -------------------------------------------- | +| toggle | emitted when toggle favorite process is done | + +## Details + +The `NodeFavoriteDirective` instance can be bound to a template variable through **adfFavorite** reference, +wich provides a method to help further style the element. + +```html + +``` + +The directive performs as follows: + +- if there are no favorite nodes in the selection, then all are marked as favorites +- if there is at least one favorite node in the selection, then only those who are not + are being marked +- if all nodes in the selection are favorites, then they are removed from favorites + + +See **Demo Shell** diff --git a/ng2-components/ng2-alfresco-core/index.ts b/ng2-components/ng2-alfresco-core/index.ts index 610c6e4f28..e20c675848 100644 --- a/ng2-components/ng2-alfresco-core/index.ts +++ b/ng2-components/ng2-alfresco-core/index.ts @@ -56,6 +56,7 @@ import { UserPreferencesService } from './src/services/user-preferences.service' import { HighlightDirective } from './src/directives/highlight.directive'; import { LogoutDirective } from './src/directives/logout.directive'; +import { NodeFavoriteDirective } from './src/directives/node-favorite.directive'; import { DeletedNodesApiService } from './src/services/deleted-nodes-api.service'; import { DiscoveryApiService } from './src/services/discovery-api.service'; import { FavoritesApiService } from './src/services/favorites-api.service'; @@ -141,6 +142,7 @@ export * from './src/components/info-drawer/info-drawer.component'; export * from './src/directives/upload.directive'; export * from './src/directives/highlight.directive'; export * from './src/directives/node-permission.directive'; +export * from './src/directives/node-favorite.directive'; export * from './src/utils/index'; export * from './src/events/base.event'; export * from './src/events/base-ui.event'; @@ -247,6 +249,7 @@ export function createTranslateLoader(http: Http, logService: LogService) { LogoutDirective, UploadDirective, NodePermissionDirective, + NodeFavoriteDirective, HighlightDirective, DataColumnComponent, DataColumnListComponent, @@ -289,6 +292,7 @@ export function createTranslateLoader(http: Http, logService: LogService) { LogoutDirective, UploadDirective, NodePermissionDirective, + NodeFavoriteDirective, HighlightDirective, DataColumnComponent, DataColumnListComponent, diff --git a/ng2-components/ng2-alfresco-core/src/directives/node-favorite.directive.spec.ts b/ng2-components/ng2-alfresco-core/src/directives/node-favorite.directive.spec.ts new file mode 100644 index 0000000000..b645c6137b --- /dev/null +++ b/ng2-components/ng2-alfresco-core/src/directives/node-favorite.directive.spec.ts @@ -0,0 +1,360 @@ +/*! + * @license + * Copyright 2016 Alfresco Software, Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Component, DebugElement } from '@angular/core'; +import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { CoreModule } from '../../index'; +import { AlfrescoApiService } from '../services/alfresco-api.service'; +import { NodeFavoriteDirective } from './node-favorite.directive'; + +@Component({ + template: ` +
+
` +}) +class TestComponent { + selection; + + done = jasmine.createSpy('done'); +} + +describe('NodeFavoriteDirective', () => { + let component: TestComponent; + let fixture: ComponentFixture; + let element: DebugElement; + let directiveInstance; + let apiService; + let favoritesApi; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + CoreModule + ], + declarations: [ + TestComponent + ] + }) + .compileComponents() + .then(() => { + fixture = TestBed.createComponent(TestComponent); + component = fixture.componentInstance; + element = fixture.debugElement.query(By.directive(NodeFavoriteDirective)); + directiveInstance = element.injector.get(NodeFavoriteDirective); + + apiService = TestBed.get(AlfrescoApiService); + favoritesApi = apiService.getInstance().core.favoritesApi; + }); + })); + + describe('selection input change event', () => { + it('should not call markFavoritesNodes() if input list is empty', () => { + spyOn(directiveInstance, 'markFavoritesNodes'); + + component.selection = []; + + fixture.detectChanges(); + + expect(directiveInstance.markFavoritesNodes).not.toHaveBeenCalledWith(); + }); + + it('should call markFavoritesNodes() on input change', () => { + spyOn(directiveInstance, 'markFavoritesNodes'); + + component.selection = [{ entry: { id: '1', name: 'name1' } }]; + + fixture.detectChanges(); + + expect(directiveInstance.markFavoritesNodes).toHaveBeenCalledWith(component.selection); + + component.selection = [ + { entry: { id: '1', name: 'name1' } }, + { entry: { id: '1', name: 'name1' } } + ]; + + fixture.detectChanges(); + + expect(directiveInstance.markFavoritesNodes).toHaveBeenCalledWith(component.selection); + }); + }); + + describe('markFavoritesNodes()', () => { + let favoritesApiSpy; + + beforeEach(() => { + favoritesApiSpy = spyOn(favoritesApi, 'getFavorite'); + }); + + it('should check each selected node if it is a favorite', fakeAsync(() => { + favoritesApiSpy.and.returnValue(Promise.resolve()); + + component.selection = [ + { entry: { id: '1', name: 'name1' } }, + { entry: { id: '2', name: 'name2' } } + ]; + + fixture.detectChanges(); + tick(); + + expect(favoritesApiSpy.calls.count()).toBe(2); + })); + + it('should not check processed node when another is unselected', fakeAsync(() => { + favoritesApiSpy.and.returnValue(Promise.resolve()); + + component.selection = [ + { entry: { id: '1', name: 'name1' } }, + { entry: { id: '2', name: 'name2' } } + ]; + + fixture.detectChanges(); + tick(); + + expect(directiveInstance.favorites.length).toBe(2); + expect(favoritesApiSpy.calls.count()).toBe(2); + + favoritesApiSpy.calls.reset(); + + component.selection = [ + { entry: { id: '2', name: 'name2' } } + ]; + + fixture.detectChanges(); + tick(); + + expect(directiveInstance.favorites.length).toBe(1); + expect(favoritesApiSpy).not.toHaveBeenCalled(); + })); + + it('should not check processed nodes when another is selected', fakeAsync(() => { + favoritesApiSpy.and.returnValue(Promise.resolve()); + + component.selection = [ + { entry: { id: '1', name: 'name1' } }, + { entry: { id: '2', name: 'name2' } } + ]; + + fixture.detectChanges(); + tick(); + + expect(directiveInstance.favorites.length).toBe(2); + expect(favoritesApiSpy.calls.count()).toBe(2); + + favoritesApiSpy.calls.reset(); + + component.selection = [ + { entry: { id: '1', name: 'name1' } }, + { entry: { id: '2', name: 'name2' } }, + { entry: { id: '3', name: 'name3' } } + ]; + + fixture.detectChanges(); + tick(); + + expect(directiveInstance.favorites.length).toBe(3); + expect(favoritesApiSpy.calls.count()).toBe(1); + })); + }); + + describe('toggleFavorite()', () => { + let removeFavoriteSpy; + let addFavoriteSpy; + + beforeEach(() => { + removeFavoriteSpy = spyOn(favoritesApi, 'removeFavoriteSite'); + addFavoriteSpy = spyOn(favoritesApi, 'addFavorite'); + }); + + afterEach(() => { + removeFavoriteSpy.calls.reset(); + addFavoriteSpy.calls.reset(); + }); + + it('should not perform action if favorites collection is empty', () => { + component.selection = []; + + fixture.detectChanges(); + element.triggerEventHandler('click', null); + + expect(removeFavoriteSpy).not.toHaveBeenCalled(); + expect(addFavoriteSpy).not.toHaveBeenCalled(); + }); + + it('should call addFavorite() if none is a favorite', fakeAsync(() => { + addFavoriteSpy.and.returnValue(Promise.resolve()); + + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: false } }, + { entry: { id: '2', name: 'name2', isFavorite: false } } + ]; + + element.triggerEventHandler('click', null); + tick(); + + expect(addFavoriteSpy.calls.argsFor(0)[1].length).toBe(2); + })); + + it('should call addFavorite() on node that is not a favorite in selection', fakeAsync(() => { + addFavoriteSpy.and.returnValue(Promise.resolve()); + + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFile: true, isFolder: false, isFavorite: false } }, + { entry: { id: '2', name: 'name2', isFile: true, isFolder: false, isFavorite: true } } + ]; + + element.triggerEventHandler('click', null); + tick(); + + const callArgs = addFavoriteSpy.calls.argsFor(0)[1]; + const callParameter = callArgs[0]; + + expect(callArgs.length).toBe(1); + expect(callParameter.target.file.guid).toBe('1'); + })); + + it('should call removeFavoriteSite() if all are favorites', fakeAsync(() => { + removeFavoriteSpy.and.returnValue(Promise.resolve()); + + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: true } }, + { entry: { id: '2', name: 'name2', isFavorite: true } } + ]; + + element.triggerEventHandler('click', null); + tick(); + + expect(removeFavoriteSpy.calls.count()).toBe(2); + })); + + it('should emit event when removeFavoriteSite() is done', fakeAsync(() => { + removeFavoriteSpy.and.returnValue(Promise.resolve()); + + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: true } } + ]; + + element.triggerEventHandler('click', null); + tick(); + + expect(component.done).toHaveBeenCalled(); + })); + + it('should emit event when addFavorite() is done', fakeAsync(() => { + addFavoriteSpy.and.returnValue(Promise.resolve()); + + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: false } } + ]; + + element.triggerEventHandler('click', null); + tick(); + + expect(component.done).toHaveBeenCalled(); + })); + }); + + describe('getFavorite()', () => { + it('should process node as favorite', fakeAsync(() => { + spyOn(favoritesApi, 'getFavorite').and.returnValue(Promise.resolve()); + + component.selection = [ + { entry: { id: '1', name: 'name1' } } + ]; + + fixture.detectChanges(); + tick(); + + expect(directiveInstance.favorites[0].entry.isFavorite).toBe(true); + })); + + it('should not process node as favorite', fakeAsync(() => { + spyOn(favoritesApi, 'getFavorite').and.returnValue(Promise.reject(null)); + + component.selection = [ + { entry: { id: '1', name: 'name1' } } + ]; + + fixture.detectChanges(); + tick(); + + expect(directiveInstance.favorites[0].entry.isFavorite).toBe(false); + })); + }); + + describe('reset()', () => { + beforeEach(() => { + spyOn(favoritesApi, 'removeFavoriteSite').and.returnValue(Promise.resolve()); + spyOn(favoritesApi, 'addFavorite').and.returnValue(Promise.resolve()); + }); + + it('should reset favorite collection after removeFavoriteSite()', fakeAsync(() => { + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: true } } + ]; + + element.triggerEventHandler('click', null); + tick(); + + expect(directiveInstance.favorites.length).toBe(0); + })); + + it('should reset favorite collection after addFavorite()', fakeAsync(() => { + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: false } } + ]; + + element.triggerEventHandler('click', null); + tick(); + + expect(directiveInstance.favorites.length).toBe(0); + })); + }); + + describe('hasFavorites()', () => { + it('should return false when favorites collection is empty', () => { + directiveInstance.favorites = []; + + const hasFavorites = directiveInstance.hasFavorites(); + + expect(hasFavorites).toBe(false); + }); + + it('should return false when some are not favorite', () => { + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: true } }, + { entry: { id: '2', name: 'name2', isFavorite: false } } + ]; + + const hasFavorites = directiveInstance.hasFavorites(); + + expect(hasFavorites).toBe(false); + }); + + it('return true when all are favorite', () => { + directiveInstance.favorites = [ + { entry: { id: '1', name: 'name1', isFavorite: true } }, + { entry: { id: '2', name: 'name2', isFavorite: true } } + ]; + + const hasFavorites = directiveInstance.hasFavorites(); + + expect(hasFavorites).toBe(true); + }); + }); +}); diff --git a/ng2-components/ng2-alfresco-core/src/directives/node-favorite.directive.ts b/ng2-components/ng2-alfresco-core/src/directives/node-favorite.directive.ts new file mode 100644 index 0000000000..a652cd0c84 --- /dev/null +++ b/ng2-components/ng2-alfresco-core/src/directives/node-favorite.directive.ts @@ -0,0 +1,176 @@ +/*! + * @license + * Copyright 2016 Alfresco Software, Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Directive, EventEmitter, HostListener, Input, OnChanges, Output } from '@angular/core'; +import { FavoriteBody, MinimalNodeEntity } from 'alfresco-js-api'; +import { Observable } from 'rxjs/Rx'; +import { AlfrescoApiService } from '../services/alfresco-api.service'; + +@Directive({ + selector: '[adf-node-favorite]', + exportAs: 'adfFavorite' +}) +export class NodeFavoriteDirective implements OnChanges { + private favorites: any[] = []; + + @Input('adf-node-favorite') + selection: MinimalNodeEntity[] = []; + + @Output() toggle: EventEmitter = new EventEmitter(); + + @HostListener('click') + onClick() { + this.toggleFavorite(); + } + + constructor(private alfrescoApiService: AlfrescoApiService) {} + + ngOnChanges(changes) { + if (!changes.selection.currentValue.length) { + return; + } + + this.markFavoritesNodes(changes.selection.currentValue); + } + + toggleFavorite() { + if (!this.favorites.length) { + return; + } + + const every = this.favorites.every((selected) => selected.entry.isFavorite); + + if (every) { + const batch = this.favorites.map((selected) => { + // shared files have nodeId + const id = selected.entry.nodeId || selected.entry.id; + + return Observable.fromPromise(this.alfrescoApiService.getInstance().core.favoritesApi.removeFavoriteSite('-me-', id)); + }); + + Observable.forkJoin(batch).subscribe(() => { + this.reset(); + this.toggle.emit(); + }); + } + + if (!every) { + const notFavorite = this.favorites.filter((node) => !node.entry.isFavorite); + const body: FavoriteBody[] = notFavorite.map((node) => this.createFavoriteBody(node)); + + Observable.fromPromise(this.alfrescoApiService.getInstance().core.favoritesApi.addFavorite('-me-', body)) + .subscribe(() => { + this.reset(); + this.toggle.emit(); + }); + } + } + + markFavoritesNodes(selection: MinimalNodeEntity[]) { + if (selection.length < this.favorites.length) { + const newFavorites = this.reduce(this.favorites, selection); + this.favorites = newFavorites; + } + + const result = this.diff(selection, this.favorites); + const batch = this.getProcessBatch(result); + + Observable.forkJoin(batch).subscribe((data) => this.favorites.push(...data)); + } + + hasFavorites(): boolean { + if (this.favorites && !this.favorites.length) { + return false; + } + + return this.favorites.every((selected) => selected.entry.isFavorite); + } + + private reset() { + this.favorites = []; + } + + private getProcessBatch(selection): any[] { + return selection.map((selected: MinimalNodeEntity) => this.getFavorite(selected)); + } + + private getFavorite(selected: MinimalNodeEntity): Observable { + const { name, isFile, isFolder } = selected.entry; + // shared files have nodeId + const id = ( selected).entry.nodeId || selected.entry.id; + + const promise = this.alfrescoApiService.getInstance() + .core.favoritesApi.getFavorite('-me-', id); + + return Observable.from(promise) + .map(() => ({ + entry: { + id, + isFolder, + isFile, + name, + isFavorite: true + } + })) + .catch(() => { + return Observable.of({ + entry: { + id, + isFolder, + isFile, + name, + isFavorite: false + } + }); + }); + } + + private createFavoriteBody(node): FavoriteBody { + const type = this.getNodeType(node); + // shared files have nodeId + const id = node.entry.nodeId || node.entry.id; + + return { + target: { + [type]: { + guid: id + } + } + }; + } + + private getNodeType(node): string { + // shared could only be files + if (!node.entry.isFile && !node.entry.isFolder) { + return 'file'; + } + + return node.entry.isFile ? 'file' : 'folder'; + } + + private diff(list, patch): any[] { + const ids = patch.map(item => item.entry.id); + + return list.filter(item => ids.includes(item.entry.id) ? null : item); + } + + private reduce(patch, comparator): any[] { + const ids = comparator.map(item => item.entry.id); + + return patch.filter(item => ids.includes(item.entry.id) ? item : null); + } +}