This commit is contained in:
Ying Jin
2022-10-03 20:49:24 -05:00
205 changed files with 13029 additions and 2829 deletions

View File

@@ -135,6 +135,9 @@ languages:
- code: lv
label: Latviešu
active: true
- code: hi
label: Hindi
active: true
- code: hu
label: Magyar
active: true

View File

@@ -104,6 +104,8 @@
"jwt-decode": "^3.1.2",
"klaro": "^0.7.10",
"lodash": "^4.17.21",
"markdown-it": "^13.0.1",
"markdown-it-mathjax3": "^4.3.1",
"mirador": "^3.3.0",
"mirador-dl-plugin": "^0.13.0",
"mirador-share-plugin": "^0.11.0",
@@ -116,6 +118,7 @@
"ngx-moment": "^5.0.0",
"ngx-pagination": "5.0.0",
"ngx-sortablejs": "^11.1.0",
"ngx-ui-switch": "^11.0.1",
"nouislider": "^14.6.3",
"pem": "1.14.4",
"postcss-cli": "^9.1.0",
@@ -123,13 +126,13 @@
"react-copy-to-clipboard": "^5.0.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.5.5",
"sanitize-html": "^2.7.2",
"sortablejs": "1.13.0",
"tslib": "^2.0.0",
"url-parse": "^1.5.6",
"uuid": "^8.3.2",
"webfontloader": "1.6.28",
"zone.js": "~0.11.5",
"ngx-ui-switch": "^11.0.1"
"zone.js": "~0.11.5"
},
"devDependencies": {
"@angular-builders/custom-webpack": "~13.1.0",
@@ -155,6 +158,7 @@
"@types/js-cookie": "2.2.6",
"@types/lodash": "^4.14.165",
"@types/node": "^14.14.9",
"@types/sanitize-html": "^2.6.2",
"@typescript-eslint/eslint-plugin": "5.11.0",
"@typescript-eslint/parser": "5.11.0",
"axe-core": "^4.3.3",

View File

@@ -76,6 +76,10 @@ export function app() {
*/
const server = express();
// Tell Express to trust X-FORWARDED-* headers from proxies
// See https://expressjs.com/en/guide/behind-proxies.html
server.set('trust proxy', environment.ui.useProxies);
/*
* If production mode is enabled in the environment file:
* - Enable Angular's production mode

View File

@@ -238,7 +238,6 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
this.epersonService.deleteEPerson(ePerson).pipe(getFirstCompletedRemoteData()).subscribe((restResponse: RemoteData<NoContent>) => {
if (restResponse.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', {name: ePerson.name}));
this.reset();
} else {
this.notificationsService.error('Error occured when trying to delete EPerson with id: ' + ePerson.id + ' with code: ' + restResponse.statusCode + ' and message: ' + restResponse.errorMessage);
}

View File

@@ -5,11 +5,12 @@ import { TranslateService } from '@ngx-translate/core';
import {
BehaviorSubject,
combineLatest as observableCombineLatest,
EMPTY,
Observable,
of as observableOf,
Subscription
} from 'rxjs';
import { catchError, map, switchMap, tap } from 'rxjs/operators';
import { catchError, defaultIfEmpty, map, switchMap, tap } from 'rxjs/operators';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
@@ -144,7 +145,7 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
}
return this.authorizationService.isAuthorized(FeatureID.AdministratorOf).pipe(
switchMap((isSiteAdmin: boolean) => {
return observableCombineLatest(groups.page.map((group: Group) => {
return observableCombineLatest([...groups.page.map((group: Group) => {
if (hasValue(group) && !this.deletedGroupsIds.includes(group.id)) {
return observableCombineLatest([
this.authorizationService.isAuthorized(FeatureID.CanDelete, group.self),
@@ -165,8 +166,10 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
}
)
);
} else {
return EMPTY;
}
})).pipe(map((dtos: GroupDtoModel[]) => {
})]).pipe(defaultIfEmpty([]), map((dtos: GroupDtoModel[]) => {
return buildPaginatedList(groups.pageInfo, dtos);
}));
})

View File

@@ -0,0 +1,35 @@
<div class="container">
<h2 id="header">{{'admin.batch-import.page.header' | translate}}</h2>
<p>{{'admin.batch-import.page.help' | translate}}</p>
<p *ngIf="dso">
selected collection: <b>{{getDspaceObjectName()}}</b>&nbsp;
<a href="javascript:void(0)" (click)="removeDspaceObject()">{{'admin.batch-import.page.remove' | translate}}</a>
</p>
<p>
<button class="btn btn-primary" (click)="this.selectCollection();">{{'admin.metadata-import.page.button.select-collection' | translate}}</button>
</p>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="validateOnly" [(ngModel)]="validateOnly">
<label class="form-check-label" for="validateOnly">
{{'admin.metadata-import.page.validateOnly' | translate}}
</label>
</div>
<small id="validateOnlyHelpBlock" class="form-text text-muted">
{{'admin.batch-import.page.validateOnly.hint' | translate}}
</small>
</div>
<ds-file-dropzone-no-uploader
(onFileAdded)="setFile($event)"
[dropMessageLabel]="'admin.batch-import.page.dropMsg'"
[dropMessageLabelReplacement]="'admin.batch-import.page.dropMsgReplace'">
</ds-file-dropzone-no-uploader>
<div class="space-children-mr">
<button class="btn btn-secondary" id="backButton"
(click)="this.onReturn();">{{'admin.metadata-import.page.button.return' | translate}}</button>
<button class="btn btn-primary" id="proceedButton"
(click)="this.importMetadata();">{{'admin.metadata-import.page.button.proceed' | translate}}</button>
</div>
</div>

View File

@@ -0,0 +1,151 @@
import { ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/core/testing';
import { BatchImportPageComponent } from './batch-import-page.component';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { FormsModule } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { RouterTestingModule } from '@angular/router/testing';
import { FileValueAccessorDirective } from '../../shared/utils/file-value-accessor.directive';
import { FileValidator } from '../../shared/utils/require-file.validator';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import {
BATCH_IMPORT_SCRIPT_NAME,
ScriptDataService
} from '../../core/data/processes/script-data.service';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';
import { ProcessParameter } from '../../process-page/processes/process-parameter.model';
describe('BatchImportPageComponent', () => {
let component: BatchImportPageComponent;
let fixture: ComponentFixture<BatchImportPageComponent>;
let notificationService: NotificationsServiceStub;
let scriptService: any;
let router;
let locationStub;
function init() {
notificationService = new NotificationsServiceStub();
scriptService = jasmine.createSpyObj('scriptService',
{
invoke: createSuccessfulRemoteDataObject$({ processId: '46' })
}
);
router = jasmine.createSpyObj('router', {
navigateByUrl: jasmine.createSpy('navigateByUrl')
});
locationStub = jasmine.createSpyObj('location', {
back: jasmine.createSpy('back')
});
}
beforeEach(waitForAsync(() => {
init();
TestBed.configureTestingModule({
imports: [
FormsModule,
TranslateModule.forRoot(),
RouterTestingModule.withRoutes([])
],
declarations: [BatchImportPageComponent, FileValueAccessorDirective, FileValidator],
providers: [
{ provide: NotificationsService, useValue: notificationService },
{ provide: ScriptDataService, useValue: scriptService },
{ provide: Router, useValue: router },
{ provide: Location, useValue: locationStub },
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BatchImportPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('if back button is pressed', () => {
beforeEach(fakeAsync(() => {
const proceed = fixture.debugElement.query(By.css('#backButton')).nativeElement;
proceed.click();
fixture.detectChanges();
}));
it('should do location.back', () => {
expect(locationStub.back).toHaveBeenCalled();
});
});
describe('if file is set', () => {
let fileMock: File;
beforeEach(() => {
fileMock = new File([''], 'filename.zip', { type: 'application/zip' });
component.setFile(fileMock);
});
describe('if proceed button is pressed without validate only', () => {
beforeEach(fakeAsync(() => {
component.validateOnly = false;
const proceed = fixture.debugElement.query(By.css('#proceedButton')).nativeElement;
proceed.click();
fixture.detectChanges();
}));
it('metadata-import script is invoked with --zip fileName and the mockFile', () => {
const parameterValues: ProcessParameter[] = [
Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' }),
];
parameterValues.push(Object.assign(new ProcessParameter(), { name: '--add' }));
expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [fileMock]);
});
it('success notification is shown', () => {
expect(notificationService.success).toHaveBeenCalled();
});
it('redirected to process page', () => {
expect(router.navigateByUrl).toHaveBeenCalledWith('/processes/46');
});
});
describe('if proceed button is pressed with validate only', () => {
beforeEach(fakeAsync(() => {
component.validateOnly = true;
const proceed = fixture.debugElement.query(By.css('#proceedButton')).nativeElement;
proceed.click();
fixture.detectChanges();
}));
it('metadata-import script is invoked with --zip fileName and the mockFile and -v validate-only', () => {
const parameterValues: ProcessParameter[] = [
Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' }),
Object.assign(new ProcessParameter(), { name: '--add' }),
Object.assign(new ProcessParameter(), { name: '-v', value: true }),
];
expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [fileMock]);
});
it('success notification is shown', () => {
expect(notificationService.success).toHaveBeenCalled();
});
it('redirected to process page', () => {
expect(router.navigateByUrl).toHaveBeenCalledWith('/processes/46');
});
});
describe('if proceed is pressed; but script invoke fails', () => {
beforeEach(fakeAsync(() => {
jasmine.getEnv().allowRespy(true);
spyOn(scriptService, 'invoke').and.returnValue(createFailedRemoteDataObject$('Error', 500));
const proceed = fixture.debugElement.query(By.css('#proceedButton')).nativeElement;
proceed.click();
fixture.detectChanges();
}));
it('error notification is shown', () => {
expect(notificationService.error).toHaveBeenCalled();
});
});
});
});

View File

@@ -0,0 +1,124 @@
import { Component } from '@angular/core';
import { Location } from '@angular/common';
import { TranslateService } from '@ngx-translate/core';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { BATCH_IMPORT_SCRIPT_NAME, ScriptDataService } from '../../core/data/processes/script-data.service';
import { Router } from '@angular/router';
import { ProcessParameter } from '../../process-page/processes/process-parameter.model';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { RemoteData } from '../../core/data/remote-data';
import { Process } from '../../process-page/processes/process.model';
import { isNotEmpty } from '../../shared/empty.util';
import { getProcessDetailRoute } from '../../process-page/process-page-routing.paths';
import {
ImportBatchSelectorComponent
} from '../../shared/dso-selector/modal-wrappers/import-batch-selector/import-batch-selector.component';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { take } from 'rxjs/operators';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
@Component({
selector: 'ds-batch-import-page',
templateUrl: './batch-import-page.component.html'
})
export class BatchImportPageComponent {
/**
* The current value of the file
*/
fileObject: File;
/**
* The validate only flag
*/
validateOnly = true;
/**
* dso object for community or collection
*/
dso: DSpaceObject = null;
public constructor(private location: Location,
protected translate: TranslateService,
protected notificationsService: NotificationsService,
private scriptDataService: ScriptDataService,
private router: Router,
private modalService: NgbModal,
private dsoNameService: DSONameService) {
}
/**
* Set file
* @param file
*/
setFile(file) {
this.fileObject = file;
}
/**
* When return button is pressed go to previous location
*/
public onReturn() {
this.location.back();
}
public selectCollection() {
const modalRef = this.modalService.open(ImportBatchSelectorComponent);
modalRef.componentInstance.response.pipe(take(1)).subscribe((dso) => {
this.dso = dso || null;
});
}
/**
* Starts import-metadata script with --zip fileName (and the selected file)
*/
public importMetadata() {
if (this.fileObject == null) {
this.notificationsService.error(this.translate.get('admin.metadata-import.page.error.addFile'));
} else {
const parameterValues: ProcessParameter[] = [
Object.assign(new ProcessParameter(), { name: '--zip', value: this.fileObject.name }),
Object.assign(new ProcessParameter(), { name: '--add' })
];
if (this.dso) {
parameterValues.push(Object.assign(new ProcessParameter(), { name: '--collection', value: this.dso.uuid }));
}
if (this.validateOnly) {
parameterValues.push(Object.assign(new ProcessParameter(), { name: '-v', value: true }));
}
this.scriptDataService.invoke(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [this.fileObject]).pipe(
getFirstCompletedRemoteData(),
).subscribe((rd: RemoteData<Process>) => {
if (rd.hasSucceeded) {
const title = this.translate.get('process.new.notification.success.title');
const content = this.translate.get('process.new.notification.success.content');
this.notificationsService.success(title, content);
if (isNotEmpty(rd.payload)) {
this.router.navigateByUrl(getProcessDetailRoute(rd.payload.processId));
}
} else {
const title = this.translate.get('process.new.notification.error.title');
const content = this.translate.get('process.new.notification.error.content');
this.notificationsService.error(title, content);
}
});
}
}
/**
* return selected dspace object name
*/
getDspaceObjectName(): string {
if (this.dso) {
return this.dsoNameService.getName(this.dso);
}
return null;
}
/**
* remove selected dso object
*/
removeDspaceObject(): void {
this.dso = null;
}
}

View File

@@ -7,6 +7,7 @@ import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow
import { I18nBreadcrumbsService } from '../core/breadcrumbs/i18n-breadcrumbs.service';
import { AdminCurationTasksComponent } from './admin-curation-tasks/admin-curation-tasks.component';
import { REGISTRIES_MODULE_PATH } from './admin-routing-paths';
import { BatchImportPageComponent } from './admin-import-batch-page/batch-import-page.component';
@NgModule({
imports: [
@@ -40,6 +41,12 @@ import { REGISTRIES_MODULE_PATH } from './admin-routing-paths';
component: MetadataImportPageComponent,
data: { title: 'admin.metadata-import.title', breadcrumbKey: 'admin.metadata-import' }
},
{
path: 'batch-import',
resolve: { breadcrumb: I18nBreadcrumbResolver },
component: BatchImportPageComponent,
data: { title: 'admin.batch-import.title', breadcrumbKey: 'admin.batch-import' }
},
])
],
providers: [

View File

@@ -9,6 +9,7 @@ import { AdminWorkflowModuleModule } from './admin-workflow-page/admin-workflow.
import { AdminSearchModule } from './admin-search-page/admin-search.module';
import { AdminSidebarSectionComponent } from './admin-sidebar/admin-sidebar-section/admin-sidebar-section.component';
import { ExpandableAdminSidebarSectionComponent } from './admin-sidebar/expandable-admin-sidebar-section/expandable-admin-sidebar-section.component';
import { BatchImportPageComponent } from './admin-import-batch-page/batch-import-page.component';
const ENTRY_COMPONENTS = [
// put only entry components that use custom decorator
@@ -28,7 +29,8 @@ const ENTRY_COMPONENTS = [
],
declarations: [
AdminCurationTasksComponent,
MetadataImportPageComponent
MetadataImportPageComponent,
BatchImportPageComponent
]
})
export class AdminModule {

View File

@@ -1,10 +1,9 @@
import { Store, StoreModule } from '@ngrx/store';
import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule, DOCUMENT } from '@angular/common';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
// Load the implementations that should be tested
import { AppComponent } from './app.component';
@@ -73,7 +72,6 @@ describe('App component', () => {
providers: [
{ provide: NativeWindowService, useValue: new NativeWindowRef() },
{ provide: MetadataService, useValue: new MetadataServiceMock() },
{ provide: Angulartics2GoogleAnalytics, useValue: new AngularticsProviderMock() },
{ provide: Angulartics2DSpace, useValue: new AngularticsProviderMock() },
{ provide: AuthService, useValue: new AuthServiceMock() },
{ provide: Router, useValue: new RouterMock() },

View File

@@ -11,7 +11,6 @@ import { ActivatedRoute, Params, Router } from '@angular/router';
import { BrowseService } from '../../core/browse/browse.service';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { StartsWithType } from '../../shared/starts-with/starts-with-decorator';
import { BrowseByDataType, rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { PaginationService } from '../../core/pagination/pagination.service';
import { map } from 'rxjs/operators';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
@@ -29,7 +28,6 @@ import { AppConfig, APP_CONFIG } from '../../../config/app-config.interface';
* A metadata definition (a.k.a. browse id) is a short term used to describe one or multiple metadata fields.
* An example would be 'dateissued' for 'dc.date.issued'
*/
@rendersBrowseBy(BrowseByDataType.Date)
export class BrowseByDatePageComponent extends BrowseByMetadataPageComponent {
/**

View File

@@ -0,0 +1,29 @@
import {Component} from '@angular/core';
import { ThemedComponent } from '../../shared/theme-support/themed.component';
import { BrowseByDatePageComponent } from './browse-by-date-page.component';
import {BrowseByDataType, rendersBrowseBy} from '../browse-by-switcher/browse-by-decorator';
/**
* Themed wrapper for BrowseByDatePageComponent
* */
@Component({
selector: 'ds-themed-browse-by-metadata-page',
styleUrls: [],
templateUrl: '../../shared/theme-support/themed.component.html',
})
@rendersBrowseBy(BrowseByDataType.Date)
export class ThemedBrowseByDatePageComponent
extends ThemedComponent<BrowseByDatePageComponent> {
protected getComponentName(): string {
return 'BrowseByDatePageComponent';
}
protected importThemedComponent(themeName: string): Promise<any> {
return import(`../../../themes/${themeName}/app/browse-by/browse-by-date-page/browse-by-date-page.component`);
}
protected importUnthemedComponent(): Promise<any> {
return import(`./browse-by-date-page.component`);
}
}

View File

@@ -6,10 +6,10 @@
<ds-comcol-page-header [name]="parentContext.name">
</ds-comcol-page-header>
<!-- Handle -->
<ds-comcol-page-handle
<ds-themed-comcol-page-handle
[content]="parentContext.handle"
[title]="parentContext.type+'.page.handle'" >
</ds-comcol-page-handle>
</ds-themed-comcol-page-handle>
<!-- Introductory text -->
<ds-comcol-page-content [content]="parentContext.introductoryText" [hasInnerHtml]="true">
</ds-comcol-page-content>

View File

@@ -1,5 +1,5 @@
import { combineLatest as observableCombineLatest, Observable, Subscription } from 'rxjs';
import { Component, Inject, OnInit } from '@angular/core';
import { Component, Inject, OnInit, OnDestroy } from '@angular/core';
import { RemoteData } from '../../core/data/remote-data';
import { PaginatedList } from '../../core/data/paginated-list.model';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
@@ -14,7 +14,6 @@ import { getFirstSucceededRemoteData } from '../../core/shared/operators';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { StartsWithType } from '../../shared/starts-with/starts-with-decorator';
import { BrowseByDataType, rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { PaginationService } from '../../core/pagination/pagination.service';
import { map } from 'rxjs/operators';
import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface';
@@ -32,8 +31,7 @@ export const BBM_PAGINATION_ID = 'bbm';
* or multiple metadata fields. An example would be 'author' for
* 'dc.contributor.*'
*/
@rendersBrowseBy(BrowseByDataType.Metadata)
export class BrowseByMetadataPageComponent implements OnInit {
export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
/**
* The list of browse-entries to display
@@ -93,7 +91,7 @@ export class BrowseByMetadataPageComponent implements OnInit {
startsWithOptions;
/**
* The value we're browing items for
* The value we're browsing items for
* - When the value is not empty, we're browsing items
* - When the value is empty, we're browsing browse-entries (values for the given metadata definition)
*/

View File

@@ -0,0 +1,29 @@
import {Component} from '@angular/core';
import { ThemedComponent } from '../../shared/theme-support/themed.component';
import { BrowseByMetadataPageComponent } from './browse-by-metadata-page.component';
import {BrowseByDataType, rendersBrowseBy} from '../browse-by-switcher/browse-by-decorator';
/**
* Themed wrapper for BrowseByMetadataPageComponent
**/
@Component({
selector: 'ds-themed-browse-by-metadata-page',
styleUrls: [],
templateUrl: '../../shared/theme-support/themed.component.html',
})
@rendersBrowseBy(BrowseByDataType.Metadata)
export class ThemedBrowseByMetadataPageComponent
extends ThemedComponent<BrowseByMetadataPageComponent> {
protected getComponentName(): string {
return 'BrowseByMetadataPageComponent';
}
protected importThemedComponent(themeName: string): Promise<any> {
return import(`../../../themes/${themeName}/app/browse-by/browse-by-metadata-page/browse-by-metadata-page.component`);
}
protected importUnthemedComponent(): Promise<any> {
return import(`./browse-by-metadata-page.component`);
}
}

View File

@@ -9,7 +9,6 @@ import {
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { BrowseService } from '../../core/browse/browse.service';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { BrowseByDataType, rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { PaginationService } from '../../core/pagination/pagination.service';
import { map } from 'rxjs/operators';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
@@ -23,7 +22,6 @@ import { AppConfig, APP_CONFIG } from '../../../config/app-config.interface';
/**
* Component for browsing items by title (dc.title)
*/
@rendersBrowseBy(BrowseByDataType.Title)
export class BrowseByTitlePageComponent extends BrowseByMetadataPageComponent {
public constructor(protected route: ActivatedRoute,

View File

@@ -0,0 +1,29 @@
import {Component} from '@angular/core';
import { ThemedComponent } from '../../shared/theme-support/themed.component';
import { BrowseByTitlePageComponent } from './browse-by-title-page.component';
import {BrowseByDataType, rendersBrowseBy} from '../browse-by-switcher/browse-by-decorator';
/**
* Themed wrapper for BrowseByTitlePageComponent
*/
@Component({
selector: 'ds-themed-browse-by-title-page',
styleUrls: [],
templateUrl: '../../shared/theme-support/themed.component.html',
})
@rendersBrowseBy(BrowseByDataType.Title)
export class ThemedBrowseByTitlePageComponent
extends ThemedComponent<BrowseByTitlePageComponent> {
protected getComponentName(): string {
return 'BrowseByTitlePageComponent';
}
protected importThemedComponent(themeName: string): Promise<any> {
return import(`../../../themes/${themeName}/app/browse-by/browse-by-title-page/browse-by-title-page.component`);
}
protected importUnthemedComponent(): Promise<any> {
return import(`./browse-by-title-page.component`);
}
}

View File

@@ -7,12 +7,20 @@ import { BrowseByDatePageComponent } from './browse-by-date-page/browse-by-date-
import { BrowseBySwitcherComponent } from './browse-by-switcher/browse-by-switcher.component';
import { ThemedBrowseBySwitcherComponent } from './browse-by-switcher/themed-browse-by-switcher.component';
import { ComcolModule } from '../shared/comcol/comcol.module';
import { ThemedBrowseByMetadataPageComponent } from './browse-by-metadata-page/themed-browse-by-metadata-page.component';
import { ThemedBrowseByDatePageComponent } from './browse-by-date-page/themed-browse-by-date-page.component';
import { ThemedBrowseByTitlePageComponent } from './browse-by-title-page/themed-browse-by-title-page.component';
const ENTRY_COMPONENTS = [
// put only entry components that use custom decorator
BrowseByTitlePageComponent,
BrowseByMetadataPageComponent,
BrowseByDatePageComponent
BrowseByDatePageComponent,
ThemedBrowseByMetadataPageComponent,
ThemedBrowseByDatePageComponent,
ThemedBrowseByTitlePageComponent,
];
@NgModule({

View File

@@ -17,10 +17,10 @@
</ds-comcol-page-logo>
<!-- Handle -->
<ds-comcol-page-handle
<ds-themed-comcol-page-handle
[content]="collection.handle"
[title]="'collection.page.handle'" >
</ds-comcol-page-handle>
</ds-themed-comcol-page-handle>
<!-- Introductory text -->
<ds-comcol-page-content
[content]="collection.introductoryText"

View File

@@ -10,8 +10,8 @@
<ds-comcol-page-logo *ngIf="logoRD$" [logo]="(logoRD$ | async)?.payload" [alternateText]="'Community Logo'">
</ds-comcol-page-logo>
<!-- Handle -->
<ds-comcol-page-handle [content]="communityPayload.handle" [title]="'community.page.handle'">
</ds-comcol-page-handle>
<ds-themed-comcol-page-handle [content]="communityPayload.handle" [title]="'community.page.handle'">
</ds-themed-comcol-page-handle>
<!-- Introductory text -->
<ds-comcol-page-content [content]="communityPayload.introductoryText" [hasInnerHtml]="true">
</ds-comcol-page-content>

View File

@@ -1,5 +1,5 @@
<ds-comcol-role
*ngFor="let comcolRole of getComcolRoles$() | async"
*ngFor="let comcolRole of comcolRoles$ | async"
[dso]="community$ | async"
[comcolRole]="comcolRole"
>

View File

@@ -78,8 +78,9 @@ describe('CommunityRolesComponent', () => {
fixture.detectChanges();
});
it('should display a community admin role component', () => {
it('should display a community admin role component', (done) => {
expect(de.query(By.css('ds-comcol-role .community-admin')))
.toBeTruthy();
done();
});
});

View File

@@ -19,28 +19,14 @@ export class CommunityRolesComponent implements OnInit {
dsoRD$: Observable<RemoteData<Community>>;
/**
* The community to manage, as an observable.
* The different roles for the community, as an observable.
*/
get community$(): Observable<Community> {
return this.dsoRD$.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
);
}
comcolRoles$: Observable<HALLink[]>;
/**
* The different roles for the community.
* The community to manage, as an observable.
*/
getComcolRoles$(): Observable<HALLink[]> {
return this.community$.pipe(
map((community) => [
{
name: 'community-admin',
href: community._links.adminGroup.href,
},
]),
);
}
community$: Observable<Community>;
constructor(
protected route: ActivatedRoute,
@@ -52,5 +38,22 @@ export class CommunityRolesComponent implements OnInit {
first(),
map((data) => data.dso),
);
this.community$ = this.dsoRD$.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
);
/**
* The different roles for the community.
*/
this.comcolRoles$ = this.community$.pipe(
map((community) => [
{
name: 'community-admin',
href: community._links.adminGroup.href,
},
]),
);
}
}

View File

@@ -180,17 +180,20 @@ describe('CommunityPageSubCollectionList Component', () => {
comp.community = mockCommunity;
});
it('should display a list of collections', () => {
subCollList = collections;
fixture.detectChanges();
const collList = fixture.debugElement.queryAll(By.css('li'));
expect(collList.length).toEqual(5);
expect(collList[0].nativeElement.textContent).toContain('Collection 1');
expect(collList[1].nativeElement.textContent).toContain('Collection 2');
expect(collList[2].nativeElement.textContent).toContain('Collection 3');
expect(collList[3].nativeElement.textContent).toContain('Collection 4');
expect(collList[4].nativeElement.textContent).toContain('Collection 5');
it('should display a list of collections', () => {
waitForAsync(() => {
subCollList = collections;
fixture.detectChanges();
const collList = fixture.debugElement.queryAll(By.css('li'));
expect(collList.length).toEqual(5);
expect(collList[0].nativeElement.textContent).toContain('Collection 1');
expect(collList[1].nativeElement.textContent).toContain('Collection 2');
expect(collList[2].nativeElement.textContent).toContain('Collection 3');
expect(collList[3].nativeElement.textContent).toContain('Collection 4');
expect(collList[4].nativeElement.textContent).toContain('Collection 5');
});
});
it('should not display the header when list of collections is empty', () => {

View File

@@ -181,17 +181,20 @@ describe('CommunityPageSubCommunityListComponent Component', () => {
});
it('should display a list of sub-communities', () => {
subCommList = subcommunities;
fixture.detectChanges();
const subComList = fixture.debugElement.queryAll(By.css('li'));
expect(subComList.length).toEqual(5);
expect(subComList[0].nativeElement.textContent).toContain('SubCommunity 1');
expect(subComList[1].nativeElement.textContent).toContain('SubCommunity 2');
expect(subComList[2].nativeElement.textContent).toContain('SubCommunity 3');
expect(subComList[3].nativeElement.textContent).toContain('SubCommunity 4');
expect(subComList[4].nativeElement.textContent).toContain('SubCommunity 5');
it('should display a list of sub-communities', () => {
waitForAsync(() => {
subCommList = subcommunities;
fixture.detectChanges();
const subComList = fixture.debugElement.queryAll(By.css('li'));
expect(subComList.length).toEqual(5);
expect(subComList[0].nativeElement.textContent).toContain('SubCommunity 1');
expect(subComList[1].nativeElement.textContent).toContain('SubCommunity 2');
expect(subComList[2].nativeElement.textContent).toContain('SubCommunity 3');
expect(subComList[3].nativeElement.textContent).toContain('SubCommunity 4');
expect(subComList[4].nativeElement.textContent).toContain('SubCommunity 5');
});
});
it('should not display the header when list of sub-communities is empty', () => {

View File

@@ -13,7 +13,9 @@ export const ObjectCacheActionTypes = {
REMOVE: type('dspace/core/cache/object/REMOVE'),
RESET_TIMESTAMPS: type('dspace/core/cache/object/RESET_TIMESTAMPS'),
ADD_PATCH: type('dspace/core/cache/object/ADD_PATCH'),
APPLY_PATCH: type('dspace/core/cache/object/APPLY_PATCH')
APPLY_PATCH: type('dspace/core/cache/object/APPLY_PATCH'),
ADD_DEPENDENTS: type('dspace/core/cache/object/ADD_DEPENDENTS'),
REMOVE_DEPENDENTS: type('dspace/core/cache/object/REMOVE_DEPENDENTS')
};
/**
@@ -126,13 +128,55 @@ export class ApplyPatchObjectCacheAction implements Action {
}
}
/**
* An NgRx action to add dependent request UUIDs to a cached object
*/
export class AddDependentsObjectCacheAction implements Action {
type = ObjectCacheActionTypes.ADD_DEPENDENTS;
payload: {
href: string;
dependentRequestUUIDs: string[];
};
/**
* Create a new AddDependentsObjectCacheAction
*
* @param href the self link of a cached object
* @param dependentRequestUUIDs the UUID of the request that depends on this object
*/
constructor(href: string, dependentRequestUUIDs: string[]) {
this.payload = {
href,
dependentRequestUUIDs,
};
}
}
/**
* An NgRx action to remove all dependent request UUIDs from a cached object
*/
export class RemoveDependentsObjectCacheAction implements Action {
type = ObjectCacheActionTypes.REMOVE_DEPENDENTS;
payload: string;
/**
* Create a new RemoveDependentsObjectCacheAction
*
* @param href the self link of a cached object for which to remove all dependent request UUIDs
*/
constructor(href: string) {
this.payload = href;
}
}
/**
* A type to encompass all ObjectCacheActions
*/
export type ObjectCacheAction
= AddToObjectCacheAction
| RemoveFromObjectCacheAction
| ResetObjectCacheTimestampsAction
| AddPatchObjectCacheAction
| ApplyPatchObjectCacheAction;
| RemoveFromObjectCacheAction
| ResetObjectCacheTimestampsAction
| AddPatchObjectCacheAction
| ApplyPatchObjectCacheAction
| AddDependentsObjectCacheAction
| RemoveDependentsObjectCacheAction;

View File

@@ -2,11 +2,13 @@ import * as deepFreeze from 'deep-freeze';
import { Operation } from 'fast-json-patch';
import { Item } from '../shared/item.model';
import {
AddDependentsObjectCacheAction,
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
RemoveDependentsObjectCacheAction,
RemoveFromObjectCacheAction,
ResetObjectCacheTimestampsAction
ResetObjectCacheTimestampsAction,
} from './object-cache.actions';
import { objectCacheReducer } from './object-cache.reducer';
@@ -42,20 +44,22 @@ describe('objectCacheReducer', () => {
timeCompleted: new Date().getTime(),
msToLive: 900000,
requestUUIDs: [requestUUID1],
dependentRequestUUIDs: [],
patches: [],
isDirty: false,
},
[selfLink2]: {
data: {
type: Item.type,
self: requestUUID2,
self: selfLink2,
foo: 'baz',
_links: { self: { href: requestUUID2 } }
_links: { self: { href: selfLink2 } }
},
alternativeLinks: [altLink3, altLink4],
timeCompleted: new Date().getTime(),
msToLive: 900000,
requestUUIDs: [selfLink2],
requestUUIDs: [requestUUID2],
dependentRequestUUIDs: [requestUUID1],
patches: [],
isDirty: false
}
@@ -189,4 +193,20 @@ describe('objectCacheReducer', () => {
expect((newState[selfLink1].data as any).name).toEqual(newName);
});
it('should add dependent requests on ADD_DEPENDENTS', () => {
let newState = objectCacheReducer(testState, new AddDependentsObjectCacheAction(selfLink1, ['new', 'newer', 'newest']));
expect(newState[selfLink1].dependentRequestUUIDs).toEqual(['new', 'newer', 'newest']);
newState = objectCacheReducer(newState, new AddDependentsObjectCacheAction(selfLink2, ['more']));
expect(newState[selfLink2].dependentRequestUUIDs).toEqual([requestUUID1, 'more']);
});
it('should clear dependent requests on REMOVE_DEPENDENTS', () => {
let newState = objectCacheReducer(testState, new RemoveDependentsObjectCacheAction(selfLink1));
expect(newState[selfLink1].dependentRequestUUIDs).toEqual([]);
newState = objectCacheReducer(newState, new RemoveDependentsObjectCacheAction(selfLink2));
expect(newState[selfLink2].dependentRequestUUIDs).toEqual([]);
});
});

View File

@@ -1,12 +1,13 @@
/* eslint-disable max-classes-per-file */
import {
AddDependentsObjectCacheAction,
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
ObjectCacheAction,
ObjectCacheActionTypes,
ObjectCacheActionTypes, RemoveDependentsObjectCacheAction,
RemoveFromObjectCacheAction,
ResetObjectCacheTimestampsAction
ResetObjectCacheTimestampsAction,
} from './object-cache.actions';
import { hasValue, isNotEmpty } from '../../shared/empty.util';
import { CacheEntry } from './cache-entry';
@@ -69,6 +70,12 @@ export class ObjectCacheEntry implements CacheEntry {
*/
requestUUIDs: string[];
/**
* A list of UUIDs for the requests that depend on this object.
* When this object is invalidated, these requests will be invalidated as well.
*/
dependentRequestUUIDs: string[];
/**
* An array of patches that were made on the client side to this entry, but haven't been sent to the server yet
*/
@@ -134,6 +141,14 @@ export function objectCacheReducer(state = initialState, action: ObjectCacheActi
return applyPatchObjectCache(state, action as ApplyPatchObjectCacheAction);
}
case ObjectCacheActionTypes.ADD_DEPENDENTS: {
return addDependentsObjectCacheState(state, action as AddDependentsObjectCacheAction);
}
case ObjectCacheActionTypes.REMOVE_DEPENDENTS: {
return removeDependentsObjectCacheState(state, action as RemoveDependentsObjectCacheAction);
}
default: {
return state;
}
@@ -159,6 +174,7 @@ function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheActio
timeCompleted: action.payload.timeCompleted,
msToLive: action.payload.msToLive,
requestUUIDs: [action.payload.requestUUID, ...(existing.requestUUIDs || [])],
dependentRequestUUIDs: existing.dependentRequestUUIDs || [],
isDirty: isNotEmpty(existing.patches),
patches: existing.patches || [],
alternativeLinks: [...(existing.alternativeLinks || []), ...newAltLinks]
@@ -252,3 +268,49 @@ function applyPatchObjectCache(state: ObjectCacheState, action: ApplyPatchObject
}
return newState;
}
/**
* Add a list of dependent request UUIDs to a cached object, used when defining new dependencies
*
* @param state the current state
* @param action an AddDependentsObjectCacheAction
* @return the new state, with the dependent requests of the cached object updated
*/
function addDependentsObjectCacheState(state: ObjectCacheState, action: AddDependentsObjectCacheAction): ObjectCacheState {
const href = action.payload.href;
const newState = Object.assign({}, state);
if (hasValue(newState[href])) {
newState[href] = Object.assign({}, newState[href], {
dependentRequestUUIDs: [
...new Set([
...newState[href]?.dependentRequestUUIDs || [],
...action.payload.dependentRequestUUIDs,
])
]
});
}
return newState;
}
/**
* Remove all dependent request UUIDs from a cached object, used to clear out-of-date depedencies
*
* @param state the current state
* @param action an AddDependentsObjectCacheAction
* @return the new state, with the dependent requests of the cached object updated
*/
function removeDependentsObjectCacheState(state: ObjectCacheState, action: RemoveDependentsObjectCacheAction): ObjectCacheState {
const href = action.payload;
const newState = Object.assign({}, state);
if (hasValue(newState[href])) {
newState[href] = Object.assign({}, newState[href], {
dependentRequestUUIDs: []
});
}
return newState;
}

View File

@@ -11,10 +11,12 @@ import { coreReducers} from '../core.reducers';
import { RestRequestMethod } from '../data/rest-request-method';
import { Item } from '../shared/item.model';
import {
AddDependentsObjectCacheAction,
RemoveDependentsObjectCacheAction,
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
RemoveFromObjectCacheAction
RemoveFromObjectCacheAction,
} from './object-cache.actions';
import { Patch } from './object-cache.reducer';
import { ObjectCacheService } from './object-cache.service';
@@ -25,6 +27,7 @@ import { storeModuleConfig } from '../../app.reducer';
import { TestColdObservable } from 'jasmine-marbles/src/test-observables';
import { IndexName } from '../index/index-name.model';
import { CoreState } from '../core-state.model';
import { TestScheduler } from 'rxjs/testing';
describe('ObjectCacheService', () => {
let service: ObjectCacheService;
@@ -38,6 +41,7 @@ describe('ObjectCacheService', () => {
let altLink1;
let altLink2;
let requestUUID;
let requestUUID2;
let alternativeLink;
let timestamp;
let timestamp2;
@@ -55,6 +59,7 @@ describe('ObjectCacheService', () => {
altLink1 = 'https://alternative.link/endpoint/1234';
altLink2 = 'https://alternative.link/endpoint/5678';
requestUUID = '4d3a4ce8-a375-4b98-859b-39f0a014d736';
requestUUID2 = 'c0f486c1-c4d3-4a03-b293-ca5b71ff0054';
alternativeLink = 'https://rest.api/endpoint/5e4f8a5-be98-4c51-9fd8-6bfedcbd59b7/item';
timestamp = new Date().getTime();
timestamp2 = new Date().getTime() - 200;
@@ -71,13 +76,17 @@ describe('ObjectCacheService', () => {
data: objectToCache,
timeCompleted: timestamp,
msToLive: msToLive,
alternativeLinks: [altLink1, altLink2]
alternativeLinks: [altLink1, altLink2],
requestUUIDs: [requestUUID],
dependentRequestUUIDs: [],
};
cacheEntry2 = {
data: objectToCache,
timeCompleted: timestamp2,
msToLive: msToLive2,
alternativeLinks: [altLink2]
alternativeLinks: [altLink2],
requestUUIDs: [requestUUID2],
dependentRequestUUIDs: [],
};
invalidCacheEntry = Object.assign({}, cacheEntry, { msToLive: -1 });
operations = [{ op: 'replace', path: '/name', value: 'random string' } as Operation];
@@ -343,4 +352,122 @@ describe('ObjectCacheService', () => {
expect(store.dispatch).toHaveBeenCalledWith(new ApplyPatchObjectCacheAction(selfLink));
});
});
describe('request dependencies', () => {
beforeEach(() => {
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'cache/object': {
['objectWithoutDependents']: {
dependentRequestUUIDs: [],
},
['objectWithDependents']: {
dependentRequestUUIDs: [requestUUID],
},
[selfLink]: cacheEntry,
},
'index': {
'object/alt-link-to-self-link': {
[anotherLink]: selfLink,
['objectWithoutDependentsAlt']: 'objectWithoutDependents',
['objectWithDependentsAlt']: 'objectWithDependents',
}
}
})
});
mockStore.setState(state);
});
describe('addDependency', () => {
it('should dispatch an ADD_DEPENDENTS action', () => {
service.addDependency(selfLink, 'objectWithoutDependents');
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
it('should resolve alt links', () => {
service.addDependency(anotherLink, 'objectWithoutDependentsAlt');
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
it('should not dispatch if either href cannot be resolved to a cached self link', () => {
service.addDependency(selfLink, 'unknown');
service.addDependency('unknown', 'objectWithoutDependents');
service.addDependency('nothing', 'matches');
expect(store.dispatch).not.toHaveBeenCalled();
});
it('should not dispatch if either href is undefined', () => {
service.addDependency(selfLink, undefined);
service.addDependency(undefined, 'objectWithoutDependents');
service.addDependency(undefined, undefined);
expect(store.dispatch).not.toHaveBeenCalled();
});
it('should not dispatch if the dependency exists already', () => {
service.addDependency(selfLink, 'objectWithDependents');
expect(store.dispatch).not.toHaveBeenCalled();
});
it('should work with observable hrefs', () => {
service.addDependency(observableOf(selfLink), observableOf('objectWithoutDependents'));
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
it('should only dispatch once for the first value of either observable href', () => {
const testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
testScheduler.run(({ cold: tsCold, flush }) => {
const href$ = tsCold('--y-n-n', {
y: selfLink,
n: 'NOPE'
});
const dependsOnHref$ = tsCold('-y-n-n', {
y: 'objectWithoutDependents',
n: 'NOPE'
});
service.addDependency(href$, dependsOnHref$);
flush();
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
});
it('should not dispatch if either of the hrefs emits undefined', () => {
const testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
testScheduler.run(({ cold: tsCold, flush }) => {
const undefined$ = tsCold('--u');
service.addDependency(selfLink, undefined$);
service.addDependency(undefined$, 'objectWithoutDependents');
service.addDependency(undefined$, undefined$);
flush();
expect(store.dispatch).not.toHaveBeenCalled();
});
});
});
describe('removeDependents', () => {
it('should dispatch a REMOVE_DEPENDENTS action', () => {
service.removeDependents('objectWithDependents');
expect(store.dispatch).toHaveBeenCalledOnceWith(new RemoveDependentsObjectCacheAction('objectWithDependents'));
});
it('should resolve alt links', () => {
service.removeDependents('objectWithDependentsAlt');
expect(store.dispatch).toHaveBeenCalledOnceWith(new RemoveDependentsObjectCacheAction('objectWithDependents'));
});
it('should not dispatch if the href cannot be resolved to a cached self link', () => {
service.removeDependents('unknown');
expect(store.dispatch).not.toHaveBeenCalled();
});
});
});
});

View File

@@ -4,23 +4,15 @@ import { applyPatch, Operation } from 'fast-json-patch';
import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs';
import { distinctUntilChanged, filter, map, mergeMap, switchMap, take } from 'rxjs/operators';
import { hasValue, isNotEmpty, isEmpty } from '../../shared/empty.util';
import { hasNoValue, hasValue, isEmpty, isNotEmpty } from '../../shared/empty.util';
import { CoreState } from '../core-state.model';
import { coreSelector } from '../core.selectors';
import { RestRequestMethod } from '../data/rest-request-method';
import {
selfLinkFromAlternativeLinkSelector,
selfLinkFromUuidSelector
} from '../index/index.selectors';
import { selfLinkFromAlternativeLinkSelector, selfLinkFromUuidSelector } from '../index/index.selectors';
import { GenericConstructor } from '../shared/generic-constructor';
import { getClassForType } from './builders/build-decorators';
import { LinkService } from './builders/link.service';
import {
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
RemoveFromObjectCacheAction
} from './object-cache.actions';
import { AddDependentsObjectCacheAction, AddPatchObjectCacheAction, AddToObjectCacheAction, ApplyPatchObjectCacheAction, RemoveDependentsObjectCacheAction, RemoveFromObjectCacheAction } from './object-cache.actions';
import { ObjectCacheEntry, ObjectCacheState } from './object-cache.reducer';
import { AddToSSBAction } from './server-sync-buffer.actions';
@@ -339,4 +331,97 @@ export class ObjectCacheService {
this.store.dispatch(new ApplyPatchObjectCacheAction(selfLink));
}
/**
* Add a new dependency between two cached objects.
* When {@link dependsOnHref$} is invalidated, {@link href$} will be invalidated as well.
*
* This method should be called _after_ requests have been sent;
* it will only work if both objects are already present in the cache.
*
* If either object is undefined, the dependency will not be added
*
* @param href$ the href of an object to add a dependency to
* @param dependsOnHref$ the href of the new dependency
*/
addDependency(href$: string | Observable<string>, dependsOnHref$: string | Observable<string>) {
if (hasNoValue(href$) || hasNoValue(dependsOnHref$)) {
return;
}
if (typeof href$ === 'string') {
href$ = observableOf(href$);
}
if (typeof dependsOnHref$ === 'string') {
dependsOnHref$ = observableOf(dependsOnHref$);
}
observableCombineLatest([
href$,
dependsOnHref$.pipe(
switchMap(dependsOnHref => this.resolveSelfLink(dependsOnHref))
),
]).pipe(
switchMap(([href, dependsOnSelfLink]: [string, string]) => {
const dependsOnSelfLink$ = observableOf(dependsOnSelfLink);
return observableCombineLatest([
dependsOnSelfLink$,
dependsOnSelfLink$.pipe(
switchMap(selfLink => this.getBySelfLink(selfLink)),
map(oce => oce?.dependentRequestUUIDs || []),
),
this.getByHref(href).pipe(
// only add the latest request to keep dependency index from growing indefinitely
map((entry: ObjectCacheEntry) => entry?.requestUUIDs?.[0]),
)
]);
}),
take(1),
).subscribe(([dependsOnSelfLink, currentDependents, newDependent]: [string, string[], string]) => {
// don't dispatch if either href is invalid or if the new dependency already exists
if (hasValue(dependsOnSelfLink) && hasValue(newDependent) && !currentDependents.includes(newDependent)) {
this.store.dispatch(new AddDependentsObjectCacheAction(dependsOnSelfLink, [newDependent]));
}
});
}
/**
* Clear all dependent requests associated with a cache entry.
*
* @href the href of a cached object
*/
removeDependents(href: string) {
this.resolveSelfLink(href).pipe(
take(1),
).subscribe((selfLink: string) => {
if (hasValue(selfLink)) {
this.store.dispatch(new RemoveDependentsObjectCacheAction(selfLink));
}
});
}
/**
* Resolve the self link of an existing cached object from an arbitrary href
*
* @param href any href
* @return an observable of the self link corresponding to the given href.
* Will emit the given href if it was a self link, another href
* if the given href was an alt link, or undefined if there is no
* cached object for this href.
*/
private resolveSelfLink(href: string): Observable<string> {
return this.getBySelfLink(href).pipe(
switchMap((oce: ObjectCacheEntry) => {
if (isNotEmpty(oce)) {
return [href];
} else {
return this.store.pipe(
select(selfLinkFromAlternativeLinkSelector(href)),
);
}
}),
);
}
}

View File

@@ -10,7 +10,7 @@ import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.s
import { HALEndpointService } from '../../shared/hal-endpoint.service';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { FindListOptions } from '../find-list-options.model';
import { Observable, of as observableOf } from 'rxjs';
import { Observable, of as observableOf, combineLatest as observableCombineLatest } from 'rxjs';
import { getMockRequestService } from '../../../shared/mocks/request.service.mock';
import { HALEndpointServiceStub } from '../../../shared/testing/hal-endpoint-service.stub';
import { getMockRemoteDataBuildService } from '../../../shared/mocks/remote-data-build.service.mock';
@@ -20,6 +20,7 @@ import { RemoteData } from '../remote-data';
import { RequestEntryState } from '../request-entry-state.model';
import { fakeAsync, tick } from '@angular/core/testing';
import { BaseDataService } from './base-data.service';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
const endpoint = 'https://rest.api/core';
@@ -65,7 +66,13 @@ describe('BaseDataService', () => {
},
getByHref: () => {
/* empty */
}
},
addDependency: () => {
/* empty */
},
removeDependents: () => {
/* empty */
},
} as any;
selfLink = 'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7';
linksToFollow = [
@@ -558,7 +565,8 @@ describe('BaseDataService', () => {
beforeEach(() => {
getByHrefSpy = spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2', 'request3']
requestUUIDs: ['request1', 'request2', 'request3'],
dependentRequestUUIDs: ['request4', 'request5']
}));
});
@@ -570,6 +578,8 @@ describe('BaseDataService', () => {
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request1');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request2');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request3');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request4');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request5');
done();
});
});
@@ -582,6 +592,8 @@ describe('BaseDataService', () => {
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request1');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request2');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request3');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request4');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request5');
}));
it('should return an Observable that only emits true once all requests are stale', () => {
@@ -591,9 +603,13 @@ describe('BaseDataService', () => {
case 'request1':
return cold('--(t|)', BOOLEAN);
case 'request2':
return cold('----(t|)', BOOLEAN);
case 'request3':
return cold('------(t|)', BOOLEAN);
case 'request3':
return cold('---(t|)', BOOLEAN);
case 'request4':
return cold('-(t|)', BOOLEAN);
case 'request5':
return cold('----(t|)', BOOLEAN);
}
});
@@ -607,9 +623,9 @@ describe('BaseDataService', () => {
it('should only fire for the current state of the object (instead of tracking it)', () => {
testScheduler.run(({ cold, flush }) => {
getByHrefSpy.and.returnValue(cold('a---b---c---', {
a: { requestUUIDs: ['request1'] }, // this is the state at the moment we're invalidating the cache
b: { requestUUIDs: ['request2'] }, // we shouldn't keep tracking the state
c: { requestUUIDs: ['request3'] }, // because we may invalidate when we shouldn't
a: { requestUUIDs: ['request1'], dependentRequestUUIDs: [] }, // this is the state at the moment we're invalidating the cache
b: { requestUUIDs: ['request2'], dependentRequestUUIDs: [] }, // we shouldn't keep tracking the state
c: { requestUUIDs: ['request3'], dependentRequestUUIDs: [] }, // because we may invalidate when we shouldn't
}));
service.invalidateByHref('some-href');
@@ -624,4 +640,42 @@ describe('BaseDataService', () => {
});
});
});
describe('addDependency', () => {
let addDependencySpy;
beforeEach(() => {
addDependencySpy = spyOn(objectCache, 'addDependency');
});
it('should call objectCache.addDependency with the object\'s self link', () => {
addDependencySpy.and.callFake((href$: Observable<string>, dependsOn$: Observable<string>) => {
observableCombineLatest([href$, dependsOn$]).subscribe(([href, dependsOn]) => {
expect(href).toBe('object-href');
expect(dependsOn).toBe('dependsOnHref');
});
});
(service as any).addDependency(
createSuccessfulRemoteDataObject$({ _links: { self: { href: 'object-href' } } }),
observableOf('dependsOnHref')
);
expect(addDependencySpy).toHaveBeenCalled();
});
it('should call objectCache.addDependency without an href if request failed', () => {
addDependencySpy.and.callFake((href$: Observable<string>, dependsOn$: Observable<string>) => {
observableCombineLatest([href$, dependsOn$]).subscribe(([href, dependsOn]) => {
expect(href).toBe(undefined);
expect(dependsOn).toBe('dependsOnHref');
});
});
(service as any).addDependency(
createFailedRemoteDataObject$('something went wrong'),
observableOf('dependsOnHref')
);
expect(addDependencySpy).toHaveBeenCalled();
});
});
});

View File

@@ -23,7 +23,9 @@ import { PaginatedList } from '../paginated-list.model';
import { ObjectCacheEntry } from '../../cache/object-cache.reducer';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { HALDataService } from './hal-data-service.interface';
import { getFirstCompletedRemoteData } from '../../shared/operators';
export const EMBED_SEPARATOR = '%2F';
/**
* Common functionality for data services.
* Specific functionality that not all services would need
@@ -201,7 +203,7 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
let nestEmbed = embedString;
linksToFollow.forEach((linkToFollow: FollowLinkConfig<T>) => {
if (hasValue(linkToFollow) && linkToFollow.shouldEmbed) {
nestEmbed = nestEmbed + '/' + String(linkToFollow.name);
nestEmbed = nestEmbed + EMBED_SEPARATOR + String(linkToFollow.name);
// Add the nested embeds size if given in the FollowLinkConfig.FindListOptions
if (hasValue(linkToFollow.findListOptions) && hasValue(linkToFollow.findListOptions.elementsPerPage)) {
const nestedEmbedSize = 'embed.size=' + nestEmbed.split('=')[1] + '=' + linkToFollow.findListOptions.elementsPerPage;
@@ -352,19 +354,55 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
}
/**
* Invalidate a cached object by its href
* @param href the href to invalidate
* Shorthand method to add a dependency to a cached object
* ```
* const out$ = this.findByHref(...); // or another method that sends a request
* this.addDependency(out$, dependsOnHref);
* ```
* When {@link dependsOnHref$} is invalidated, {@link object$} will be invalidated as well.
*
*
* @param object$ the cached object
* @param dependsOnHref$ the href of the object it should depend on
*/
public invalidateByHref(href: string): Observable<boolean> {
protected addDependency(object$: Observable<RemoteData<T | PaginatedList<T>>>, dependsOnHref$: string | Observable<string>) {
this.objectCache.addDependency(
object$.pipe(
getFirstCompletedRemoteData(),
switchMap((rd: RemoteData<T>) => {
if (rd.hasSucceeded) {
return [rd.payload._links.self.href];
} else {
// undefined href will be skipped in objectCache.addDependency
return [undefined];
}
}),
),
dependsOnHref$
);
}
/**
* Invalidate an existing DSpaceObject by marking all requests it is included in as stale
* @param href The self link of the object to be invalidated
* @return An Observable that will emit `true` once all requests are stale
*/
invalidateByHref(href: string): Observable<boolean> {
const done$ = new AsyncSubject<boolean>();
this.objectCache.getByHref(href).pipe(
take(1),
switchMap((oce: ObjectCacheEntry) => observableFrom(oce.requestUUIDs).pipe(
mergeMap((requestUUID: string) => this.requestService.setStaleByUUID(requestUUID)),
toArray(),
)),
switchMap((oce: ObjectCacheEntry) => {
return observableFrom([
...oce.requestUUIDs,
...oce.dependentRequestUUIDs
]).pipe(
mergeMap((requestUUID: string) => this.requestService.setStaleByUUID(requestUUID)),
toArray(),
);
}),
).subscribe(() => {
this.objectCache.removeDependents(href);
done$.next(true);
done$.complete();
});

View File

@@ -22,6 +22,7 @@ import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.s
import { HALEndpointService } from '../../shared/hal-endpoint.service';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { Observable, of as observableOf } from 'rxjs';
import { EMBED_SEPARATOR } from './base-data.service';
/**
* Tests whether calls to `FindAllData` methods are correctly patched through in a concrete data service that implements it
@@ -276,7 +277,7 @@ describe('FindAllDataImpl', () => {
});
it('should include nested linksToFollow 3lvl', () => {
const expected = `${endpoint}?embed=owningCollection/itemtemplate/relationships`;
const expected = `${endpoint}?embed=owningCollection${EMBED_SEPARATOR}itemtemplate${EMBED_SEPARATOR}relationships`;
(service as any).getFindAllHref({}, null, followLink('owningCollection', {}, followLink('itemtemplate', {}, followLink('relationships')))).subscribe((value) => {
expect(value).toBe(expected);
@@ -284,7 +285,7 @@ describe('FindAllDataImpl', () => {
});
it('should include nested linksToFollow 2lvl and nested embed\'s size', () => {
const expected = `${endpoint}?embed.size=owningCollection/itemtemplate=4&embed=owningCollection/itemtemplate`;
const expected = `${endpoint}?embed.size=owningCollection${EMBED_SEPARATOR}itemtemplate=4&embed=owningCollection${EMBED_SEPARATOR}itemtemplate`;
const config: FindListOptions = Object.assign(new FindListOptions(), {
elementsPerPage: 4,
});

View File

@@ -19,6 +19,7 @@ import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.s
import { HALEndpointService } from '../../shared/hal-endpoint.service';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { IdentifiableDataService } from './identifiable-data.service';
import { EMBED_SEPARATOR } from './base-data.service';
const endpoint = 'https://rest.api/core';
@@ -137,7 +138,7 @@ describe('IdentifiableDataService', () => {
});
it('should include nested linksToFollow 3lvl', () => {
const expected = `${endpointMock}/${resourceIdMock}?embed=owningCollection/itemtemplate/relationships`;
const expected = `${endpointMock}/${resourceIdMock}?embed=owningCollection${EMBED_SEPARATOR}itemtemplate${EMBED_SEPARATOR}relationships`;
const result = (service as any).getIDHref(endpointMock, resourceIdMock, followLink('owningCollection', {}, followLink('itemtemplate', {}, followLink('relationships'))));
expect(result).toEqual(expected);
});

View File

@@ -178,7 +178,12 @@ describe('PatchDataImpl', () => {
describe('patch', () => {
const dso = {
uuid: 'dso-uuid'
uuid: 'dso-uuid',
_links: {
self: {
href: 'dso-href',
}
}
};
const operations = [
Object.assign({
@@ -188,14 +193,23 @@ describe('PatchDataImpl', () => {
}) as Operation
];
beforeEach((done) => {
service.patch(dso, operations).subscribe(() => {
done();
});
it('should send a PatchRequest', () => {
service.patch(dso, operations);
expect(requestService.send).toHaveBeenCalledWith(jasmine.any(PatchRequest));
});
it('should send a PatchRequest', () => {
expect(requestService.send).toHaveBeenCalledWith(jasmine.any(PatchRequest));
it('should invalidate the cached object if successfully patched', () => {
spyOn(rdbService, 'buildFromRequestUUIDAndAwait');
spyOn(service, 'invalidateByHref');
service.patch(dso, operations);
expect(rdbService.buildFromRequestUUIDAndAwait).toHaveBeenCalled();
expect((rdbService.buildFromRequestUUIDAndAwait as jasmine.Spy).calls.argsFor(0)[0]).toBe(requestService.generateRequestId());
const callback = (rdbService.buildFromRequestUUIDAndAwait as jasmine.Spy).calls.argsFor(0)[1];
callback();
expect(service.invalidateByHref).toHaveBeenCalledWith('dso-href');
});
});

View File

@@ -101,7 +101,7 @@ export class PatchDataImpl<T extends CacheableObject> extends IdentifiableDataSe
this.requestService.send(request);
});
return this.rdbService.buildFromRequestUUID(requestId);
return this.rdbService.buildFromRequestUUIDAndAwait(requestId, () => this.invalidateByHref(object._links.self.href));
}
/**

View File

@@ -9,6 +9,7 @@ import { GetRequest, IdentifierType } from './request.models';
import { RequestService } from './request.service';
import { createSuccessfulRemoteDataObject } from '../../shared/remote-data.utils';
import { Item } from '../shared/item.model';
import { EMBED_SEPARATOR } from './base/base-data.service';
describe('DsoRedirectService', () => {
let scheduler: TestScheduler;
@@ -174,7 +175,7 @@ describe('DsoRedirectService', () => {
});
it('should include nested linksToFollow 3lvl', () => {
const expected = `${requestUUIDURL}&embed=owningCollection/itemtemplate/relationships`;
const expected = `${requestUUIDURL}&embed=owningCollection${EMBED_SEPARATOR}itemtemplate${EMBED_SEPARATOR}relationships`;
const result = (service as any).dataService.getIDHref(
pidLink,
dsoUUID,

View File

@@ -2,7 +2,7 @@ import { AuthorizationDataService } from './authorization-data.service';
import { SiteDataService } from '../site-data.service';
import { Site } from '../../shared/site.model';
import { EPerson } from '../../eperson/models/eperson.model';
import { of as observableOf } from 'rxjs';
import { of as observableOf, combineLatest as observableCombineLatest, Observable } from 'rxjs';
import { FeatureID } from './feature-id';
import { hasValue } from '../../../shared/empty.util';
import { RequestParam } from '../../cache/models/request-param.model';
@@ -12,10 +12,12 @@ import { createPaginatedList } from '../../../shared/testing/utils.test';
import { Feature } from '../../shared/feature.model';
import { FindListOptions } from '../find-list-options.model';
import { testSearchDataImplementation } from '../base/search-data.spec';
import { getMockObjectCacheService } from '../../../shared/mocks/object-cache.service.mock';
describe('AuthorizationDataService', () => {
let service: AuthorizationDataService;
let siteService: SiteDataService;
let objectCache;
let site: Site;
let ePerson: EPerson;
@@ -38,7 +40,8 @@ describe('AuthorizationDataService', () => {
siteService = jasmine.createSpyObj('siteService', {
find: observableOf(site),
});
service = new AuthorizationDataService(requestService, undefined, undefined, undefined, siteService);
objectCache = getMockObjectCacheService();
service = new AuthorizationDataService(requestService, undefined, objectCache, undefined, siteService);
}
beforeEach(() => {
@@ -110,6 +113,43 @@ describe('AuthorizationDataService', () => {
expect(service.searchBy).toHaveBeenCalledWith('object', createExpected(objectUrl, ePersonUuid, FeatureID.LoginOnBehalfOf), true, true);
});
});
describe('dependencies', () => {
let addDependencySpy;
beforeEach(() => {
(service.searchBy as any).and.returnValue(observableOf('searchBy RD$'));
addDependencySpy = spyOn(service as any, 'addDependency');
});
it('should add a dependency on the objectUrl', (done) => {
addDependencySpy.and.callFake((href$: Observable<string>, dependsOn$: Observable<string>) => {
observableCombineLatest([href$, dependsOn$]).subscribe(([href, dependsOn]) => {
expect(href).toBe('searchBy RD$');
expect(dependsOn).toBe('object-href');
});
});
service.searchByObject(FeatureID.AdministratorOf, 'object-href').subscribe(() => {
expect(addDependencySpy).toHaveBeenCalled();
done();
});
});
it('should add a dependency on the Site object if no objectUrl is given', (done) => {
addDependencySpy.and.callFake((object$: Observable<any>, dependsOn$: Observable<string>) => {
observableCombineLatest([object$, dependsOn$]).subscribe(([object, dependsOn]) => {
expect(object).toBe('searchBy RD$');
expect(dependsOn).toBe('test-site-href');
});
});
service.searchByObject(FeatureID.AdministratorOf).subscribe(() => {
expect(addDependencySpy).toHaveBeenCalled();
done();
});
});
});
});
describe('isAuthorized', () => {

View File

@@ -11,10 +11,10 @@ import { followLink, FollowLinkConfig } from '../../../shared/utils/follow-link-
import { RemoteData } from '../remote-data';
import { PaginatedList } from '../paginated-list.model';
import { catchError, map, switchMap } from 'rxjs/operators';
import { hasValue, isNotEmpty } from '../../../shared/empty.util';
import { hasNoValue, hasValue, isNotEmpty } from '../../../shared/empty.util';
import { RequestParam } from '../../cache/models/request-param.model';
import { AuthorizationSearchParams } from './authorization-search-params';
import { addSiteObjectUrlIfEmpty, oneAuthorizationMatchesFeature } from './authorization-utils';
import { oneAuthorizationMatchesFeature } from './authorization-utils';
import { FeatureID } from './feature-id';
import { getFirstCompletedRemoteData } from '../../shared/operators';
import { FindListOptions } from '../find-list-options.model';
@@ -96,12 +96,28 @@ export class AuthorizationDataService extends BaseDataService<Authorization> imp
* {@link HALLink}s should be automatically resolved
*/
searchByObject(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Authorization>[]): Observable<RemoteData<PaginatedList<Authorization>>> {
return observableOf(new AuthorizationSearchParams(objectUrl, ePersonUuid, featureId)).pipe(
addSiteObjectUrlIfEmpty(this.siteService),
const objectUrl$ = observableOf(objectUrl).pipe(
switchMap((url) => {
if (hasNoValue(url)) {
return this.siteService.find().pipe(
map((site) => site.self)
);
} else {
return observableOf(url);
}
}),
);
const out$ = objectUrl$.pipe(
map((url: string) => new AuthorizationSearchParams(url, ePersonUuid, featureId)),
switchMap((params: AuthorizationSearchParams) => {
return this.searchBy(this.searchByObjectPath, this.createSearchOptions(params.objectUrl, options, params.ePersonUuid, params.featureId), useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
})
);
this.addDependency(out$, objectUrl$);
return out$;
}
/**

View File

@@ -24,6 +24,8 @@ import { dataService } from '../base/data-service.decorator';
export const METADATA_IMPORT_SCRIPT_NAME = 'metadata-import';
export const METADATA_EXPORT_SCRIPT_NAME = 'metadata-export';
export const BATCH_IMPORT_SCRIPT_NAME = 'import';
export const BATCH_EXPORT_SCRIPT_NAME = 'export';
@Injectable()
@dataService(SCRIPT)

View File

@@ -307,7 +307,7 @@ describe('EPersonDataService', () => {
it('should sent a patch request with an uuid, token and new password to the epersons endpoint', () => {
service.patchPasswordWithToken('test-uuid', 'test-token', 'test-password');
const operation = Object.assign({ op: 'add', path: '/password', value: 'test-password' });
const operation = Object.assign({ op: 'add', path: '/password', value: { new_password: 'test-password' } });
const expected = new PatchRequest(requestService.generateRequestId(), epersonsEndpoint + '/test-uuid?token=test-token', [operation]);
expect(requestService.send).toHaveBeenCalledWith(expected);

View File

@@ -3,7 +3,10 @@ import { createSelector, select, Store } from '@ngrx/store';
import { Operation } from 'fast-json-patch';
import { Observable } from 'rxjs';
import { find, map, take } from 'rxjs/operators';
import { EPeopleRegistryCancelEPersonAction, EPeopleRegistryEditEPersonAction } from '../../access-control/epeople-registry/epeople-registry.actions';
import {
EPeopleRegistryCancelEPersonAction,
EPeopleRegistryEditEPersonAction
} from '../../access-control/epeople-registry/epeople-registry.actions';
import { EPeopleRegistryState } from '../../access-control/epeople-registry/epeople-registry.reducers';
import { AppState } from '../../app.reducer';
import { hasNoValue, hasValue } from '../../shared/empty.util';
@@ -318,7 +321,7 @@ export class EPersonDataService extends IdentifiableDataService<EPerson> impleme
patchPasswordWithToken(uuid: string, token: string, password: string): Observable<RemoteData<EPerson>> {
const requestId = this.requestService.generateRequestId();
const operation = Object.assign({ op: 'add', path: '/password', value: password });
const operation = Object.assign({ op: 'add', path: '/password', value: { 'new_password': password } });
const hrefObs = this.halService.getEndpoint(this.linkPath).pipe(
map((endpoint: string) => this.getIDHref(endpoint, uuid)),

View File

@@ -26,10 +26,9 @@ import { EPersonMock, EPersonMock2 } from '../../shared/testing/eperson.mock';
import { createPaginatedList, createRequestEntry$ } from '../../shared/testing/utils.test';
import { CoreState } from '../core-state.model';
import { FindListOptions } from '../data/find-list-options.model';
import { ObjectCacheService } from '../cache/object-cache.service';
import { getMockLinkService } from '../../shared/mocks/link-service.mock';
import { of as observableOf } from 'rxjs';
import { ObjectCacheEntry } from '../cache/object-cache.reducer';
import { getMockObjectCacheService } from '../../shared/mocks/object-cache.service.mock';
describe('GroupDataService', () => {
let service: GroupDataService;
@@ -42,7 +41,7 @@ describe('GroupDataService', () => {
let groups$;
let halService;
let rdbService;
let objectCache: ObjectCacheService;
let objectCache;
function init() {
restEndpointURL = 'https://dspace.4science.it/dspace-spring-rest/api/eperson';
groupsEndpoint = `${restEndpointURL}/groups`;
@@ -50,7 +49,7 @@ describe('GroupDataService', () => {
groups$ = createSuccessfulRemoteDataObject$(createPaginatedList(groups));
rdbService = getMockRemoteDataBuildServiceHrefMap(undefined, { 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups': groups$ });
halService = new HALEndpointServiceStub(restEndpointURL);
objectCache = new ObjectCacheService(store, getMockLinkService());
objectCache = getMockObjectCacheService();
TestBed.configureTestingModule({
imports: [
CommonModule,
@@ -114,8 +113,9 @@ describe('GroupDataService', () => {
describe('addSubGroupToGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.addSubGroupToGroup(GroupMock, GroupMock2).subscribe();
@@ -143,8 +143,9 @@ describe('GroupDataService', () => {
describe('deleteSubGroupFromGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.deleteSubGroupFromGroup(GroupMock, GroupMock2).subscribe();
@@ -168,8 +169,9 @@ describe('GroupDataService', () => {
describe('addMemberToGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.addMemberToGroup(GroupMock, EPersonMock2).subscribe();
@@ -198,8 +200,9 @@ describe('GroupDataService', () => {
describe('deleteMemberFromGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.deleteMemberFromGroup(GroupMock, EPersonMock).subscribe();

View File

@@ -0,0 +1,3 @@
import { ResourceType } from '../../shared/resource-type';
export const WORKSPACEITEM = new ResourceType('workspaceitem');

View File

@@ -2,17 +2,25 @@ import { TestBed } from '@angular/core/testing';
import { BrowserHardRedirectService } from './browser-hard-redirect.service';
describe('BrowserHardRedirectService', () => {
const origin = 'https://test-host.com:4000';
const mockLocation = {
href: undefined,
pathname: '/pathname',
search: '/search',
origin
} as Location;
const service: BrowserHardRedirectService = new BrowserHardRedirectService(mockLocation);
let origin: string;
let mockLocation: Location;
let service: BrowserHardRedirectService;
beforeEach(() => {
origin = 'https://test-host.com:4000';
mockLocation = {
href: undefined,
pathname: '/pathname',
search: '/search',
origin,
replace: (url: string) => {
mockLocation.href = url;
}
} as Location;
spyOn(mockLocation, 'replace');
service = new BrowserHardRedirectService(mockLocation);
TestBed.configureTestingModule({});
});
@@ -28,8 +36,8 @@ describe('BrowserHardRedirectService', () => {
service.redirect(redirect);
});
it('should update the location', () => {
expect(mockLocation.href).toEqual(redirect);
it('should call location.replace with the new url', () => {
expect(mockLocation.replace).toHaveBeenCalledWith(redirect);
});
});

View File

@@ -24,7 +24,7 @@ export class BrowserHardRedirectService extends HardRedirectService {
* @param url
*/
redirect(url: string) {
this.location.href = url;
this.location.replace(url);
}
/**

View File

@@ -2,7 +2,7 @@ import { deserializeAs, inheritSerialization } from 'cerialize';
import { inheritLinkAnnotations, typedObject } from '../../cache/builders/build-decorators';
import { IDToUUIDSerializer } from '../../cache/id-to-uuid-serializer';
import { SubmissionObject } from './submission-object.model';
import { ResourceType } from '../../shared/resource-type';
import { WORKSPACEITEM } from '../../eperson/models/workspaceitem.resource-type';
/**
* A model class for a WorkspaceItem.
@@ -11,7 +11,7 @@ import { ResourceType } from '../../shared/resource-type';
@inheritSerialization(SubmissionObject)
@inheritLinkAnnotations(SubmissionObject)
export class WorkspaceItem extends SubmissionObject {
static type = new ResourceType('workspaceitem');
static type = WORKSPACEITEM;
/**
* The universally unique identifier of this WorkspaceItem

View File

@@ -6,6 +6,10 @@
<ds-thumbnail [thumbnail]="dso?.thumbnail | async" [limitWidth]="true">
</ds-thumbnail>
</a>
<span *ngIf="linkType == linkTypes.None" class="lead item-list-title dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async" [limitWidth]="true">
</ds-thumbnail>
</span>
</div>
<div [ngClass]="showThumbnails ? 'col-9' : 'col-md-12'">
<ds-type-badge *ngIf="showLabel" [object]="dso"></ds-type-badge>

View File

@@ -6,6 +6,10 @@
<ds-thumbnail [thumbnail]="dso?.thumbnail | async" [limitWidth]="true">
</ds-thumbnail>
</a>
<span *ngIf="linkType == linkTypes.None" class="lead item-list-title dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async" [limitWidth]="true">
</ds-thumbnail>
</span>
</div>
<div [ngClass]="showThumbnails ? 'col-9' : 'col-md-12'">
<ds-type-badge *ngIf="showLabel" [object]="dso"></ds-type-badge>

View File

@@ -5,6 +5,10 @@
<ds-thumbnail [thumbnail]="dso?.thumbnail | async" [limitWidth]="true">
</ds-thumbnail>
</a>
<span *ngIf="linkType == linkTypes.None" class="lead item-list-title dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async" [limitWidth]="true">
</ds-thumbnail>
</span>
</div>
<div [ngClass]="showThumbnails ? 'col-9' : 'col-md-12'">
<ds-type-badge *ngIf="showLabel" [object]="dso"></ds-type-badge>

View File

@@ -1,33 +1,40 @@
<div class="row">
<div *ngIf="showThumbnails" class="col-3 col-md-2">
<a *ngIf="linkType != linkTypes.None" [target]="(linkType == linkTypes.ExternalLink) ? '_blank' : '_self'"
rel="noopener noreferrer"
[routerLink]="[itemPageRoute]" class="dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async"
[defaultImage]="'assets/images/orgunit-placeholder.svg'"
[alt]="'thumbnail.orgunit.alt'"
[placeholder]="'thumbnail.orgunit.placeholder'">
</ds-thumbnail>
</a>
</div>
<div [ngClass]="showThumbnails ? 'col-9' : 'col-md-12'">
<ds-type-badge *ngIf="showLabel" [object]="dso"></ds-type-badge>
<ds-truncatable [id]="dso.id">
<a *ngIf="linkType != linkTypes.None" [target]="(linkType == linkTypes.ExternalLink) ? '_blank' : '_self'"
rel="noopener noreferrer"
[routerLink]="[itemPageRoute]" class="lead"
[innerHTML]="dsoTitle"></a>
<span *ngIf="linkType == linkTypes.None"
class="lead"
[innerHTML]="dsoTitle"></span>
<span class="text-muted">
<div *ngIf="showThumbnails" class="col-3 col-md-2">
<a *ngIf="linkType != linkTypes.None" [target]="(linkType == linkTypes.ExternalLink) ? '_blank' : '_self'"
rel="noopener noreferrer"
[routerLink]="[itemPageRoute]" class="dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async"
[defaultImage]="'assets/images/orgunit-placeholder.svg'"
[alt]="'thumbnail.orgunit.alt'"
[placeholder]="'thumbnail.orgunit.placeholder'">
</ds-thumbnail>
</a>
<span *ngIf="linkType == linkTypes.None" class="dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async"
[defaultImage]="'assets/images/orgunit-placeholder.svg'"
[alt]="'thumbnail.orgunit.alt'"
[placeholder]="'thumbnail.orgunit.placeholder'">
</ds-thumbnail>
</span>
</div>
<div [ngClass]="showThumbnails ? 'col-9' : 'col-md-12'">
<ds-type-badge *ngIf="showLabel" [object]="dso"></ds-type-badge>
<ds-truncatable [id]="dso.id">
<a *ngIf="linkType != linkTypes.None" [target]="(linkType == linkTypes.ExternalLink) ? '_blank' : '_self'"
rel="noopener noreferrer"
[routerLink]="[itemPageRoute]" class="lead"
[innerHTML]="dsoTitle || ('orgunit.listelement.no-title' | translate)"></a>
<span *ngIf="linkType == linkTypes.None"
class="lead"
[innerHTML]="dsoTitle || ('orgunit.listelement.no-title' | translate)"></span>
<span class="text-muted">
<span *ngIf="dso.allMetadata(['dc.description']).length > 0"
class="item-list-org-unit-description">
<ds-truncatable-part [id]="dso.id" [minLines]="3"><span
[innerHTML]="firstMetadataValue('dc.description')"></span>
[innerHTML]="firstMetadataValue('dc.description')"></span>
</ds-truncatable-part>
</span>
</span>
</ds-truncatable>
</div>
</ds-truncatable>
</div>
</div>

View File

@@ -10,6 +10,8 @@ import { ItemSearchResult } from '../../../../../shared/object-collection/shared
import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service';
import { DSONameServiceMock } from '../../../../../shared/mocks/dso-name.service.mock';
import { APP_CONFIG } from '../../../../../../config/app-config.interface';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateLoaderMock } from '../../../../../shared/mocks/translate-loader.mock';
let orgUnitListElementComponent: OrgUnitSearchResultListElementComponent;
let fixture: ComponentFixture<OrgUnitSearchResultListElementComponent>;
@@ -66,6 +68,13 @@ const enviromentNoThumbs = {
describe('OrgUnitSearchResultListElementComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}
)],
declarations: [ OrgUnitSearchResultListElementComponent , TruncatePipe],
providers: [
{ provide: TruncatableService, useValue: {} },
@@ -129,6 +138,13 @@ describe('OrgUnitSearchResultListElementComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}
)],
declarations: [OrgUnitSearchResultListElementComponent, TruncatePipe],
providers: [
{provide: TruncatableService, useValue: {}},

View File

@@ -9,6 +9,13 @@
[placeholder]="'thumbnail.person.placeholder'">
</ds-thumbnail>
</a>
<span *ngIf="linkType == linkTypes.None" class="dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async"
[defaultImage]="'assets/images/person-placeholder.svg'"
[alt]="'thumbnail.person.alt'"
[placeholder]="'thumbnail.person.placeholder'">
</ds-thumbnail>
</span>
</div>
<div [ngClass]="showThumbnails ? 'col-9 col-md-10' : 'col-12'">
<ds-type-badge *ngIf="showLabel" [object]="dso"></ds-type-badge>
@@ -16,10 +23,10 @@
<a *ngIf="linkType != linkTypes.None" [target]="(linkType == linkTypes.ExternalLink) ? '_blank' : '_self'"
rel="noopener noreferrer"
[routerLink]="[itemPageRoute]" class="lead"
[innerHTML]="dsoTitle"></a>
[innerHTML]="dsoTitle || ('person.listelement.no-title' | translate)"></a>
<span *ngIf="linkType == linkTypes.None"
class="lead"
[innerHTML]="dsoTitle"></span>
[innerHTML]="dsoTitle || ('person.listelement.no-title' | translate)"></span>
<span class="text-muted">
<ds-truncatable-part [id]="dso.id" [minLines]="1">
<span *ngIf="dso.allMetadata(['person.jobTitle']).length > 0"

View File

@@ -10,6 +10,8 @@ import { TruncatableService } from '../../../../../shared/truncatable/truncatabl
import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service';
import { DSONameServiceMock } from '../../../../../shared/mocks/dso-name.service.mock';
import { APP_CONFIG } from '../../../../../../config/app-config.interface';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateLoaderMock } from '../../../../../shared/mocks/translate-loader.mock';
let personListElementComponent: PersonSearchResultListElementComponent;
let fixture: ComponentFixture<PersonSearchResultListElementComponent>;
@@ -66,6 +68,13 @@ const enviromentNoThumbs = {
describe('PersonSearchResultListElementComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}
)],
declarations: [PersonSearchResultListElementComponent, TruncatePipe],
providers: [
{ provide: TruncatableService, useValue: {} },
@@ -129,6 +138,13 @@ describe('PersonSearchResultListElementComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}
)],
declarations: [PersonSearchResultListElementComponent, TruncatePipe],
providers: [
{provide: TruncatableService, useValue: {}},

View File

@@ -9,6 +9,13 @@
[placeholder]="'thumbnail.project.placeholder'">
</ds-thumbnail>
</a>
<span *ngIf="linkType == linkTypes.None" class="dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async"
[defaultImage]="'assets/images/project-placeholder.svg'"
[alt]="'thumbnail.project.alt'"
[placeholder]="'thumbnail.project.placeholder'">
</ds-thumbnail>
</span>
</div>
<div [ngClass]="showThumbnails ? 'col-9' : 'col-md-12'">
<ds-truncatable [id]="dso.id">

View File

@@ -8,6 +8,13 @@
[placeholder]="'thumbnail.person.placeholder'">
</ds-thumbnail>
</a>
<span *ngIf="linkType == linkTypes.None" class="dont-break-out">
<ds-thumbnail [thumbnail]="dso?.thumbnail | async"
[defaultImage]="'assets/images/person-placeholder.svg'"
[alt]="'thumbnail.person.alt'"
[placeholder]="'thumbnail.person.placeholder'">
</ds-thumbnail>
</span>
</div>
<div [ngClass]="showThumbnails ? 'col-9' : 'col-md-12'">
<div class="d-flex">

View File

@@ -6,7 +6,7 @@
</a>
<nav role="navigation" [attr.aria-label]="'nav.user.description' | translate" class="navbar navbar-light navbar-expand-md flex-shrink-0 px-0">
<ds-search-navbar></ds-search-navbar>
<ds-themed-search-navbar></ds-themed-search-navbar>
<ds-lang-switch></ds-lang-switch>
<ds-themed-auth-nav-menu></ds-themed-auth-nav-menu>
<ds-impersonate-navbar></ds-impersonate-navbar>

View File

@@ -10,6 +10,9 @@ import { StatisticsModule } from '../statistics/statistics.module';
import { ThemedHomeNewsComponent } from './home-news/themed-home-news.component';
import { ThemedHomePageComponent } from './themed-home-page.component';
import { RecentItemListComponent } from './recent-item-list/recent-item-list.component';
import { JournalEntitiesModule } from '../entity-groups/journal-entities/journal-entities.module';
import { ResearchEntitiesModule } from '../entity-groups/research-entities/research-entities.module';
const DECLARATIONS = [
HomePageComponent,
ThemedHomePageComponent,
@@ -22,7 +25,9 @@ const DECLARATIONS = [
@NgModule({
imports: [
CommonModule,
SharedModule,
SharedModule.withEntryComponents(),
JournalEntitiesModule.withEntryComponents(),
ResearchEntitiesModule.withEntryComponents(),
HomePageRoutingModule,
StatisticsModule.forRoot()
],

View File

@@ -1,5 +1,5 @@
<ng-container *ngVar="(itemRD$ | async) as itemRD">
<div class="mt-4" *ngIf="itemRD?.hasSucceeded && itemRD?.payload?.page.length > 0" @fadeIn>
<div class="mt-4" [ngClass]="placeholderFontClass" *ngIf="itemRD?.hasSucceeded && itemRD?.payload?.page.length > 0" @fadeIn>
<div class="d-flex flex-row border-bottom mb-4 pb-4 ng-tns-c416-2"></div>
<h2> {{'home.recent-submissions.head' | translate}}</h2>
<div class="my-4" *ngFor="let item of itemRD?.payload?.page">
@@ -12,4 +12,4 @@
<ds-error *ngIf="itemRD?.hasFailed" message="{{'error.recent-submissions' | translate}}"></ds-error>
<ds-loading *ngIf="!itemRD || itemRD.isLoading" message="{{'loading.recent-submissions' | translate}}">
</ds-loading>
</ng-container>
</ng-container>

View File

@@ -10,8 +10,11 @@ import { SearchConfigurationService } from '../../core/shared/search/search-conf
import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { ViewMode } from 'src/app/core/shared/view-mode.model';
import { of as observableOf } from 'rxjs';
import { APP_CONFIG } from '../../../config/app-config.interface';
import { environment } from '../../../environments/environment';
import { PLATFORM_ID } from '@angular/core';
describe('RecentItemListComponent', () => {
let component: RecentItemListComponent;
let fixture: ComponentFixture<RecentItemListComponent>;
@@ -42,6 +45,8 @@ describe('RecentItemListComponent', () => {
{ provide: SearchService, useValue: searchServiceStub },
{ provide: PaginationService, useValue: paginationService },
{ provide: SearchConfigurationService, useValue: searchConfigServiceStub },
{ provide: APP_CONFIG, useValue: environment },
{ provide: PLATFORM_ID, useValue: 'browser' },
],
})
.compileComponents();

View File

@@ -1,4 +1,4 @@
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ChangeDetectionStrategy, Component, ElementRef, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
import { fadeIn, fadeInOut } from '../../shared/animations/fade';
import { RemoteData } from '../../core/data/remote-data';
@@ -11,12 +11,13 @@ import { SortDirection, SortOptions } from '../../core/cache/models/sort-options
import { environment } from '../../../environments/environment';
import { ViewMode } from '../../core/shared/view-mode.model';
import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service';
import {
toDSpaceObjectListRD
} from '../../core/shared/operators';
import {
Observable,
} from 'rxjs';
import { toDSpaceObjectListRD } from '../../core/shared/operators';
import { Observable } from 'rxjs';
import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface';
import { isPlatformBrowser } from '@angular/common';
import { setPlaceHolderAttributes } from '../../shared/utils/object-list-utils';
@Component({
selector: 'ds-recent-item-list',
templateUrl: './recent-item-list.component.html',
@@ -31,14 +32,22 @@ export class RecentItemListComponent implements OnInit {
itemRD$: Observable<RemoteData<PaginatedList<Item>>>;
paginationConfig: PaginationComponentOptions;
sortConfig: SortOptions;
/**
* The view-mode we're currently on
* @type {ViewMode}
*/
viewMode = ViewMode.ListElement;
constructor(private searchService: SearchService,
private _placeholderFontClass: string;
constructor(
private searchService: SearchService,
private paginationService: PaginationService,
public searchConfigurationService: SearchConfigurationService
public searchConfigurationService: SearchConfigurationService,
protected elementRef: ElementRef,
@Inject(APP_CONFIG) private appConfig: AppConfig,
@Inject(PLATFORM_ID) private platformId: Object,
) {
this.paginationConfig = Object.assign(new PaginationComponentOptions(), {
@@ -50,16 +59,29 @@ export class RecentItemListComponent implements OnInit {
this.sortConfig = new SortOptions(environment.homePage.recentSubmissions.sortField, SortDirection.DESC);
}
ngOnInit(): void {
const linksToFollow: FollowLinkConfig<Item>[] = [];
if (this.appConfig.browseBy.showThumbnails) {
linksToFollow.push(followLink('thumbnail'));
}
this.itemRD$ = this.searchService.search(
new PaginatedSearchOptions({
pagination: this.paginationConfig,
sort: this.sortConfig,
}),
).pipe(toDSpaceObjectListRD()) as Observable<RemoteData<PaginatedList<Item>>>;
undefined,
undefined,
undefined,
...linksToFollow,
).pipe(
toDSpaceObjectListRD()
) as Observable<RemoteData<PaginatedList<Item>>>;
}
ngOnDestroy(): void {
this.paginationService.clearPagination(this.paginationConfig.id);
}
onLoadMore(): void {
this.paginationService.updateRouteWithUrl(this.searchConfigurationService.paginationID, ['search'], {
sortField: environment.homePage.recentSubmissions.sortField,
@@ -68,5 +90,17 @@ export class RecentItemListComponent implements OnInit {
});
}
get placeholderFontClass(): string {
if (this._placeholderFontClass === undefined) {
if (isPlatformBrowser(this.platformId)) {
const width = this.elementRef.nativeElement.offsetWidth;
this._placeholderFontClass = setPlaceHolderAttributes(width);
} else {
this._placeholderFontClass = 'hide-placeholder-text';
}
}
return this._placeholderFontClass;
}
}

View File

@@ -175,14 +175,18 @@ describe('TopLevelCommunityList Component', () => {
});
it('should display a list of top-communities', () => {
const subComList = fixture.debugElement.queryAll(By.css('li'));
expect(subComList.length).toEqual(5);
expect(subComList[0].nativeElement.textContent).toContain('TopCommunity 1');
expect(subComList[1].nativeElement.textContent).toContain('TopCommunity 2');
expect(subComList[2].nativeElement.textContent).toContain('TopCommunity 3');
expect(subComList[3].nativeElement.textContent).toContain('TopCommunity 4');
expect(subComList[4].nativeElement.textContent).toContain('TopCommunity 5');
it('should display a list of top-communities', () => {
waitForAsync(() => {
const subComList = fixture.debugElement.queryAll(By.css('li'));
expect(subComList.length).toEqual(5);
expect(subComList[0].nativeElement.textContent).toContain('TopCommunity 1');
expect(subComList[1].nativeElement.textContent).toContain('TopCommunity 2');
expect(subComList[2].nativeElement.textContent).toContain('TopCommunity 3');
expect(subComList[3].nativeElement.textContent).toContain('TopCommunity 4');
expect(subComList[4].nativeElement.textContent).toContain('TopCommunity 5');
});
});
});

View File

@@ -26,7 +26,7 @@
<td class="w-100">
<div class="value-field">
<div *ngIf="!(editable | async)">
<span class="dont-break-out">{{metadata?.value}}</span>
<span class="dont-break-out preserve-line-breaks">{{metadata?.value}}</span>
</div>
<div *ngIf="(editable | async)" class="field-container">
<textarea class="form-control" type="textarea" attr.aria-labelledby="fieldValue" [(ngModel)]="metadata.value" [dsDebounce]

View File

@@ -6,6 +6,8 @@ import { By } from '@angular/platform-browser';
import { MetadataUriValuesComponent } from './metadata-uri-values.component';
import { isNotEmpty } from '../../../shared/empty.util';
import { MetadataValue } from '../../../core/shared/metadata.models';
import { APP_CONFIG } from '../../../../config/app-config.interface';
import { environment } from '../../../../environments/environment';
let comp: MetadataUriValuesComponent;
let fixture: ComponentFixture<MetadataUriValuesComponent>;
@@ -33,6 +35,9 @@ describe('MetadataUriValuesComponent', () => {
useClass: TranslateLoaderMock
}
})],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
declarations: [MetadataUriValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(MetadataUriValuesComponent, {

View File

@@ -1,5 +1,18 @@
<ds-metadata-field-wrapper [label]="label | translate">
<span class="dont-break-out" *ngFor="let mdValue of mdValues; let last=last;">
{{mdValue.value}}<span *ngIf="!last" [innerHTML]="separator"></span>
</span>
<ng-container *ngFor="let mdValue of mdValues; let last=last;">
<ng-container *ngTemplateOutlet="(renderMarkdown ? markdown : simple); context: {value: mdValue.value, classes: 'dont-break-out preserve-line-breaks'}">
</ng-container>
<span class="separator" *ngIf="!last" [innerHTML]="separator"></span>
</ng-container>
</ds-metadata-field-wrapper>
<ng-template #markdown let-value="value" let-classes="classes">
<span class="{{classes}}" [innerHTML]="value | dsMarkdown | async">
</span>
</ng-template>
<ng-template #simple let-value="value" let-classes="classes">
<span class="{{classes}}">
{{value}}
</span>
</ng-template>

View File

@@ -5,6 +5,8 @@ import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock
import { MetadataValuesComponent } from './metadata-values.component';
import { By } from '@angular/platform-browser';
import { MetadataValue } from '../../../core/shared/metadata.models';
import { APP_CONFIG } from '../../../../config/app-config.interface';
import { environment } from '../../../../environments/environment';
let comp: MetadataValuesComponent;
let fixture: ComponentFixture<MetadataValuesComponent>;
@@ -32,8 +34,11 @@ describe('MetadataValuesComponent', () => {
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
},
})],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
declarations: [MetadataValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(MetadataValuesComponent, {
@@ -58,7 +63,7 @@ describe('MetadataValuesComponent', () => {
});
it('should contain separators equal to the amount of metadata values minus one', () => {
const separators = fixture.debugElement.queryAll(By.css('span>span'));
const separators = fixture.debugElement.queryAll(By.css('span.separator'));
expect(separators.length).toBe(mockMetadata.length - 1);
});

View File

@@ -1,5 +1,6 @@
import { Component, Input } from '@angular/core';
import { Component, Inject, Input, OnChanges, SimpleChanges } from '@angular/core';
import { MetadataValue } from '../../../core/shared/metadata.models';
import { APP_CONFIG, AppConfig } from '../../../../config/app-config.interface';
/**
* This component renders the configured 'values' into the ds-metadata-field-wrapper component.
@@ -10,7 +11,12 @@ import { MetadataValue } from '../../../core/shared/metadata.models';
styleUrls: ['./metadata-values.component.scss'],
templateUrl: './metadata-values.component.html'
})
export class MetadataValuesComponent {
export class MetadataValuesComponent implements OnChanges {
constructor(
@Inject(APP_CONFIG) private appConfig: AppConfig,
) {
}
/**
* The metadata values to display
@@ -27,4 +33,19 @@ export class MetadataValuesComponent {
*/
@Input() label: string;
/**
* Whether the {@link MarkdownPipe} should be used to render these metadata values.
* This will only have effect if {@link MarkdownConfig#enabled} is true.
* Mathjax will only be rendered if {@link MarkdownConfig#mathjax} is true.
*/
@Input() enableMarkdown = false;
/**
* This variable will be true if both {@link environment.markdown.enabled} and {@link enableMarkdown} are true.
*/
renderMarkdown;
ngOnChanges(changes: SimpleChanges): void {
this.renderMarkdown = !!this.appConfig.markdown.enabled && this.enableMarkdown;
}
}

View File

@@ -12,6 +12,7 @@ import { createPaginatedList } from '../../shared/testing/utils.test';
import { of as observableOf } from 'rxjs';
import { MiradorViewerService } from './mirador-viewer.service';
import { HostWindowService } from '../../shared/host-window.service';
import { BundleDataService } from '../../core/data/bundle-data.service';
function getItem(metadata: MetadataMap) {
@@ -46,6 +47,7 @@ describe('MiradorViewerComponent with search', () => {
declarations: [MiradorViewerComponent],
providers: [
{ provide: BitstreamDataService, useValue: {} },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
],
schemas: [NO_ERRORS_SCHEMA]
@@ -108,6 +110,7 @@ describe('MiradorViewerComponent with multiple images', () => {
declarations: [MiradorViewerComponent],
providers: [
{ provide: BitstreamDataService, useValue: {} },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
],
schemas: [NO_ERRORS_SCHEMA]
@@ -167,6 +170,7 @@ describe('MiradorViewerComponent with a single image', () => {
declarations: [MiradorViewerComponent],
providers: [
{ provide: BitstreamDataService, useValue: {} },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
],
schemas: [NO_ERRORS_SCHEMA]
@@ -225,6 +229,7 @@ describe('MiradorViewerComponent in development mode', () => {
set: {
providers: [
{ provide: MiradorViewerService, useValue: viewerService },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
]
}

View File

@@ -8,6 +8,7 @@ import { map, take } from 'rxjs/operators';
import { isPlatformBrowser } from '@angular/common';
import { MiradorViewerService } from './mirador-viewer.service';
import { HostWindowService, WidthCategory } from '../../shared/host-window.service';
import { BundleDataService } from '../../core/data/bundle-data.service';
@Component({
selector: 'ds-mirador-viewer',
@@ -55,6 +56,7 @@ export class MiradorViewerComponent implements OnInit {
constructor(private sanitizer: DomSanitizer,
private viewerService: MiradorViewerService,
private bitstreamDataService: BitstreamDataService,
private bundleDataService: BundleDataService,
private hostWindowService: HostWindowService,
@Inject(PLATFORM_ID) private platformId: any) {
}
@@ -107,10 +109,10 @@ export class MiradorViewerComponent implements OnInit {
this.notMobile = !(category === WidthCategory.XS || category === WidthCategory.SM);
});
// We need to set the multi property to true if the
// item is searchable or when the ORIGINAL bundle contains more
// than 1 image. (The multi property determines whether the
// Mirador side thumbnail navigation panel is shown.)
// Set the multi property. The default mirador configuration adds a right
// thumbnail navigation panel to the viewer when multi is 'true'.
// Set the multi property to 'true' if the item is searchable.
if (this.searchable) {
this.multi = true;
const observable = of('');
@@ -120,8 +122,12 @@ export class MiradorViewerComponent implements OnInit {
})
);
} else {
// Sets the multi value based on the image count.
this.iframeViewerUrl = this.viewerService.getImageCount(this.object, this.bitstreamDataService).pipe(
// Set the multi property based on the image count in IIIF-eligible bundles.
// Any count greater than 1 sets the value to 'true'.
this.iframeViewerUrl = this.viewerService.getImageCount(
this.object,
this.bitstreamDataService,
this.bundleDataService).pipe(
map(c => {
if (c > 1) {
this.multi = true;

View File

@@ -1,14 +1,18 @@
import { Injectable, isDevMode } from '@angular/core';
import { Observable } from 'rxjs';
import { Item } from '../../core/shared/item.model';
import { getFirstCompletedRemoteData, getFirstSucceededRemoteDataPayload } from '../../core/shared/operators';
import { last, map, switchMap } from 'rxjs/operators';
import {
getFirstCompletedRemoteData,
} from '../../core/shared/operators';
import { filter, last, map, mergeMap, switchMap } from 'rxjs/operators';
import { RemoteData } from '../../core/data/remote-data';
import { PaginatedList } from '../../core/data/paginated-list.model';
import { Bitstream } from '../../core/shared/bitstream.model';
import { BitstreamFormat } from '../../core/shared/bitstream-format.model';
import { BitstreamDataService } from '../../core/data/bitstream-data.service';
import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { Bundle } from '../../core/shared/bundle.model';
import { BundleDataService } from '../../core/data/bundle-data.service';
@Injectable()
export class MiradorViewerService {
@@ -26,32 +30,64 @@ export class MiradorViewerService {
}
/**
* Returns observable of the number of images in the ORIGINAL bundle
* Returns observable of the number of images found in eligible IIIF bundles. Checks
* the mimetype of the first 5 bitstreams in each bundle.
* @param item
* @param bitstreamDataService
* @param bundleDataService
* @returns the total image count
*/
getImageCount(item: Item, bitstreamDataService: BitstreamDataService): Observable<number> {
let count = 0;
return bitstreamDataService.findAllByItemAndBundleName(item, 'ORIGINAL', {
currentPage: 1,
elementsPerPage: 10
}, true, true, ...this.LINKS_TO_FOLLOW)
.pipe(
getFirstCompletedRemoteData(),
map((bitstreamsRD: RemoteData<PaginatedList<Bitstream>>) => bitstreamsRD.payload),
map((paginatedList: PaginatedList<Bitstream>) => paginatedList.page),
switchMap((bitstreams: Bitstream[]) => bitstreams),
switchMap((bitstream: Bitstream) => bitstream.format.pipe(
getFirstSucceededRemoteDataPayload(),
map((format: BitstreamFormat) => format)
)),
map((format: BitstreamFormat) => {
if (format.mimetype.includes('image')) {
count++;
}
return count;
}),
last()
getImageCount(item: Item, bitstreamDataService: BitstreamDataService, bundleDataService: BundleDataService):
Observable<number> {
let count = 0;
return bundleDataService.findAllByItem(item).pipe(
getFirstCompletedRemoteData(),
map((bundlesRD: RemoteData<PaginatedList<Bundle>>) => {
return bundlesRD.payload;
}),
map((paginatedList: PaginatedList<Bundle>) => paginatedList.page),
switchMap((bundles: Bundle[]) => bundles),
filter((b: Bundle) => this.isIiifBundle(b.name)),
mergeMap((bundle: Bundle) => {
return bitstreamDataService.findAllByItemAndBundleName(item, bundle.name, {
currentPage: 1,
elementsPerPage: 5
}, true, true, ...this.LINKS_TO_FOLLOW).pipe(
getFirstCompletedRemoteData(),
map((bitstreamsRD: RemoteData<PaginatedList<Bitstream>>) => {
return bitstreamsRD.payload;
}),
map((paginatedList: PaginatedList<Bitstream>) => paginatedList.page),
switchMap((bitstreams: Bitstream[]) => bitstreams),
switchMap((bitstream: Bitstream) => bitstream.format.pipe(
getFirstCompletedRemoteData(),
map((formatRD: RemoteData<BitstreamFormat>) => {
return formatRD.payload;
}),
map((format: BitstreamFormat) => {
if (format.mimetype.includes('image')) {
count++;
}
return count;
}),
)
)
);
}),
last()
);
}
isIiifBundle(bundleName: string): boolean {
return !(
bundleName === 'OtherContent' ||
bundleName === 'LICENSE' ||
bundleName === 'THUMBNAIL' ||
bundleName === 'TEXT' ||
bundleName === 'METADATA' ||
bundleName === 'CC-LICENSE' ||
bundleName === 'BRANDED_PREVIEW'
);
}
}

View File

@@ -3,25 +3,30 @@ import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ItemPageAbstractFieldComponent } from './item-page-abstract-field.component';
import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loader.mock';
import { MetadataValuesComponent } from '../../../../field-components/metadata-values/metadata-values.component';
import { mockItemWithMetadataFieldAndValue } from '../item-page-field.component.spec';
import { SharedModule } from '../../../../../shared/shared.module';
import { APP_CONFIG } from '../../../../../../config/app-config.interface';
import { environment } from '../../../../../../environments/environment';
import { By } from '@angular/platform-browser';
let comp: ItemPageAbstractFieldComponent;
let fixture: ComponentFixture<ItemPageAbstractFieldComponent>;
const mockField = 'dc.description.abstract';
const mockValue = 'test value';
describe('ItemPageAbstractFieldComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
})],
declarations: [ItemPageAbstractFieldComponent, MetadataValuesComponent],
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
SharedModule,
],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
declarations: [ItemPageAbstractFieldComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(ItemPageAbstractFieldComponent, {
set: { changeDetection: ChangeDetectionStrategy.Default }
@@ -29,13 +34,13 @@ describe('ItemPageAbstractFieldComponent', () => {
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(ItemPageAbstractFieldComponent);
comp = fixture.componentInstance;
comp.item = mockItemWithMetadataFieldAndValue(mockField, mockValue);
fixture.detectChanges();
}));
it('should display display the correct metadata value', () => {
expect(fixture.nativeElement.innerHTML).toContain(mockValue);
it('should render a ds-metadata-values', () => {
expect(fixture.debugElement.query(By.css('ds-metadata-values'))).toBeDefined();
});
});

View File

@@ -36,4 +36,8 @@ export class ItemPageAbstractFieldComponent extends ItemPageFieldComponent {
*/
label = 'item.page.abstract';
/**
* Use the {@link MarkdownPipe} to render dc.description.abstract values
*/
enableMarkdown = true;
}

View File

@@ -5,6 +5,8 @@ import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loa
import { MetadataValuesComponent } from '../../../../field-components/metadata-values/metadata-values.component';
import { mockItemWithMetadataFieldAndValue } from '../item-page-field.component.spec';
import { ItemPageAuthorFieldComponent } from './item-page-author-field.component';
import { APP_CONFIG } from '../../../../../../config/app-config.interface';
import { environment } from '../../../../../../environments/environment';
let comp: ItemPageAuthorFieldComponent;
let fixture: ComponentFixture<ItemPageAuthorFieldComponent>;
@@ -21,6 +23,9 @@ describe('ItemPageAuthorFieldComponent', () => {
useClass: TranslateLoaderMock
}
})],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
declarations: [ItemPageAuthorFieldComponent, MetadataValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(ItemPageAuthorFieldComponent, {

View File

@@ -5,6 +5,8 @@ import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loa
import { MetadataValuesComponent } from '../../../../field-components/metadata-values/metadata-values.component';
import { mockItemWithMetadataFieldAndValue } from '../item-page-field.component.spec';
import { ItemPageDateFieldComponent } from './item-page-date-field.component';
import { APP_CONFIG } from '../../../../../../config/app-config.interface';
import { environment } from '../../../../../../environments/environment';
let comp: ItemPageDateFieldComponent;
let fixture: ComponentFixture<ItemPageDateFieldComponent>;
@@ -21,6 +23,9 @@ describe('ItemPageDateFieldComponent', () => {
useClass: TranslateLoaderMock
}
})],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
declarations: [ItemPageDateFieldComponent, MetadataValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(ItemPageDateFieldComponent, {

View File

@@ -5,6 +5,8 @@ import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loa
import { MetadataValuesComponent } from '../../../../field-components/metadata-values/metadata-values.component';
import { mockItemWithMetadataFieldAndValue } from '../item-page-field.component.spec';
import { GenericItemPageFieldComponent } from './generic-item-page-field.component';
import { APP_CONFIG } from '../../../../../../config/app-config.interface';
import { environment } from '../../../../../../environments/environment';
let comp: GenericItemPageFieldComponent;
let fixture: ComponentFixture<GenericItemPageFieldComponent>;
@@ -23,6 +25,9 @@ describe('GenericItemPageFieldComponent', () => {
useClass: TranslateLoaderMock
}
})],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
declarations: [GenericItemPageFieldComponent, MetadataValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(GenericItemPageFieldComponent, {

View File

@@ -1,3 +1,8 @@
<div class="item-page-field">
<ds-metadata-values [mdValues]="item?.allMetadata(fields)" [separator]="separator" [label]="label"></ds-metadata-values>
<ds-metadata-values
[mdValues]="item?.allMetadata(fields)"
[separator]="separator"
[label]="label"
[enableMarkdown]="enableMarkdown"
></ds-metadata-values>
</div>

View File

@@ -8,9 +8,14 @@ import { MetadataValuesComponent } from '../../../field-components/metadata-valu
import { MetadataMap, MetadataValue } from '../../../../core/shared/metadata.models';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { createPaginatedList } from '../../../../shared/testing/utils.test';
import { environment } from '../../../../../environments/environment';
import { MarkdownPipe } from '../../../../shared/utils/markdown.pipe';
import { SharedModule } from '../../../../shared/shared.module';
import { APP_CONFIG } from '../../../../../config/app-config.interface';
let comp: ItemPageFieldComponent;
let fixture: ComponentFixture<ItemPageFieldComponent>;
let markdownSpy;
const mockValue = 'test value';
const mockField = 'dc.test';
@@ -18,32 +23,109 @@ const mockLabel = 'test label';
const mockFields = [mockField];
describe('ItemPageFieldComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
})],
let appConfig = Object.assign({}, environment, {
markdown: {
enabled: false,
mathjax: false,
}
});
const buildTestEnvironment = async () => {
await TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
SharedModule,
],
providers: [
{ provide: APP_CONFIG, useValue: appConfig },
],
declarations: [ItemPageFieldComponent, MetadataValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(ItemPageFieldComponent, {
set: { changeDetection: ChangeDetectionStrategy.Default }
}).compileComponents();
}));
beforeEach(waitForAsync(() => {
markdownSpy = spyOn(MarkdownPipe.prototype, 'transform');
fixture = TestBed.createComponent(ItemPageFieldComponent);
comp = fixture.componentInstance;
comp.item = mockItemWithMetadataFieldAndValue(mockField, mockValue);
comp.fields = mockFields;
comp.label = mockLabel;
fixture.detectChanges();
};
it('should display display the correct metadata value', waitForAsync(async () => {
await buildTestEnvironment();
expect(fixture.nativeElement.innerHTML).toContain(mockValue);
}));
it('should display display the correct metadata value', () => {
expect(fixture.nativeElement.innerHTML).toContain(mockValue);
describe('when markdown is disabled in the environment config', () => {
beforeEach(waitForAsync(async () => {
appConfig.markdown.enabled = false;
await buildTestEnvironment();
}));
describe('and markdown is disabled in this component', () => {
beforeEach(() => {
comp.enableMarkdown = false;
fixture.detectChanges();
});
it('should not use the Markdown Pipe', () => {
expect(markdownSpy).not.toHaveBeenCalled();
});
});
describe('and markdown is enabled in this component', () => {
beforeEach(() => {
comp.enableMarkdown = true;
fixture.detectChanges();
});
it('should not use the Markdown Pipe', () => {
expect(markdownSpy).not.toHaveBeenCalled();
});
});
});
describe('when markdown is enabled in the environment config', () => {
beforeEach(waitForAsync(async () => {
appConfig.markdown.enabled = true;
await buildTestEnvironment();
}));
describe('and markdown is disabled in this component', () => {
beforeEach(() => {
comp.enableMarkdown = false;
fixture.detectChanges();
});
it('should not use the Markdown Pipe', () => {
expect(markdownSpy).not.toHaveBeenCalled();
});
});
describe('and markdown is enabled in this component', () => {
beforeEach(() => {
comp.enableMarkdown = true;
fixture.detectChanges();
});
it('should use the Markdown Pipe', () => {
expect(markdownSpy).toHaveBeenCalled();
});
});
});
});

View File

@@ -1,5 +1,4 @@
import { Component, Input } from '@angular/core';
import { Item } from '../../../../core/shared/item.model';
/**
@@ -18,6 +17,11 @@ export class ItemPageFieldComponent {
*/
@Input() item: Item;
/**
* Whether the {@link MarkdownPipe} should be used to render this metadata.
*/
enableMarkdown = false;
/**
* Fields (schema.element.qualifier) used to render their values.
*/

View File

@@ -5,6 +5,8 @@ import { TranslateLoaderMock } from '../../../../../shared/testing/translate-loa
import { mockItemWithMetadataFieldAndValue } from '../item-page-field.component.spec';
import { ItemPageUriFieldComponent } from './item-page-uri-field.component';
import { MetadataUriValuesComponent } from '../../../../field-components/metadata-uri-values/metadata-uri-values.component';
import { environment } from '../../../../../../environments/environment';
import { APP_CONFIG } from '../../../../../../config/app-config.interface';
let comp: ItemPageUriFieldComponent;
let fixture: ComponentFixture<ItemPageUriFieldComponent>;
@@ -22,6 +24,9 @@ describe('ItemPageUriFieldComponent', () => {
useClass: TranslateLoaderMock
}
})],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
declarations: [ItemPageUriFieldComponent, MetadataUriValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(ItemPageUriFieldComponent, {

View File

@@ -259,9 +259,15 @@ describe('MenuResolver', () => {
expect(menuService.addSection).toHaveBeenCalledWith(MenuID.ADMIN, jasmine.objectContaining({
id: 'import', visible: true,
}));
expect(menuService.addSection).toHaveBeenCalledWith(MenuID.ADMIN, jasmine.objectContaining({
id: 'import_batch', parentID: 'import', visible: true,
}));
expect(menuService.addSection).toHaveBeenCalledWith(MenuID.ADMIN, jasmine.objectContaining({
id: 'export', visible: true,
}));
expect(menuService.addSection).toHaveBeenCalledWith(MenuID.ADMIN, jasmine.objectContaining({
id: 'export_batch', parentID: 'export', visible: true,
}));
});
});

View File

@@ -44,6 +44,9 @@ import {
METADATA_IMPORT_SCRIPT_NAME,
ScriptDataService
} from './core/data/processes/script-data.service';
import {
ExportBatchSelectorComponent
} from './shared/dso-selector/modal-wrappers/export-batch-selector/export-batch-selector.component';
/**
* Creates all of the app's menus
@@ -440,6 +443,20 @@ export class MenuResolver implements Resolve<boolean> {
} as OnClickMenuItemModel,
shouldPersistOnRouteChange: true
});
this.menuService.addSection(MenuID.ADMIN, {
id: 'export_batch',
parentID: 'export',
active: false,
visible: true,
model: {
type: MenuItemType.ONCLICK,
text: 'menu.section.export_batch',
function: () => {
this.modalService.open(ExportBatchSelectorComponent);
}
} as OnClickMenuItemModel,
shouldPersistOnRouteChange: true
});
});
}
@@ -448,20 +465,7 @@ export class MenuResolver implements Resolve<boolean> {
* the import scripts exist and the current user is allowed to execute them
*/
createImportMenuSections() {
const menuList = [
// TODO: enable this menu item once the feature has been implemented
// {
// id: 'import_batch',
// parentID: 'import',
// active: false,
// visible: true,
// model: {
// type: MenuItemType.LINK,
// text: 'menu.section.import_batch',
// link: ''
// } as LinkMenuItemModel,
// }
];
const menuList = [];
menuList.forEach((menuSection) => this.menuService.addSection(MenuID.ADMIN, menuSection));
observableCombineLatest([
@@ -498,6 +502,18 @@ export class MenuResolver implements Resolve<boolean> {
} as LinkMenuItemModel,
shouldPersistOnRouteChange: true
});
this.menuService.addSection(MenuID.ADMIN, {
id: 'import_batch',
parentID: 'import',
active: false,
visible: true,
model: {
type: MenuItemType.LINK,
text: 'menu.section.import_batch',
link: '/admin/batch-import'
} as LinkMenuItemModel,
shouldPersistOnRouteChange: true
});
});
}

View File

@@ -8,15 +8,14 @@ import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { AuthService } from '../../core/auth/auth.service';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { NotificationOptions } from '../../shared/notifications/models/notification-options.model';
import { UploaderOptions } from '../../shared/uploader/uploader-options.model';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
import { NotificationType } from '../../shared/notifications/models/notification-type';
import { hasValue } from '../../shared/empty.util';
import { SearchResult } from '../../shared/search/models/search-result.model';
import { CollectionSelectorComponent } from '../collection-selector/collection-selector.component';
import { UploaderComponent } from '../../shared/uploader/uploader.component';
import { UploaderError } from '../../shared/uploader/uploader-error.model';
import { Router } from '@angular/router';
/**
* This component represents the whole mydspace page header
@@ -56,13 +55,15 @@ export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit {
* @param {NotificationsService} notificationsService
* @param {TranslateService} translate
* @param {NgbModal} modalService
* @param {Router} router
*/
constructor(private authService: AuthService,
private changeDetectorRef: ChangeDetectorRef,
private halService: HALEndpointService,
private notificationsService: NotificationsService,
private translate: TranslateService,
private modalService: NgbModal) {
private modalService: NgbModal,
private router: Router) {
}
/**
@@ -87,16 +88,9 @@ export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit {
this.uploadEnd.emit(workspaceitems);
if (workspaceitems.length === 1) {
const options = new NotificationOptions();
options.timeOut = 0;
const link = '/workspaceitems/' + workspaceitems[0].id + '/edit';
this.notificationsService.notificationWithAnchor(
NotificationType.Success,
options,
link,
'mydspace.general.text-here',
'mydspace.upload.upload-successful',
'here');
// To avoid confusion and ambiguity, redirect the user on the publication page.
this.router.navigateByUrl(link);
} else if (workspaceitems.length > 1) {
this.notificationsService.success(null, this.translate.get('mydspace.upload.upload-multiple-successful', {qty: workspaceitems.length}));
}

View File

@@ -16,6 +16,7 @@ import { WorkflowItemSearchResultListElementComponent } from '../shared/object-l
import { PoolSearchResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/pool-search-result/pool-search-result-detail-element.component';
import { ClaimedApprovedSearchResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/claimed-search-result/claimed-approved-search-result/claimed-approved-search-result-list-element.component';
import { ClaimedDeclinedSearchResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/claimed-search-result/claimed-declined-search-result/claimed-declined-search-result-list-element.component';
import { ResearchEntitiesModule } from '../entity-groups/research-entities/research-entities.module';
const ENTRY_COMPONENTS = [
// put only entry components that use custom decorator
@@ -38,6 +39,7 @@ const ENTRY_COMPONENTS = [
CommonModule,
SharedModule,
MyDspacePageRoutingModule,
ResearchEntitiesModule.withEntryComponents()
],
declarations: [
...ENTRY_COMPONENTS

View File

@@ -4,7 +4,7 @@ nav.navbar {
}
/** Mobile menu styling **/
@media screen and (max-width: map-get($grid-breakpoints, md)) {
@media screen and (max-width: map-get($grid-breakpoints, md)-0.02) {
.navbar {
width: 100vw;
background-color: var(--bs-white);
@@ -26,7 +26,7 @@ nav.navbar {
/* TODO remove when https://github.com/twbs/bootstrap/issues/24726 is fixed */
.navbar-expand-md.navbar-container {
@media screen and (max-width: map-get($grid-breakpoints, md)) {
@media screen and (max-width: map-get($grid-breakpoints, md)-0.02) {
> .container {
padding: 0 var(--bs-spacer);
}

View File

@@ -74,6 +74,19 @@ describe('ProfilePageSecurityFormComponent', () => {
expect(component.passwordValue.emit).toHaveBeenCalledWith('new-password');
}));
it('should emit the value on password change with current password for profile-page', fakeAsync(() => {
spyOn(component.passwordValue, 'emit');
spyOn(component.currentPasswordValue, 'emit');
component.FORM_PREFIX = 'profile.security.form.';
component.ngOnInit();
component.formGroup.patchValue({password: 'new-password'});
component.formGroup.patchValue({'current-password': 'current-password'});
tick(300);
expect(component.passwordValue.emit).toHaveBeenCalledWith('new-password');
expect(component.currentPasswordValue.emit).toHaveBeenCalledWith('current-password');
}));
});
});
});

View File

@@ -27,6 +27,10 @@ export class ProfilePageSecurityFormComponent implements OnInit {
* Emits the value of the password
*/
@Output() passwordValue = new EventEmitter<string>();
/**
* Emits the value of the current-password
*/
@Output() currentPasswordValue = new EventEmitter<string>();
/**
* The form's input models
@@ -70,6 +74,14 @@ export class ProfilePageSecurityFormComponent implements OnInit {
}
ngOnInit(): void {
if (this.FORM_PREFIX === 'profile.security.form.') {
this.formModel.unshift(new DynamicInputModel({
id: 'current-password',
name: 'current-password',
inputType: 'password',
required: true
}));
}
if (this.passwordCanBeEmpty) {
this.formGroup = this.formService.createFormGroup(this.formModel,
{ validators: [this.checkPasswordsEqual] });
@@ -94,6 +106,9 @@ export class ProfilePageSecurityFormComponent implements OnInit {
debounceTime(300),
).subscribe((valueChange) => {
this.passwordValue.emit(valueChange.password);
if (this.FORM_PREFIX === 'profile.security.form.') {
this.currentPasswordValue.emit(valueChange['current-password']);
}
}));
}

View File

@@ -24,6 +24,7 @@
[FORM_PREFIX]="'profile.security.form.'"
(isInvalid)="setInvalid($event)"
(passwordValue)="setPasswordValue($event)"
(currentPasswordValue)="setCurrentPasswordValue($event)"
></ds-profile-page-security-form>
</div>
</div>

View File

@@ -180,7 +180,7 @@ describe('ProfilePageComponent', () => {
beforeEach(() => {
component.setPasswordValue('');
component.setCurrentPasswordValue('current-password');
result = component.updateSecurity();
});
@@ -199,6 +199,7 @@ describe('ProfilePageComponent', () => {
beforeEach(() => {
component.setPasswordValue('test');
component.setInvalid(true);
component.setCurrentPasswordValue('current-password');
result = component.updateSecurity();
});
@@ -215,8 +216,11 @@ describe('ProfilePageComponent', () => {
beforeEach(() => {
component.setPasswordValue('testest');
component.setInvalid(false);
component.setCurrentPasswordValue('current-password');
operations = [{ op: 'add', path: '/password', value: 'testest' }];
operations = [
{ 'op': 'add', 'path': '/password', 'value': { 'new_password': 'testest', 'current_password': 'current-password' } }
];
result = component.updateSecurity();
});
@@ -228,6 +232,28 @@ describe('ProfilePageComponent', () => {
expect(epersonService.patch).toHaveBeenCalledWith(user, operations);
});
});
describe('when password is filled in, and is valid but return 403', () => {
let result;
let operations;
it('should return call epersonService.patch', (done) => {
epersonService.patch.and.returnValue(observableOf(Object.assign(new RestResponse(false, 403, 'Error'))));
component.setPasswordValue('testest');
component.setInvalid(false);
component.setCurrentPasswordValue('current-password');
operations = [
{ 'op': 'add', 'path': '/password', 'value': {'new_password': 'testest', 'current_password': 'current-password' }}
];
result = component.updateSecurity();
epersonService.patch(user, operations).subscribe((response) => {
expect(response.statusCode).toEqual(403);
done();
});
expect(epersonService.patch).toHaveBeenCalledWith(user, operations);
expect(result).toEqual(true);
});
});
});
describe('canChangePassword$', () => {

View File

@@ -67,6 +67,10 @@ export class ProfilePageComponent implements OnInit {
* The password filled in, in the security form
*/
private password: string;
/**
* The current-password filled in, in the security form
*/
private currentPassword: string;
/**
* The authenticated user
@@ -138,15 +142,14 @@ export class ProfilePageComponent implements OnInit {
*/
updateSecurity() {
const passEntered = isNotEmpty(this.password);
if (this.invalidSecurity) {
this.notificationsService.error(this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.general'));
}
if (!this.invalidSecurity && passEntered) {
const operation = {op: 'add', path: '/password', value: this.password} as Operation;
this.epersonService.patch(this.currentUser, [operation]).pipe(
getFirstCompletedRemoteData()
).subscribe((response: RemoteData<EPerson>) => {
const operations = [
{ 'op': 'add', 'path': '/password', 'value': { 'new_password': this.password, 'current_password': this.currentPassword } }
] as Operation[];
this.epersonService.patch(this.currentUser, operations).pipe(getFirstCompletedRemoteData()).subscribe((response: RemoteData<EPerson>) => {
if (response.hasSucceeded) {
this.notificationsService.success(
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'success.title'),
@@ -154,7 +157,8 @@ export class ProfilePageComponent implements OnInit {
);
} else {
this.notificationsService.error(
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.title'), response.errorMessage
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.title'),
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.change-failed')
);
}
});
@@ -170,6 +174,14 @@ export class ProfilePageComponent implements OnInit {
this.password = $event;
}
/**
* Set the current-password value based on the value emitted from the security form
* @param $event
*/
setCurrentPasswordValue($event: string) {
this.currentPassword = $event;
}
/**
* Submit of the security form that triggers the updateProfile method
*/

View File

@@ -41,6 +41,11 @@ export class CreateProfileComponent implements OnInit {
userInfoForm: FormGroup;
activeLangs: LangConfig[];
/**
* Prefix for the notification messages of this security form
*/
NOTIFICATIONS_PREFIX = 'register-page.create-profile.submit.';
constructor(
private translateService: TranslateService,
private ePersonDataService: EPersonDataService,
@@ -161,13 +166,12 @@ export class CreateProfileComponent implements OnInit {
getFirstCompletedRemoteData(),
).subscribe((rd: RemoteData<EPerson>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get('register-page.create-profile.submit.success.head'),
this.translateService.get('register-page.create-profile.submit.success.content'));
this.notificationsService.success(this.translateService.get(this.NOTIFICATIONS_PREFIX + 'success.head'),
this.translateService.get(this.NOTIFICATIONS_PREFIX + 'success.content'));
this.store.dispatch(new AuthenticateAction(this.email, this.password));
this.router.navigate(['/home']);
} else {
this.notificationsService.error(this.translateService.get('register-page.create-profile.submit.error.head'),
this.translateService.get('register-page.create-profile.submit.error.content'));
this.notificationsService.error(this.translateService.get(this.NOTIFICATIONS_PREFIX + 'error.head'), rd.errorMessage);
}
});
}

View File

@@ -9,7 +9,6 @@ import { TranslateLoaderMock } from '../shared/mocks/translate-loader.mock';
import { NativeWindowRef, NativeWindowService } from '../core/services/window.service';
import { MetadataService } from '../core/metadata/metadata.service';
import { MetadataServiceMock } from '../shared/mocks/metadata-service.mock';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
import { AngularticsProviderMock } from '../shared/mocks/angulartics-provider.service.mock';
import { Angulartics2DSpace } from '../statistics/angulartics/dspace-provider';
import { AuthService } from '../core/auth/auth.service';
@@ -50,7 +49,6 @@ describe('RootComponent', () => {
providers: [
{ provide: NativeWindowService, useValue: new NativeWindowRef() },
{ provide: MetadataService, useValue: new MetadataServiceMock() },
{ provide: Angulartics2GoogleAnalytics, useValue: new AngularticsProviderMock() },
{ provide: Angulartics2DSpace, useValue: new AngularticsProviderMock() },
{ provide: AuthService, useValue: new AuthServiceMock() },
{ provide: Router, useValue: new RouterMock() },

View File

@@ -5,7 +5,6 @@ import { Router } from '@angular/router';
import { combineLatest as combineLatestObservable, Observable, of } from 'rxjs';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
import { MetadataService } from '../core/metadata/metadata.service';
import { HostWindowState } from '../shared/search/host-window.reducer';
@@ -51,7 +50,6 @@ export class RootComponent implements OnInit {
private translate: TranslateService,
private store: Store<HostWindowState>,
private metadata: MetadataService,
private angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics,
private angulartics2DSpace: Angulartics2DSpace,
private authService: AuthService,
private router: Router,

View File

@@ -0,0 +1,24 @@
import { ThemedComponent } from '../shared/theme-support/themed.component';
import { SearchNavbarComponent } from './search-navbar.component';
import { Component } from '@angular/core';
@Component({
selector: 'ds-themed-search-navbar',
styleUrls: [],
templateUrl: '../shared/theme-support/themed.component.html',
})
export class ThemedSearchNavbarComponent extends ThemedComponent<SearchNavbarComponent> {
protected getComponentName(): string {
return 'SearchNavbarComponent';
}
protected importThemedComponent(themeName: string): Promise<any> {
return import(`../../themes/${themeName}/app/search-navbar/search-navbar.component`);
}
protected importUnthemedComponent(): Promise<any> {
return import(`./search-navbar.component`);
}
}

View File

@@ -198,11 +198,13 @@ describe('BrowseByComponent', () => {
});
it('should use the base component to render browse entries', () => {
const componentLoaders = fixture.debugElement.queryAll(By.directive(ListableObjectComponentLoaderComponent));
expect(componentLoaders.length).toEqual(browseEntries.length);
componentLoaders.forEach((componentLoader) => {
const browseEntry = componentLoader.query(By.css('ds-browse-entry-list-element'));
expect(browseEntry.componentInstance).toBeInstanceOf(BrowseEntryListElementComponent);
waitForAsync(() => {
const componentLoaders = fixture.debugElement.queryAll(By.directive(ListableObjectComponentLoaderComponent));
expect(componentLoaders.length).toEqual(browseEntries.length);
componentLoaders.forEach((componentLoader) => {
const browseEntry = componentLoader.query(By.css('ds-browse-entry-list-element'));
expect(browseEntry.componentInstance).toBeInstanceOf(BrowseEntryListElementComponent);
});
});
});
});
@@ -215,11 +217,13 @@ describe('BrowseByComponent', () => {
});
it('should use the themed component to render browse entries', () => {
const componentLoaders = fixture.debugElement.queryAll(By.directive(ListableObjectComponentLoaderComponent));
expect(componentLoaders.length).toEqual(browseEntries.length);
componentLoaders.forEach((componentLoader) => {
const browseEntry = componentLoader.query(By.css('ds-browse-entry-list-element'));
expect(browseEntry.componentInstance).toBeInstanceOf(MockThemedBrowseEntryListElementComponent);
waitForAsync(() => {
const componentLoaders = fixture.debugElement.queryAll(By.directive(ListableObjectComponentLoaderComponent));
expect(componentLoaders.length).toEqual(browseEntries.length);
componentLoaders.forEach((componentLoader) => {
const browseEntry = componentLoader.query(By.css('ds-browse-entry-list-element'));
expect(browseEntry.componentInstance).toBeInstanceOf(MockThemedBrowseEntryListElementComponent);
});
});
});
});

View File

@@ -0,0 +1,36 @@
import {Component, Input} from '@angular/core';
import { ThemedComponent } from '../../theme-support/themed.component';
import { ComcolPageHandleComponent } from './comcol-page-handle.component';
/**
* Themed wrapper for BreadcrumbsComponent
*/
@Component({
selector: 'ds-themed-comcol-page-handle',
styleUrls: [],
templateUrl: '../../theme-support/themed.component.html',
})
export class ThemedComcolPageHandleComponent extends ThemedComponent<ComcolPageHandleComponent> {
// Optional title
@Input() title: string;
// The value of "handle"
@Input() content: string;
inAndOutputNames: (keyof ComcolPageHandleComponent & keyof this)[] = ['title', 'content'];
protected getComponentName(): string {
return 'ComcolPageHandleComponent';
}
protected importThemedComponent(themeName: string): Promise<any> {
return import(`../../../../themes/${themeName}/app/shared/comcol/comcol-page-handle/comcol-page-handle.component`);
}
protected importUnthemedComponent(): Promise<any> {
return import(`./comcol-page-handle.component`);
}
}

View File

@@ -2,6 +2,8 @@ import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ComcolPageContentComponent } from './comcol-page-content/comcol-page-content.component';
import { ComcolPageHandleComponent } from './comcol-page-handle/comcol-page-handle.component';
import { ThemedComcolPageHandleComponent} from './comcol-page-handle/themed-comcol-page-handle.component';
import { ComcolPageHeaderComponent } from './comcol-page-header/comcol-page-header.component';
import { ComcolPageLogoComponent } from './comcol-page-logo/comcol-page-logo.component';
import { ComColFormComponent } from './comcol-forms/comcol-form/comcol-form.component';
@@ -26,6 +28,9 @@ const COMPONENTS = [
ComcolPageBrowseByComponent,
ThemedComcolPageBrowseByComponent,
ComcolRoleComponent,
ThemedComcolPageHandleComponent
];
@NgModule({

View File

@@ -10,10 +10,12 @@ import { AuthService } from '../../core/auth/auth.service';
import { CookieService } from '../../core/services/cookie.service';
import { getTestScheduler } from 'jasmine-marbles';
import { MetadataValue } from '../../core/shared/metadata.models';
import {clone, cloneDeep} from 'lodash';
import { clone, cloneDeep } from 'lodash';
import { ConfigurationDataService } from '../../core/data/configuration-data.service';
import {createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$} from '../remote-data.utils';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../remote-data.utils';
import { ConfigurationProperty } from '../../core/shared/configuration-property.model';
import { ANONYMOUS_STORAGE_NAME_KLARO } from './klaro-configuration';
import { TestScheduler } from 'rxjs/testing';
describe('BrowserKlaroService', () => {
const trackingIdProp = 'google.analytics.key';
@@ -29,7 +31,7 @@ describe('BrowserKlaroService', () => {
let configurationDataService: ConfigurationDataService;
const createConfigSuccessSpy = (...values: string[]) => jasmine.createSpyObj('configurationDataService', {
findByPropertyName: createSuccessfulRemoteDataObject$({
... new ConfigurationProperty(),
...new ConfigurationProperty(),
name: trackingIdProp,
values: values,
}),
@@ -42,7 +44,9 @@ describe('BrowserKlaroService', () => {
let findByPropertyName;
beforeEach(() => {
user = new EPerson();
user = Object.assign(new EPerson(), {
uuid: 'test-user'
});
translateService = getMockTranslateService();
ePersonService = jasmine.createSpyObj('ePersonService', {
@@ -104,7 +108,7 @@ describe('BrowserKlaroService', () => {
services: [{
name: appName,
purposes: [purpose]
},{
}, {
name: googleAnalytics,
purposes: [purpose]
}],
@@ -219,6 +223,40 @@ describe('BrowserKlaroService', () => {
});
});
describe('getSavedPreferences', () => {
let scheduler: TestScheduler;
beforeEach(() => {
scheduler = getTestScheduler();
});
describe('when no user is autheticated', () => {
beforeEach(() => {
spyOn(service as any, 'getUser$').and.returnValue(observableOf(undefined));
});
it('should return the cookie consents object', () => {
scheduler.schedule(() => service.getSavedPreferences().subscribe());
scheduler.flush();
expect(cookieService.get).toHaveBeenCalledWith(ANONYMOUS_STORAGE_NAME_KLARO);
});
});
describe('when user is autheticated', () => {
beforeEach(() => {
spyOn(service as any, 'getUser$').and.returnValue(observableOf(user));
});
it('should return the cookie consents object', () => {
scheduler.schedule(() => service.getSavedPreferences().subscribe());
scheduler.flush();
expect(cookieService.get).toHaveBeenCalledWith('klaro-' + user.uuid);
});
});
});
describe('setSettingsForUser when there are changes', () => {
const cookieConsent = { test: 'testt' };
const cookieConsentString = '{test: \'testt\'}';
@@ -271,40 +309,40 @@ describe('BrowserKlaroService', () => {
});
it('should not filter googleAnalytics when servicesToHide are empty', () => {
const filteredConfig = (service as any).filterConfigServices([]);
expect(filteredConfig).toContain(jasmine.objectContaining({name: googleAnalytics}));
expect(filteredConfig).toContain(jasmine.objectContaining({ name: googleAnalytics }));
});
it('should filter services using names passed as servicesToHide', () => {
const filteredConfig = (service as any).filterConfigServices([googleAnalytics]);
expect(filteredConfig).not.toContain(jasmine.objectContaining({name: googleAnalytics}));
expect(filteredConfig).not.toContain(jasmine.objectContaining({ name: googleAnalytics }));
});
it('should have been initialized with googleAnalytics', () => {
service.initialize();
expect(service.klaroConfig.services).toContain(jasmine.objectContaining({name: googleAnalytics}));
expect(service.klaroConfig.services).toContain(jasmine.objectContaining({ name: googleAnalytics }));
});
it('should filter googleAnalytics when empty configuration is retrieved', () => {
configurationDataService.findByPropertyName = jasmine.createSpy().withArgs(GOOGLE_ANALYTICS_KEY).and.returnValue(
createSuccessfulRemoteDataObject$({
... new ConfigurationProperty(),
...new ConfigurationProperty(),
name: googleAnalytics,
values: [],
}));
service.initialize();
expect(service.klaroConfig.services).not.toContain(jasmine.objectContaining({name: googleAnalytics}));
expect(service.klaroConfig.services).not.toContain(jasmine.objectContaining({ name: googleAnalytics }));
});
it('should filter googleAnalytics when an error occurs', () => {
configurationDataService.findByPropertyName = jasmine.createSpy().withArgs(GOOGLE_ANALYTICS_KEY).and.returnValue(
createFailedRemoteDataObject$('Erro while loading GA')
);
service.initialize();
expect(service.klaroConfig.services).not.toContain(jasmine.objectContaining({name: googleAnalytics}));
expect(service.klaroConfig.services).not.toContain(jasmine.objectContaining({ name: googleAnalytics }));
});
it('should filter googleAnalytics when an invalid payload is retrieved', () => {
configurationDataService.findByPropertyName = jasmine.createSpy().withArgs(GOOGLE_ANALYTICS_KEY).and.returnValue(
createSuccessfulRemoteDataObject$(null)
);
service.initialize();
expect(service.klaroConfig.services).not.toContain(jasmine.objectContaining({name: googleAnalytics}));
expect(service.klaroConfig.services).not.toContain(jasmine.objectContaining({ name: googleAnalytics }));
});
});
});

View File

@@ -13,7 +13,7 @@ import { EPersonDataService } from '../../core/eperson/eperson-data.service';
import { cloneDeep, debounce } from 'lodash';
import { ANONYMOUS_STORAGE_NAME_KLARO, klaroConfiguration } from './klaro-configuration';
import { Operation } from 'fast-json-patch';
import { getFirstCompletedRemoteData} from '../../core/shared/operators';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { ConfigurationDataService } from '../../core/data/configuration-data.service';
/**
@@ -121,6 +121,23 @@ export class BrowserKlaroService extends KlaroService {
});
}
/**
* Return saved preferences stored in the klaro cookie
*/
getSavedPreferences(): Observable<any> {
return this.getUser$().pipe(
map((user: EPerson) => {
let storageName;
if (isEmpty(user)) {
storageName = ANONYMOUS_STORAGE_NAME_KLARO;
} else {
storageName = this.getStorageName(user.uuid);
}
return this.cookieService.get(storageName);
})
);
}
/**
* Initialize configuration for the logged in user
* @param user The authenticated user

View File

@@ -12,6 +12,8 @@ export const HAS_AGREED_END_USER = 'dsHasAgreedEndUser';
*/
export const ANONYMOUS_STORAGE_NAME_KLARO = 'klaro-anonymous';
export const GOOGLE_ANALYTICS_KLARO_KEY = 'google-analytics';
/**
* Klaro configuration
* For more information see https://kiprotect.com/docs/klaro/annotated-config
@@ -113,7 +115,7 @@ export const klaroConfiguration: any = {
]
},
{
name: 'google-analytics',
name: GOOGLE_ANALYTICS_KLARO_KEY,
purposes: ['statistical'],
required: false,
cookies: [

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