resolved merge conflicts

This commit is contained in:
William Welling
2017-09-29 10:05:49 -05:00
75 changed files with 1836 additions and 1316 deletions

View File

@@ -87,7 +87,7 @@
"@ngx-translate/core": "8.0.0",
"@ngx-translate/http-loader": "2.0.0",
"body-parser": "1.18.2",
"bootstrap": "4.0.0-alpha.6",
"bootstrap": "v4.0.0-beta",
"cerialize": "0.1.16",
"compression": "1.7.1",
"cookie-parser": "1.4.3",

View File

@@ -69,5 +69,14 @@
"head": "Communities in DSpace",
"help": "Select a community to browse its collections."
}
},
"search": {
"form": {
"search": "Search",
"search_dspace": "Search DSpace"
},
"results": {
"title": "Search Results"
}
}
}

View File

@@ -32,13 +32,9 @@
</ds-comcol-page-content>
</div>
<br>
<div *ngIf="itemData.hasSucceeded | async">
<div *ngIf="(itemData.hasSucceeded | async)">
<h2>{{'collection.page.browse.recent.head' | translate}}</h2>
<ds-object-list [config]="config" [sortConfig]="sortConfig"
[objects]="itemData" [hideGear]="true"
(pageChange)="onPageChange($event)"
(pageSizeChange)="onPageSizeChange($event)"
(sortDirectionChange)="onSortDirectionChange($event)"
(sortFieldChange)="onSortDirectionChange($event)"></ds-object-list>
<ds-object-list [config]="paginationConfig" [sortConfig]="sortConfig"
[objects]="itemData" [hideGear]="false"></ds-object-list>
</div>
</div>

View File

@@ -14,90 +14,81 @@ import { ItemDataService } from '../core/data/item-data.service';
import { Item } from '../core/shared/item.model';
import { SortOptions, SortDirection } from '../core/cache/models/sort-options.model';
import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model';
import { hasValue, isUndefined } from '../shared/empty.util';
import { hasValue, isNotEmpty, isUndefined } from '../shared/empty.util';
import { PageInfo } from '../core/shared/page-info.model';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'ds-collection-page',
styleUrls: ['./collection-page.component.scss'],
templateUrl: './collection-page.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CollectionPageComponent implements OnInit, OnDestroy {
collectionData: RemoteData<Collection>;
itemData: RemoteData<Item[]>;
logoData: RemoteData<Bitstream>;
config: PaginationComponentOptions;
paginationConfig: PaginationComponentOptions;
sortConfig: SortOptions;
private subs: Subscription[] = [];
private collectionId: string;
private pageInfoState: PageInfo;
constructor(
private collectionDataService: CollectionDataService,
constructor(private collectionDataService: CollectionDataService,
private itemDataService: ItemDataService,
private ref: ChangeDetectorRef,
private route: ActivatedRoute
) {
private route: ActivatedRoute) {
this.paginationConfig = new PaginationComponentOptions();
this.paginationConfig.id = 'collection-page-pagination';
this.paginationConfig.pageSizeOptions = [4];
this.paginationConfig.pageSize = 4;
this.paginationConfig.currentPage = 1;
this.sortConfig = new SortOptions();
}
ngOnInit(): void {
this.subs.push(this.route.params.map((params: Params) => params.id)
.subscribe((id: string) => {
this.collectionId = id;
this.subs.push(
Observable.combineLatest(
this.route.params,
this.route.queryParams,
(params, queryParams,) => {
return Object.assign({}, params, queryParams);
})
.subscribe((params) => {
this.collectionId = params.id;
this.collectionData = this.collectionDataService.findById(this.collectionId);
this.subs.push(this.collectionData.payload.subscribe((collection) => this.logoData = collection.logo));
this.config = new PaginationComponentOptions();
this.config.id = 'collection-browse';
this.config.pageSizeOptions = [4];
this.config.pageSize = 4;
this.sortConfig = new SortOptions();
this.updateResults();
const page = +params.page || this.paginationConfig.currentPage;
const pageSize = +params.pageSize || this.paginationConfig.pageSize;
const sortDirection = +params.page || this.sortConfig.direction;
const pagination = Object.assign({},
this.paginationConfig,
{ currentPage: page, pageSize: pageSize }
);
const sort = Object.assign({},
this.sortConfig,
{ direction: sortDirection, field: params.sortField }
);
this.updatePage({
pagination: pagination,
sort: sort
});
}));
}
updatePage(searchOptions) {
this.itemData = this.itemDataService.findAll({
scopeID: this.collectionId,
currentPage: searchOptions.pagination.currentPage,
elementsPerPage: searchOptions.pagination.pageSize,
sort: searchOptions.sort
});
}
ngOnDestroy(): void {
this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe());
}
onPageChange(currentPage: number): void {
this.config.currentPage = currentPage;
this.updateResults();
}
onPageSizeChange(elementsPerPage: number): void {
this.config.pageSize = elementsPerPage;
this.updateResults();
}
onSortDirectionChange(sortDirection: SortDirection): void {
this.sortConfig = new SortOptions(this.sortConfig.field, sortDirection);
this.updateResults();
}
onSortFieldChange(field: string): void {
this.sortConfig = new SortOptions(field, this.sortConfig.direction);
this.updateResults();
}
updateResults() {
this.itemData = null;
this.ref.markForCheck();
this.itemData = this.itemDataService.findAll({
scopeID: this.collectionId,
currentPage: this.config.currentPage,
elementsPerPage: this.config.pageSize,
sort: this.sortConfig
});
this.subs.push(this.itemData.pageInfo.subscribe((pageInfo) => {
if (isUndefined(this.pageInfoState) || this.pageInfoState !== pageInfo) {
this.pageInfoState = pageInfo;
this.ref.detectChanges();
}
}));
isNotEmpty(object: any) {
return isNotEmpty(object);
}
}

View File

@@ -1,7 +1,10 @@
@import '../../../styles/mixins.scss';
@import '../../../styles/variables.scss';
:host {
display: block;
@include negate-gutters();
margin-right: ($grid-gutter-width / -2);
margin-left: ($grid-gutter-width / -2);
margin-top: -$content-spacing;
margin-bottom: -$content-spacing;
}
.dspace-logo-container {

View File

@@ -1,2 +1,3 @@
<ds-home-news></ds-home-news>
<ds-search-form></ds-search-form>
<ds-top-level-community-list></ds-top-level-community-list>

View File

@@ -2,9 +2,5 @@
<h2>{{'home.top-level-communities.head' | translate}}</h2>
<p class="lead">{{'home.top-level-communities.help' | translate}}</p>
<ds-object-list [config]="config" [sortConfig]="sortConfig"
[objects]="topLevelCommunities" [hideGear]="true"
(pageChange)="onPageChange($event)"
(pageSizeChange)="onPageSizeChange($event)"
(sortDirectionChange)="onSortDirectionChange($event)"
(sortFieldChange)="onSortDirectionChange($event)"></ds-object-list>
[objects]="topLevelCommunities" [hideGear]="true" (paginationChange)="updatePage($event)"></ds-object-list>
</div>

View File

@@ -5,58 +5,40 @@ import { CommunityDataService } from '../../core/data/community-data.service';
import { Community } from '../../core/shared/community.model';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortOptions, SortDirection } from '../../core/cache/models/sort-options.model';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'ds-top-level-community-list',
styleUrls: ['./top-level-community-list.component.scss'],
templateUrl: './top-level-community-list.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TopLevelCommunityListComponent implements OnInit {
export class TopLevelCommunityListComponent {
topLevelCommunities: RemoteData<Community[]>;
config: PaginationComponentOptions;
sortConfig: SortOptions;
constructor(
private cds: CommunityDataService,
private ref: ChangeDetectorRef
) {
}
ngOnInit(): void {
constructor(private cds: CommunityDataService) {
this.config = new PaginationComponentOptions();
this.config.id = 'top-level-pagination';
this.config.pageSizeOptions = [4];
this.config.pageSize = 4;
this.config.currentPage = 1;
this.sortConfig = new SortOptions();
this.updateResults();
this.updatePage({
page: this.config.currentPage,
pageSize: this.config.pageSize,
sortField: this.sortConfig.field,
direction: this.sortConfig.direction
});
}
onPageChange(currentPage: number): void {
this.config.currentPage = currentPage;
this.updateResults();
}
onPageSizeChange(elementsPerPage: number): void {
this.config.pageSize = elementsPerPage;
this.updateResults();
}
onSortDirectionChange(sortDirection: SortDirection): void {
this.sortConfig = new SortOptions(this.sortConfig.field, sortDirection);
this.updateResults();
}
onSortFieldChange(field: string): void {
this.sortConfig = new SortOptions(field, this.sortConfig.direction);
this.updateResults();
}
updateResults() {
this.topLevelCommunities = undefined;
this.topLevelCommunities = this.cds.findAll({ currentPage: this.config.currentPage, elementsPerPage: this.config.pageSize, sort: this.sortConfig });
// this.ref.detectChanges();
updatePage(data) {
this.topLevelCommunities = this.cds.findAll({
currentPage: data.page,
elementsPerPage: data.pageSize,
sort: { field: data.sortField, direction: data.sortDirection }
});
}
}

View File

@@ -1,5 +1,5 @@
@import '../../../../../styles/variables.scss';
@import '../../../../../../node_modules/bootstrap/scss/_variables.scss';
@import '../../../../../styles/variables';
@import '../../../../../styles/mixins';
@media screen and (min-width: map-get($grid-breakpoints, md)) {
dt {
text-align: right;

View File

@@ -2,7 +2,7 @@
<ds-item-page-title-field [item]="item.payload | async"></ds-item-page-title-field>
<div class="simple-view-link">
<a class="btn btn-secondary col-4" [routerLink]="['/items/' + (item.payload | async)?.id]">
<a class="btn btn-outline-primary col-4" [routerLink]="['/items/' + (item.payload | async)?.id]">
{{"item.page.link.simple" | translate}}
</a>
</div>

View File

@@ -16,7 +16,7 @@
<ds-item-page-uri-field [item]="item.payload | async"></ds-item-page-uri-field>
<ds-item-page-collections [item]="item.payload | async"></ds-item-page-collections>
<div>
<a class="btn btn-secondary" [routerLink]="['/items/' + (item.payload | async)?.id + '/full']">
<a class="btn btn-outline-primary" [routerLink]="['/items/' + (item.payload | async)?.id + '/full']">
{{"item.page.link.full" | translate}}
</a>
</div>

View File

@@ -23,4 +23,6 @@ html {
.main-content {
flex: 1 0 auto;
margin-top: $content-spacing;
margin-bottom: $content-spacing;
}

View File

@@ -14,6 +14,7 @@ import { GenericConstructor } from '../../shared/generic-constructor';
import { getMapsTo, getRelationMetadata, getRelationships } from './build-decorators';
import { NormalizedObjectFactory } from '../models/normalized-object-factory';
import { Request } from '../../data/request.models';
import { PageInfo } from '../../shared/page-info.model';
@Injectable()
export class RemoteDataBuildService {
@@ -21,13 +22,12 @@ export class RemoteDataBuildService {
protected objectCache: ObjectCacheService,
protected responseCache: ResponseCacheService,
protected requestService: RequestService
) {
}
buildSingle<TNormalized extends CacheableObject, TDomain>(
href: string,
normalizedType: GenericConstructor<TNormalized>
): RemoteData<TDomain> {
buildSingle<TNormalized extends CacheableObject, TDomain>(href: string,
normalizedType: GenericConstructor<TNormalized>): RemoteData<TDomain> {
const requestHrefObs = this.objectCache.getRequestHrefBySelfLink(href);
const requestObs = Observable.race(
@@ -61,6 +61,13 @@ export class RemoteDataBuildService {
const pageInfo = responseCacheObs
.filter((entry: ResponseCacheEntry) => hasValue(entry.response) && hasValue(entry.response['pageInfo']))
.map((entry: ResponseCacheEntry) => (entry.response as SuccessResponse).pageInfo)
.map((pInfo: PageInfo) => {
if (isNotEmpty(pageInfo) && pInfo.currentPage >= 0) {
return Object.assign({}, pInfo, {currentPage: pInfo.currentPage + 1});
} else {
return pInfo;
}
})
.distinctUntilChanged();
/* tslint:enable:no-string-literal */
@@ -104,10 +111,8 @@ export class RemoteDataBuildService {
);
}
buildList<TNormalized extends CacheableObject, TDomain>(
href: string,
normalizedType: GenericConstructor<TNormalized>
): RemoteData<TDomain[]> {
buildList<TNormalized extends CacheableObject, TDomain>(href: string,
normalizedType: GenericConstructor<TNormalized>): RemoteData<TDomain[]> {
const requestObs = this.requestService.get(href)
.filter((entry) => hasValue(entry));
const responseCacheObs = this.responseCache.get(href).filter((entry) => hasValue(entry));

View File

@@ -3,11 +3,12 @@ import { isEmpty, isNotEmpty } from '../../shared/empty.util';
import { CacheableObject } from '../cache/object-cache.reducer';
import { RemoteData } from '../data/remote-data';
import { ResourceType } from './resource-type';
import { ListableObject } from '../../object-list/listable-object/listable-object.model';
/**
* An abstract model class for a DSpaceObject.
*/
export abstract class DSpaceObject implements CacheableObject {
export abstract class DSpaceObject implements CacheableObject, ListableObject {
self: string;

View File

@@ -1,6 +1,5 @@
@import '../../styles/variables.scss';
@import '../../../node_modules/bootstrap/scss/_variables.scss';
$footer-bg: $gray-lighter;
$footer-bg: $gray-100;
$footer-border: 1px solid darken($footer-bg, 10%);
$footer-padding: $spacer * 1.5;

View File

@@ -1,11 +1,11 @@
<header>
<nav class="navbar navbar-toggleable-sm navbar-inverse bg-inverse">
<button class="navbar-toggler navbar-toggler-right" type="button" (click)="toggle()" aria-controls="collapsingNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon fa fa-bars fa-fw" aria-hidden="true"></span>
</button>
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<div [ngClass]="{'clearfix': !(isNavBarCollapsed | async)}">
<a class="navbar-brand" routerLink="/home">{{ 'title' | translate }}</a>
</div>
<button class="navbar-toggler" type="button" (click)="toggle()" aria-controls="collapsingNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon fa fa-bars fa-fw" aria-hidden="true"></span>
</button>
<div [ngbCollapse]="(isNavBarCollapsed | async)" class="collapse navbar-collapse" id="collapsingNav">
<ul class="navbar-nav mr-auto">
<li class="nav-item">

View File

@@ -1,6 +1,6 @@
<a [routerLink]="['/collections/' + collection.id]" class="lead">
{{collection.name}}
<a [routerLink]="['/collections/' + object.id]" class="lead">
{{object.name}}
</a>
<div *ngIf="collection.shortDescription" class="text-muted">
{{collection.shortDescription}}
<div *ngIf="object.shortDescription" class="text-muted">
{{object.shortDescription}}
</div>

View File

@@ -1,16 +1,14 @@
import { Component, Input } from '@angular/core';
import { Component, Inject } from '@angular/core';
import { Collection } from '../../core/shared/collection.model';
import { ObjectListElementComponent } from '../object-list-element/object-list-element.component';
import { listElementFor } from '../list-element-decorator';
@Component({
selector: 'ds-collection-list-element',
styleUrls: ['./collection-list-element.component.scss'],
templateUrl: './collection-list-element.component.html'
})
export class CollectionListElementComponent {
@Input() collection: Collection;
data: any = {};
}
@listElementFor(Collection)
export class CollectionListElementComponent extends ObjectListElementComponent<Collection> {}

View File

@@ -1,6 +1,6 @@
<a [routerLink]="['/communities/' + community.id]" class="lead">
{{community.name}}
<a [routerLink]="['/communities/' + object.id]" class="lead">
{{object.name}}
</a>
<div *ngIf="community.shortDescription" class="text-muted">
{{community.shortDescription}}
<div *ngIf="object.shortDescription" class="text-muted">
{{object.shortDescription}}
</div>

View File

@@ -1,16 +1,14 @@
import { Component, Input } from '@angular/core';
import { Component, Input, Inject } from '@angular/core';
import { Community } from '../../core/shared/community.model';
import { ObjectListElementComponent } from '../object-list-element/object-list-element.component';
import { listElementFor } from '../list-element-decorator';
@Component({
selector: 'ds-community-list-element',
styleUrls: ['./community-list-element.component.scss'],
templateUrl: './community-list-element.component.html'
})
export class CommunityListElementComponent {
@Input() community: Community;
data: any = {};
}
@listElementFor(Community)
export class CommunityListElementComponent extends ObjectListElementComponent<Community> {}

View File

@@ -1,14 +1,14 @@
<a [routerLink]="['/items/' + item.id]" class="lead">
{{item.findMetadata("dc.title")}}
<a [routerLink]="['/items/' + object.id]" class="lead">
{{object.findMetadata("dc.title")}}
</a>
<div>
<span class="text-muted">
<span *ngIf="item.filterMetadata(['dc.contributor.author', 'dc.creator', 'dc.contributor.*']);" class="item-list-authors">
<span *ngFor="let authorMd of item.filterMetadata(['dc.contributor.author', 'dc.creator', 'dc.contributor.*']); let last=last;">{{authorMd.value}}
<span *ngIf="object.filterMetadata(['dc.contributor.author', 'dc.creator', 'dc.contributor.*']);" class="item-list-authors">
<span *ngFor="let authorMd of object.filterMetadata(['dc.contributor.author', 'dc.creator', 'dc.contributor.*']); let last=last;">{{authorMd.value}}
<span *ngIf="!last">; </span>
</span>
</span>
(<span *ngIf="item.findMetadata('dc.publisher')" class="item-list-publisher">{{item.findMetadata("dc.publisher")}}, </span><span *ngIf="item.findMetadata('dc.date.issued')" class="item-list-date">{{item.findMetadata("dc.date.issued")}}</span>)
(<span *ngIf="object.findMetadata('dc.publisher')" class="item-list-publisher">{{object.findMetadata("dc.publisher")}}, </span><span *ngIf="object.findMetadata('dc.date.issued')" class="item-list-date">{{object.findMetadata("dc.date.issued")}}</span>)
</span>
<div *ngIf="item.findMetadata('dc.description.abstract')" class="item-list-abstract">{{item.findMetadata("dc.description.abstract") | dsTruncate:[200] }}</div>
<div *ngIf="object.findMetadata('dc.description.abstract')" class="item-list-abstract">{{object.findMetadata("dc.description.abstract") | dsTruncate:[200] }}</div>
</div>

View File

@@ -1,15 +1,14 @@
import { Component, Input } from '@angular/core';
import { Component, Input, Inject } from '@angular/core';
import { Item } from '../../core/shared/item.model';
import { ObjectListElementComponent } from '../object-list-element/object-list-element.component';
import { listElementFor } from '../list-element-decorator';
@Component({
selector: 'ds-item-list-element',
styleUrls: ['./item-list-element.component.scss'],
templateUrl: './item-list-element.component.html'
})
export class ItemListElementComponent {
@Input() item: Item;
data: any = {};
}
@listElementFor(Item)
export class ItemListElementComponent extends ObjectListElementComponent<Item> {}

View File

@@ -0,0 +1,16 @@
import { ListableObject } from './listable-object/listable-object.model';
import { GenericConstructor } from '../core/shared/generic-constructor';
const listElementMap = new Map();
export function listElementFor(listable: GenericConstructor<ListableObject>) {
return function decorator(objectElement: any) {
if (!objectElement) {
return;
}
listElementMap.set(listable, objectElement);
};
}
export function getListElementFor(listable: GenericConstructor<ListableObject>) {
return listElementMap.get(listable);
}

View File

@@ -0,0 +1 @@
export interface ListableObject {}

View File

@@ -1,5 +0,0 @@
<div [ngSwitch]="object.type">
<ds-item-list-element *ngSwitchCase="type.Item" [item]="object"></ds-item-list-element>
<ds-collection-list-element *ngSwitchCase="type.Collection" [collection]="object"></ds-collection-list-element>
<ds-community-list-element *ngSwitchCase="type.Community" [community]="object"></ds-community-list-element>
</div>

View File

@@ -1,7 +1,6 @@
@import '../../../styles/variables.scss';
@import '../../../../node_modules/bootstrap/scss/variables';
:host {
display: block;
margin-bottom: $spacer-y;
margin-bottom: $spacer;
}

View File

@@ -1,18 +1,14 @@
import { Component, Input, OnInit } from '@angular/core';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { ResourceType } from '../../core/shared/resource-type';
import { Component, Inject } from '@angular/core';
import { ListableObject } from '../listable-object/listable-object.model';
@Component({
selector: 'ds-object-list-element',
styleUrls: ['./object-list-element.component.scss'],
templateUrl: './object-list-element.component.html'
})
export class ObjectListElementComponent {
public type = ResourceType;
@Input() object: DSpaceObject;
data: any = {};
export class ObjectListElementComponent <T extends ListableObject> {
object: T;
public constructor(@Inject('objectElementProvider') public listable: ListableObject) {
this.object = listable as T;
}
}

View File

@@ -7,10 +7,11 @@
(pageChange)="onPageChange($event)"
(pageSizeChange)="onPageSizeChange($event)"
(sortDirectionChange)="onSortDirectionChange($event)"
(sortFieldChange)="onSortDirectionChange($event)">
(sortFieldChange)="onSortDirectionChange($event)"
(paginationChange)="onPaginationChange($event)">
<ul *ngIf="objects.hasSucceeded | async"> <!--class="list-unstyled"-->
<li *ngFor="let object of (objects.payload | async) | paginate: { itemsPerPage: (pageInfo | async)?.elementsPerPage, currentPage: (pageInfo | async)?.currentPage, totalItems: (pageInfo | async)?.totalElements }">
<ds-object-list-element [object]="object"></ds-object-list-element>
<ds-wrapper-list-element [object]="object"></ds-wrapper-list-element>
</li>
</ul>

View File

@@ -0,0 +1,2 @@
<a [routerLink]="['/collections/' + dso.id]" class="lead" [innerHTML]="getFirstValue('dc.title')"></a>
<div *ngIf="dso.shortDescription" class="text-muted" [innerHTML]="getFirstValue('dc.description.abstract')"></div>

View File

@@ -0,0 +1 @@
@import '../../../../styles/variables.scss';

View File

@@ -0,0 +1,15 @@
import { Component } from '@angular/core';
import { listElementFor } from '../../list-element-decorator';
import { CollectionSearchResult } from './collection-search-result.model';
import { SearchResultListElementComponent } from '../search-result-list-element.component';
import { Collection } from '../../../core/shared/collection.model';
@Component({
selector: 'ds-collection-search-result-list-element',
styleUrls: ['../search-result-list-element.component.scss', 'collection-search-result-list-element.component.scss'],
templateUrl: 'collection-search-result-list-element.component.html'
})
@listElementFor(CollectionSearchResult)
export class CollectionSearchResultListElementComponent extends SearchResultListElementComponent<CollectionSearchResult, Collection> {}

View File

@@ -0,0 +1,5 @@
import { SearchResult } from '../../../search/search-result.model';
import { Collection } from '../../../core/shared/collection.model';
export class CollectionSearchResult extends SearchResult<Collection> {
}

View File

@@ -0,0 +1,2 @@
<a [routerLink]="['/communities/' + dso.id]" class="lead" [innerHTML]="getFirstValue('dc.title')"></a>
<div *ngIf="dso.shortDescription" class="text-muted" [innerHTML]="getFirstValue('dc.description.abstract')"></div>

View File

@@ -0,0 +1 @@
@import '../../../../styles/variables.scss';

View File

@@ -0,0 +1,17 @@
import { Component } from '@angular/core';
import { listElementFor } from '../../list-element-decorator';
import { CommunitySearchResult } from './community-search-result.model';
import { SearchResultListElementComponent } from '../search-result-list-element.component';
import { Community } from '../../../core/shared/community.model';
@Component({
selector: 'ds-community-search-result-list-element',
styleUrls: ['../search-result-list-element.component.scss', 'community-search-result-list-element.component.scss'],
templateUrl: 'community-search-result-list-element.component.html'
})
@listElementFor(CommunitySearchResult)
export class CommunitySearchResultListElementComponent extends SearchResultListElementComponent<CommunitySearchResult, Community> {
}

View File

@@ -0,0 +1,5 @@
import { SearchResult } from '../../../search/search-result.model';
import { Community } from '../../../core/shared/community.model';
export class CommunitySearchResult extends SearchResult<Community> {
}

View File

@@ -0,0 +1,12 @@
<a [routerLink]="['/items/' + dso.id]" class="lead" [innerHTML]="getFirstValue('dc.title')"></a>
<div>
<span class="text-muted">
<span *ngIf="dso.filterMetadata(['dc.contributor.author', 'dc.creator', 'dc.contributor.*']);" class="item-list-authors">
<span *ngFor="let author of getValues(['dc.contributor.author', 'dc.creator', 'dc.contributor.*']); let last=last;">
<span [innerHTML]="author"><span [innerHTML]="author"></span></span>
</span>
</span>
(<span *ngIf="dso.findMetadata('dc.publisher')" class="item-list-publisher" [innerHTML]="getFirstValue('dc.publisher')">, </span><span *ngIf="dso.findMetadata('dc.date.issued')" class="item-list-date" [innerHTML]="getFirstValue('dc.date.issued')"></span>)
</span>
<div *ngIf="dso.findMetadata('dc.description.abstract')" class="item-list-abstract" [innerHTML]="getFirstValue('dc.description.abstract') | dsTruncate:[200]"></div>
</div>

View File

@@ -0,0 +1 @@
@import '../../../../styles/variables.scss';

View File

@@ -0,0 +1,15 @@
import { Component } from '@angular/core';
import { listElementFor } from '../../list-element-decorator';
import { ItemSearchResult } from './item-search-result.model';
import { SearchResultListElementComponent } from '../search-result-list-element.component';
import { Item } from '../../../core/shared/item.model';
@Component({
selector: 'ds-item-search-result-list-element',
styleUrls: ['../search-result-list-element.component.scss', 'item-search-result-list-element.component.scss'],
templateUrl: 'item-search-result-list-element.component.html'
})
@listElementFor(ItemSearchResult)
export class ItemSearchResultListElementComponent extends SearchResultListElementComponent<ItemSearchResult, Item> {}

View File

@@ -0,0 +1,5 @@
import { SearchResult } from '../../../search/search-result.model';
import { Item } from '../../../core/shared/item.model';
export class ItemSearchResult extends SearchResult<Item> {
}

View File

@@ -0,0 +1,7 @@
@import '../../../styles/variables.scss';
:host {
/deep/ em {
font-weight: bold;
font-style: normal;
}
}

View File

@@ -0,0 +1,57 @@
import { Component, Inject } from '@angular/core';
import { ObjectListElementComponent } from '../object-list-element/object-list-element.component';
import { ListableObject } from '../listable-object/listable-object.model';
import { SearchResult } from '../../search/search-result.model';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { Metadatum } from '../../core/shared/metadatum.model';
import { isEmpty, hasNoValue } from '../../shared/empty.util';
@Component({
selector: 'ds-search-result-list-element',
template: ``
})
export class SearchResultListElementComponent<T extends SearchResult<K>, K extends DSpaceObject> extends ObjectListElementComponent<T> {
dso: K;
public constructor(@Inject('objectElementProvider') public listable: ListableObject) {
super(listable);
this.dso = this.object.dspaceObject;
}
getValues(keys: string[]): string[] {
const results: string[] = new Array<string>();
this.object.hitHighlights.forEach(
(md: Metadatum) => {
if (keys.indexOf(md.key) > -1) {
results.push(md.value);
}
}
);
if (isEmpty(results)) {
this.dso.filterMetadata(keys).forEach(
(md: Metadatum) => {
results.push(md.value);
}
);
}
return results;
}
getFirstValue(key: string): string {
let result: string;
this.object.hitHighlights.some(
(md: Metadatum) => {
if (key === md.key) {
result = md.value;
return true;
}
}
);
if (hasNoValue(result)) {
result = this.dso.findMetadata(key);
}
return result;
}
}

View File

@@ -0,0 +1 @@
<ng-container *ngComponentOutlet="getListElement(); injector: objectInjector;"></ng-container>

View File

@@ -0,0 +1,2 @@
@import '../../../styles/variables.scss';

View File

@@ -0,0 +1,27 @@
import { Component, Input, Injector, ReflectiveInjector, OnInit } from '@angular/core';
import { ListableObject } from '../listable-object/listable-object.model';
import { getListElementFor } from '../list-element-decorator'
import { GenericConstructor } from '../../core/shared/generic-constructor';
@Component({
selector: 'ds-wrapper-list-element',
styleUrls: ['./wrapper-list-element.component.scss'],
templateUrl: './wrapper-list-element.component.html'
})
export class WrapperListElementComponent implements OnInit {
@Input() object: ListableObject;
objectInjector: Injector;
constructor(private injector: Injector) {}
ngOnInit(): void {
this.objectInjector = ReflectiveInjector.resolveAndCreate(
[{provide: 'objectElementProvider', useFactory: () => (this.object) }], this.injector);
}
getListElement(): string {
const f: GenericConstructor<ListableObject> = this.object.constructor as GenericConstructor<ListableObject>;
return getListElementFor(f);
}
}

View File

@@ -0,0 +1,13 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SearchPageComponent } from './search-page.component';
@NgModule({
imports: [
RouterModule.forChild([
{ path: 'search', component: SearchPageComponent }
])
]
})
export class SearchPageRoutingModule { }

View File

@@ -0,0 +1,4 @@
<div class="search-page">
<ds-search-form [query]="query" [scope]="scopeObject?.payload | async" [currentParams]="currentParams" [scopes]="scopeList?.payload"></ds-search-form>
<ds-search-results [searchResults]="results" [searchConfig]="searchOptions"></ds-search-results>
</div>

View File

@@ -0,0 +1 @@
@import '../../styles/variables.scss';

View File

@@ -0,0 +1,89 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import { SearchService } from '../search/search.service';
import { ActivatedRoute, Router } from '@angular/router';
import { RemoteData } from '../core/data/remote-data';
import { SearchResult } from '../search/search-result.model';
import { DSpaceObject } from '../core/shared/dspace-object.model';
import { SortOptions } from '../core/cache/models/sort-options.model';
import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model';
import { SearchOptions } from '../search/search-options.model';
import { CommunityDataService } from '../core/data/community-data.service';
import { isNotEmpty } from '../shared/empty.util';
import { Community } from '../core/shared/community.model';
/**
* This component renders a simple item page.
* The route parameter 'id' is used to request the item it represents.
* All fields of the item that should be displayed, are defined in its template.
*/
@Component({
selector: 'ds-search-page',
styleUrls: ['./search-page.component.scss'],
templateUrl: './search-page.component.html',
})
export class SearchPageComponent implements OnInit, OnDestroy {
private sub;
query: string;
private scope: string;
scopeObject: RemoteData<DSpaceObject>;
results: RemoteData<Array<SearchResult<DSpaceObject>>>;
currentParams = {};
searchOptions: SearchOptions;
scopeList: RemoteData<Community[]>;
constructor(private service: SearchService,
private route: ActivatedRoute,
private communityService: CommunityDataService,) {
this.scopeList = communityService.findAll();
// Initial pagination config
const pagination: PaginationComponentOptions = new PaginationComponentOptions();
pagination.id = 'search-results-pagination';
pagination.currentPage = 1;
pagination.pageSize = 10;
const sort: SortOptions = new SortOptions();
this.searchOptions = { pagination: pagination, sort: sort };
}
ngOnInit(): void {
this.sub = this.route
.queryParams
.subscribe((params) => {
// Save current parameters
this.currentParams = params;
this.query = params.query || '';
this.scope = params.scope;
const page = +params.page || this.searchOptions.pagination.currentPage;
const pageSize = +params.pageSize || this.searchOptions.pagination.pageSize;
const sortDirection = +params.sortDirection || this.searchOptions.sort.direction;
const pagination = Object.assign({},
this.searchOptions.pagination,
{ currentPage: page, pageSize: pageSize }
);
const sort = Object.assign({},
this.searchOptions.sort,
{ direction: sortDirection, field: params.sortField }
);
this.updateSearchResults({
pagination: pagination,
sort: sort
});
if (isNotEmpty(this.scope)) {
this.scopeObject = this.communityService.findById(this.scope);
} else {
this.scopeObject = undefined;
}
}
);
}
private updateSearchResults(searchOptions) {
// Resolve search results
this.results = this.service.search(this.query, this.scope, searchOptions);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}

View File

@@ -0,0 +1,38 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { SharedModule } from '../shared/shared.module';
import { SearchPageRoutingModule } from './search-page-routing.module';
import { SearchPageComponent } from './search-page.component';
import { SearchResultsComponent } from './search-results/search-results.compontent';
import { SearchModule } from '../search/search.module';
import { ItemSearchResultListElementComponent } from '../object-list/search-result-list-element/item-search-result/item-search-result-list-element.component';
import { CollectionSearchResultListElementComponent } from '../object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component';
import { CommunitySearchResultListElementComponent } from '../object-list/search-result-list-element/community-search-result/community-search-result-list-element.component';
@NgModule({
imports: [
SearchPageRoutingModule,
CommonModule,
TranslateModule,
RouterModule,
SharedModule,
SearchModule
],
declarations: [
SearchPageComponent,
SearchResultsComponent,
ItemSearchResultListElementComponent,
CollectionSearchResultListElementComponent,
CommunitySearchResultListElementComponent
],
entryComponents: [
ItemSearchResultListElementComponent,
CollectionSearchResultListElementComponent,
CommunitySearchResultListElementComponent
]
})
export class SearchPageModule { }

View File

@@ -0,0 +1,3 @@
<h2 *ngIf="(searchResults.payload | async)?.length > 0">{{ 'search.results.title' | translate }}</h2>
<ds-object-list [config]="searchConfig.pagination" [sortConfig]="searchConfig.sort"
[objects]="searchResults" [hideGear]="false"></ds-object-list>

View File

@@ -0,0 +1,21 @@
import { Component, Input } from '@angular/core';
import { RemoteData } from '../../core/data/remote-data';
import { SearchResult } from '../../search/search-result.model';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { SearchOptions } from '../../search/search-options.model';
/**
* This component renders a simple item page.
* The route parameter 'id' is used to request the item it represents.
* All fields of the item that should be displayed, are defined in its template.
*/
@Component({
selector: 'ds-search-results',
templateUrl: './search-results.component.html',
})
export class SearchResultsComponent {
@Input() searchResults: RemoteData<Array<SearchResult<DSpaceObject>>>;
@Input() searchConfig: SearchOptions;
}

View File

@@ -0,0 +1,7 @@
import { SortOptions } from '../core/cache/models/sort-options.model';
import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model';
export class SearchOptions {
pagination?: PaginationComponentOptions;
sort?: SortOptions;
}

View File

@@ -1,7 +1,8 @@
import { DSpaceObject } from '../core/shared/dspace-object.model';
import { Metadatum } from '../core/shared/metadatum.model';
import { ListableObject } from '../object-list/listable-object/listable-object.model';
export class SearchResult<T extends DSpaceObject> {
export class SearchResult<T extends DSpaceObject> implements ListableObject {
dspaceObject: T;
hitHighlights: Metadatum[];

View File

@@ -1,7 +0,0 @@
import { SortOptions } from '../core/cache/models/sort-options.model';
export class SearchOptions {
elementsPerPage?: number;
currentPage?: number;
sort?: SortOptions;
}

View File

@@ -5,10 +5,25 @@ import { SearchResult } from './search-result.model';
import { ItemDataService } from '../core/data/item-data.service';
import { PageInfo } from '../core/shared/page-info.model';
import { DSpaceObject } from '../core/shared/dspace-object.model';
import { SearchOptions } from './search.models';
import { SearchOptions } from './search-options.model';
import { hasValue, isNotEmpty } from '../shared/empty.util';
import { Metadatum } from '../core/shared/metadatum.model';
import { Item } from '../core/shared/item.model';
import { ItemSearchResult } from '../object-list/search-result-list-element/item-search-result/item-search-result.model';
function shuffle(array: any[]) {
let i = 0;
let j = 0;
let temp = null;
for (i = array.length - 1; i > 0; i -= 1) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
@Injectable()
export class SearchService {
@@ -36,39 +51,47 @@ export class SearchService {
if (hasValue(scopeId)) {
self += `&scope=${scopeId}`;
}
if (isNotEmpty(searchOptions) && hasValue(searchOptions.currentPage)) {
self += `&page=${searchOptions.currentPage}`;
if (isNotEmpty(searchOptions) && hasValue(searchOptions.pagination.currentPage)) {
self += `&page=${searchOptions.pagination.currentPage}`;
}
if (isNotEmpty(searchOptions) && hasValue(searchOptions.pagination.pageSize)) {
self += `&pageSize=${searchOptions.pagination.pageSize}`;
}
if (isNotEmpty(searchOptions) && hasValue(searchOptions.sort.direction)) {
self += `&sortDirection=${searchOptions.sort.direction}`;
}
if (isNotEmpty(searchOptions) && hasValue(searchOptions.sort.field)) {
self += `&sortField=${searchOptions.sort.field}`;
}
const requestPending = Observable.of(false);
const responsePending = Observable.of(false);
const isSuccessFul = Observable.of(true);
const errorMessage = Observable.of(undefined);
const statusCode = Observable.of('200');
const returningPageInfo = new PageInfo();
if (isNotEmpty(searchOptions)) {
returningPageInfo.elementsPerPage = searchOptions.elementsPerPage;
returningPageInfo.currentPage = searchOptions.currentPage;
returningPageInfo.elementsPerPage = searchOptions.pagination.pageSize;
returningPageInfo.currentPage = searchOptions.pagination.currentPage;
} else {
returningPageInfo.elementsPerPage = 10;
returningPageInfo.currentPage = 1;
}
returningPageInfo.totalPages = this.totalPages;
returningPageInfo.totalElements = 10 * this.totalPages;
const pageInfo = Observable.of(returningPageInfo);
const itemsRD = this.itemDataService.findAll({
scopeID: '8e0928a0-047a-4369-8883-12669f32dd64',
scopeID: scopeId,
currentPage: returningPageInfo.currentPage,
elementsPerPage: returningPageInfo.elementsPerPage
});
const pageInfo = itemsRD.pageInfo.map((info: PageInfo) => {
info.totalElements = info.totalElements > 20 ? 20 : info.totalElements;
return info;
});
const payload = itemsRD.payload.map((items: Item[]) => {
return items.sort(() => {
const values = [-1, 0, 1];
return values[Math.floor(Math.random() * values.length)];
})
return shuffle(items)
.map((item: Item, index: number) => {
const mockResult: SearchResult<DSpaceObject> = new SearchResult();
const mockResult: SearchResult<DSpaceObject> = new ItemSearchResult();
mockResult.dspaceObject = item;
const highlight = new Metadatum();
highlight.key = 'dc.description.abstract';
@@ -82,7 +105,7 @@ export class SearchService {
self,
requestPending,
responsePending,
isSuccessFul,
itemsRD.hasSucceeded,
errorMessage,
statusCode,
pageInfo,

View File

@@ -317,7 +317,7 @@ describe('Empty Utils', () => {
});
it('should return false for an empty Object', () => {
expect(isEmpty({})).toBe(false);
expect(isEmpty({})).toBe(true);
});
it('should return true for an Object that has zero \'length\'', () => {
@@ -377,7 +377,7 @@ describe('Empty Utils', () => {
});
it('should return true for an empty Object', () => {
expect(isNotEmpty({})).toBe(true);
expect(isNotEmpty({})).toBe(false);
});
it('should return false for an Object that has zero length', () => {

View File

@@ -90,7 +90,7 @@ export function hasValue(obj?: any): boolean {
* isEmpty(undefined); // true
* isEmpty(''); // true
* isEmpty([]); // true
* isEmpty({}); // false
* isEmpty({}); // true
* isEmpty('Adam Hawkins'); // false
* isEmpty([0,1,2]); // false
* isEmpty('\n\t'); // false
@@ -119,6 +119,9 @@ export function isEmpty(obj?: any): boolean {
}
if (objectType === 'object') {
if (Object.keys(obj).length === 0) {
return true;
}
const length = obj.length;
if (typeof length === 'number') {
return !length;
@@ -136,7 +139,7 @@ export function isEmpty(obj?: any): boolean {
* isNotEmpty(undefined); // false
* isNotEmpty(''); // false
* isNotEmpty([]); // false
* isNotEmpty({}); // true
* isNotEmpty({}); // false
* isNotEmpty('Adam Hawkins'); // true
* isNotEmpty([0,1,2]); // true
* isNotEmpty('\n\t'); // true

View File

@@ -11,12 +11,12 @@ import {
import { Observable } from 'rxjs/Observable';
import { RemoteData } from '../../core/data/remote-data';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { PageInfo } from '../../core/shared/page-info.model';
import { PaginationComponentOptions } from '../pagination/pagination-component-options.model';
import { SortOptions, SortDirection } from '../../core/cache/models/sort-options.model';
import { ListableObject } from '../../object-list/listable-object/listable-object.model';
@Component({
changeDetection: ChangeDetectionStrategy.Default,
@@ -27,7 +27,7 @@ import { SortOptions, SortDirection } from '../../core/cache/models/sort-options
})
export class ObjectListComponent implements OnChanges, OnInit {
@Input() objects: RemoteData<DSpaceObject[]>;
@Input() objects: RemoteData<ListableObject[]>;
@Input() config: PaginationComponentOptions;
@Input() sortConfig: SortOptions;
@Input() hideGear = false;
@@ -52,6 +52,8 @@ export class ObjectListComponent implements OnChanges, OnInit {
*/
@Output() sortDirectionChange: EventEmitter<SortDirection> = new EventEmitter<SortDirection>();
@Output() paginationChange: EventEmitter<SortDirection> = new EventEmitter<any>();
/**
* An event fired when the sort field is changed.
* Event's payload equals to the newly selected sort field.
@@ -95,4 +97,8 @@ export class ObjectListComponent implements OnChanges, OnInit {
this.sortFieldChange.emit(event);
}
onPaginationChange(event) {
this.paginationChange.emit(event);
}
}

View File

@@ -3,22 +3,21 @@
<div class="row">
<div class="col pagination-info">
<span class="align-middle hidden-xs-down">{{ 'pagination.showing.label' | translate }}</span>
<span class="align-middle">{{ 'pagination.showing.detail' | translate:showingDetail }}</span>
<span class="align-middle" *ngIf="collectionSize">{{ 'pagination.showing.detail' | translate:getShowingDetails(collectionSize)}}</span>
</div>
<div class="col">
<div ngbDropdown #paginationControls="ngbDropdown" class="d-inline-block float-right">
<button class="btn btn-outline-primary" id="paginationControls" (click)="$event.stopPropagation(); (paginationControls.isOpen())?paginationControls.close():paginationControls.open();"><i class="fa fa-cog" aria-hidden="true"></i></button>
<div class="dropdown-menu dropdown-menu-right" id="paginationControlsDropdownMenu" aria-labelledby="paginationControls">
<button class="btn btn-outline-primary" id="paginationControls" ngbDropdownToggle><i class="fa fa-cog" aria-hidden="true"></i></button>
<div class="dropdown-menu dropdown-menu-right" id="paginationControlsDropdownMenu" aria-labelledby="paginationControls" ngbDropdownMenu>
<h6 class="dropdown-header">{{ 'pagination.results-per-page' | translate}}</h6>
<button class="dropdown-item" style="padding-left: 20px" *ngFor="let item of pageSizeOptions" (click)="setPageSize(item)"><i class="fa fa-check {{(item != paginationOptions.pageSize) ? 'invisible' : ''}}" aria-hidden="true"></i> {{item}} </button>
<button class="dropdown-item" *ngFor="let item of pageSizeOptions" (click)="doPageSizeChange(item)"><i [ngClass]="{'invisible': item != pageSize}" class="fa fa-check" aria-hidden="true"></i> {{item}} </button>
<h6 class="dropdown-header">{{ 'pagination.sort-direction' | translate}}</h6>
<button class="dropdown-item" style="padding-left: 20px" *ngFor="let direction of (sortDirections | dsKeys)" (click)="setSortDirection(direction.key)"><i class="fa fa-check {{(direction.key != sortOptions.direction) ? 'invisible' : ''}}" aria-hidden="true"></i> {{direction.value}} </button>
<button class="dropdown-item" *ngFor="let direction of (sortDirections | dsKeys)" (click)="doSortDirectionChange(direction.key)"><i [ngClass]="{'invisible': direction.key != sortDirection}" class="fa fa-check" aria-hidden="true"></i> {{direction.value}} </button>
</div>
</div>
</div>
</div>
</div>
<ng-content></ng-content>
<div *ngIf="shouldShowBottomPager" class="pagination justify-content-center clearfix bottom">
@@ -27,7 +26,7 @@
[disabled]="paginationOptions.disabled"
[ellipses]="paginationOptions.ellipses"
[maxSize]="(isXs)?5:paginationOptions.maxSize"
[(page)]="currentPage"
[page]="currentPage"
(pageChange)="doPageChange($event)"
[pageSize]="pageSize"
[rotate]="paginationOptions.rotate"

View File

@@ -0,0 +1,8 @@
:host {
.dropdown-toggle::after {
display: none;
}
.dropdown-item {
padding-left: 20px;
}
}

View File

@@ -223,43 +223,48 @@ describe('Pagination component', () => {
});
it('should render and respond to pageSize change', () => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
testComp.collectionSize = 30;
testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '3', '» Next']);
changePageSize(testFixture, '5');
paginationComponent.setPageSize(5);
testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '3', '4', '5', '6', '» Next']);
changePageSize(testFixture, '10');
paginationComponent.setPageSize(10);
testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '3', '» Next']);
changePageSize(testFixture, '20');
paginationComponent.setPageSize(20);
testFixture.detectChanges();
expectPages(testFixture, ['-« Previous', '+1', '2', '» Next']);
});
it('should emit pageChange event with correct value', fakeAsync(() => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
spyOn(testComp, 'pageChanged');
changePage(testFixture, 3);
paginationComponent.setPage(3);
tick();
expect(testComp.pageChanged).toHaveBeenCalledWith(3);
}));
it('should emit pageSizeChange event with correct value', fakeAsync(() => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
spyOn(testComp, 'pageSizeChanged');
changePageSize(testFixture, '5');
paginationComponent.setPageSize(5);
tick();
expect(testComp.pageSizeChanged).toHaveBeenCalledWith(5);
}));
it('should set correct route parameters', fakeAsync(() => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
it('should set correct page route parameters', fakeAsync(() => {
routerStub = testFixture.debugElement.injector.get(Router) as any;
testComp.collectionSize = 60;
@@ -267,11 +272,29 @@ describe('Pagination component', () => {
changePage(testFixture, 3);
tick();
expect(routerStub.navigate).toHaveBeenCalledWith([], { queryParams: { pageId: 'test', page: 3, pageSize: 10, sortDirection: 0, sortField: 'name' } });
expect(paginationComponent.currentPage).toEqual(3);
}));
it('should set correct pageSize route parameters', fakeAsync(() => {
routerStub = testFixture.debugElement.injector.get(Router) as any;
testComp.collectionSize = 60;
changePageSize(testFixture, '20');
tick();
expect(routerStub.navigate).toHaveBeenCalledWith([], { queryParams: { pageId: 'test', page: 3, pageSize: 20, sortDirection: 0, sortField: 'name' } });
expect(routerStub.navigate).toHaveBeenCalledWith([], { queryParams: { pageId: 'test', page: 1, pageSize: 20, sortDirection: 0, sortField: 'name' } });
}));
it('should set correct values', fakeAsync(() => {
const paginationComponent: PaginationComponent = testFixture.debugElement.query(By.css('ds-pagination')).references.p;
routerStub = testFixture.debugElement.injector.get(Router) as any;
testComp.collectionSize = 60;
paginationComponent.setPage(3);
expect(paginationComponent.currentPage).toEqual(3);
paginationComponent.setPageSize(20);
expect(paginationComponent.pageSize).toEqual(20);
}));

View File

@@ -3,10 +3,9 @@ import {
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output, SimpleChanges,
Output,
ViewEncapsulation
} from '@angular/core'
@@ -21,7 +20,7 @@ import { HostWindowService } from '../host-window.service';
import { HostWindowState } from '../host-window.reducer';
import { PaginationComponentOptions } from './pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { hasValue, isUndefined } from '../empty.util';
import { hasValue, isNotEmpty } from '../empty.util';
import { PageInfo } from '../../core/shared/page-info.model';
/**
@@ -30,12 +29,12 @@ import { PageInfo } from '../../core/shared/page-info.model';
@Component({
exportAs: 'paginationComponent',
selector: 'ds-pagination',
styleUrls: ['pagination.component.scss'],
templateUrl: 'pagination.component.html',
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.Emulated
})
export class PaginationComponent implements OnChanges, OnDestroy, OnInit {
export class PaginationComponent implements OnDestroy, OnInit {
/**
* Number of items in collection.
*/
@@ -80,6 +79,12 @@ export class PaginationComponent implements OnChanges, OnDestroy, OnInit {
*/
@Output() sortFieldChange: EventEmitter<string> = new EventEmitter<string>();
/**
* An event fired when the sort field is changed.
* Event's payload equals to the newly selected sort field.
*/
@Output() paginationChange: EventEmitter<any> = new EventEmitter<any>();
/**
* Option for hiding the gear
*/
@@ -103,7 +108,7 @@ export class PaginationComponent implements OnChanges, OnDestroy, OnInit {
/**
* Current URL query parameters
*/
public currentQueryParams = {};
public currentQueryParams: any;
/**
* An observable of HostWindowState type
@@ -146,34 +151,12 @@ export class PaginationComponent implements OnChanges, OnDestroy, OnInit {
*/
public sortField = 'id';
/**
* Local variable, which can be used in the template to access the paginate controls ngbDropdown methods and properties
*/
public paginationControls;
/**
* Array to track all subscriptions and unsubscribe them onDestroy
* @type {Array}
*/
private subs: Subscription[] = [];
/**
* An object that represents pagination details of the current viewed page
*/
public showingDetail: any = {
range: null,
total: null
};
ngOnChanges(changes: SimpleChanges) {
if (changes.pageInfoState && !changes.pageInfoState.isFirstChange()) {
this.subs.push(this.pageInfoState.subscribe((pageInfo) => {
/* TODO: this is a temporary fix for the pagination start index (0 or 1) discrepancy between the rest and the frontend respectively */
this.currentPageState = pageInfo.currentPage + 1;
}));
}
}
/**
* Method provided by Angular. Invoked after the constructor.
*/
@@ -184,38 +167,25 @@ export class PaginationComponent implements OnChanges, OnDestroy, OnInit {
this.cdRef.markForCheck();
}));
this.checkConfig(this.paginationOptions);
if (this.pageInfoState) {
this.subs.push(this.pageInfoState.subscribe((pageInfo) => {
/* TODO: this is a temporary fix for the pagination start index (0 or 1) discrepancy between the rest and the frontend respectively */
this.currentPageState = pageInfo.currentPage + 1;
}));
}
this.id = this.paginationOptions.id || null;
this.pageSizeOptions = this.paginationOptions.pageSizeOptions;
this.initializeConfig();
// Listen to changes
this.subs.push(this.route.queryParams
.filter((queryParams) => hasValue(queryParams))
.subscribe((queryParams) => {
this.currentQueryParams = queryParams;
if (this.id === queryParams.pageId
&& (this.paginationOptions.currentPage !== +queryParams.page
|| this.paginationOptions.pageSize !== +queryParams.pageSize
|| this.sortOptions.direction !== +queryParams.sortDirection
|| this.sortOptions.field !== queryParams.sortField)
) {
this.validateParams(queryParams.page, queryParams.pageSize, queryParams.sortDirection, queryParams.sortField);
} else if (isUndefined(queryParams.pageId) && !isUndefined(this.currentPage)) {
// When moving back from a page with query params to page without them, initialize to the first page
this.doPageChange(1);
if (this.isEmptyPaginationParams(queryParams)) {
this.initializeConfig();
} else {
this.currentPage = this.paginationOptions.currentPage;
this.pageSize = this.paginationOptions.pageSize;
this.sortDirection = this.sortOptions.direction;
this.sortField = this.sortOptions.field;
this.currentQueryParams = queryParams;
const fixedProperties = this.validateParams(queryParams);
if (isNotEmpty(fixedProperties)) {
this.fixRoute(fixedProperties);
}
this.setFields();
}
}));
this.setShowingDetail();
}
private fixRoute(fixedProperties) {
this.updateRoute(fixedProperties);
}
/**
@@ -227,156 +197,251 @@ export class PaginationComponent implements OnChanges, OnDestroy, OnInit {
.forEach((sub) => sub.unsubscribe());
}
/**
* Initializes all default variables
*/
private initializeConfig() {
// Set initial values
this.id = this.paginationOptions.id || null;
this.pageSizeOptions = this.paginationOptions.pageSizeOptions;
this.currentPage = this.paginationOptions.currentPage;
this.pageSize = this.paginationOptions.pageSize;
this.sortDirection = this.sortOptions.direction;
this.sortField = this.sortOptions.field;
this.currentQueryParams = {
pageId: this.id,
page: this.currentPage,
pageSize: this.pageSize,
sortDirection: this.sortDirection,
sortField: this.sortField
};
}
/**
* @param route
* Route is a singleton service provided by Angular.
* @param router
* Router is a singleton service provided by Angular.
*/
constructor(
private cdRef: ChangeDetectorRef,
constructor(private cdRef: ChangeDetectorRef,
private route: ActivatedRoute,
private router: Router,
public hostWindowService: HostWindowService) {
}
/**
* Method to set set new page and update route parameters
* Method to change the route to the given page
*
* @param page
* The page being navigated to.
*/
public doPageChange(page: number) {
this.currentPage = page;
this.updateRoute();
this.setShowingDetail();
this.pageChange.emit(page);
this.updateRoute({ page: page });
}
/**
* Method to set set new page size and update route parameters
* Method to change the route to the given page size
*
* @param pageSize
* The new page size.
* The page size being navigated to.
*/
public doPageSizeChange(pageSize: number) {
this.updateRoute({ page: 1, pageSize: pageSize });
}
/**
* Method to change the route to the given sort direction
*
* @param sortDirection
* The sort direction being navigated to.
*/
public doSortDirectionChange(sortDirection: SortDirection) {
this.updateRoute({ page: 1, sortDirection: sortDirection });
}
/**
* Method to change the route to the given sort field
*
* @param sortField
* The sort field being navigated to.
*/
public doSortFieldChange(field: string) {
this.updateRoute({ page: 1, sortField: field });
}
/**
* Method to set the current page and trigger page change events
*
* @param page
* The new page value
*/
public setPage(page: number) {
this.currentPage = page;
this.pageChange.emit(page);
this.emitPaginationChange();
}
/**
* Method to set the current page size and trigger page size change events
*
* @param pageSize
* The new page size value.
*/
public setPageSize(pageSize: number) {
this.pageSize = pageSize;
this.updateRoute();
this.setShowingDetail();
this.pageSizeChange.emit(pageSize);
this.emitPaginationChange();
}
/**
* Method to set set new sort direction and update route parameters
* Method to set the current sort direction and trigger sort direction change events
*
* @param sortDirection
* The new sort direction.
* The new sort directionvalue.
*/
public setSortDirection(sortDirection: SortDirection) {
this.sortDirection = sortDirection;
this.updateRoute();
this.setShowingDetail();
this.sortDirectionChange.emit(sortDirection);
this.emitPaginationChange();
}
/**
* Method to set set new sort field and update route parameters
* Method to set the current sort field and trigger sort field change events
*
* @param sortField
* The new sort field.
*/
public setSortField(field: string) {
this.sortField = field;
this.updateRoute();
this.setShowingDetail();
this.sortFieldChange.emit(field);
this.emitPaginationChange();
}
/**
* Method to update the route parameters
* Method to emit a general pagination change event
*/
private updateRoute() {
this.router.navigate([], {
queryParams: Object.assign({}, this.currentQueryParams, {
private emitPaginationChange() {
this.paginationChange.emit({
pageId: this.id,
page: this.currentPage,
pageSize: this.pageSize,
sortDirection: this.sortDirection,
sortField: this.sortField
})
});
}
/**
* Method to set pagination details of the current viewed page.
* Method to update the route parameters
*/
private setShowingDetail() {
let firstItem;
let lastItem;
const lastPage = Math.round(this.collectionSize / this.pageSize);
firstItem = this.pageSize * (this.currentPage - 1) + 1;
if (this.currentPage !== lastPage) {
lastItem = this.pageSize * this.currentPage;
} else {
lastItem = this.collectionSize;
}
this.showingDetail = {
range: firstItem + ' - ' + lastItem,
total: this.collectionSize
}
private updateRoute(params: {}) {
this.router.navigate([], {
queryParams: Object.assign({}, this.currentQueryParams, params)
});
}
/**
* Validate query params
* Method to get pagination details of the current viewed page.
*/
public getShowingDetails(collectionSize: number): any {
let showingDetails = { range: null + ' - ' + null, total: null };
if (collectionSize) {
let firstItem;
let lastItem;
const pageMax = this.pageSize * this.currentPage;
firstItem = this.pageSize * (this.currentPage - 1) + 1;
if (collectionSize > pageMax) {
lastItem = pageMax;
} else {
lastItem = collectionSize;
}
showingDetails = { range: firstItem + ' - ' + lastItem, total: collectionSize };
}
return showingDetails;
}
/**
* Method to validate query params
*
* @param page
* The page number to validate
* @param pageSize
* The page size to validate
* @returns valid parameters if initial parameters were invalid
*/
private validateParams(page: any, pageSize: any, sortDirection: any, sortField: any) {
// tslint:disable-next-line:triple-equals
let filteredPageSize = this.pageSizeOptions.find((x) => x == pageSize);
if (!isNumeric(page) || !filteredPageSize) {
const filteredPage = isNumeric(page) ? page : this.currentPage;
filteredPageSize = (filteredPageSize) ? filteredPageSize : this.pageSize;
this.router.navigate([], {
queryParams: {
pageId: this.id,
page: filteredPage,
pageSize: filteredPageSize,
sortDirection: sortDirection,
sortField: sortField
private validateParams(params: any): any {
const validPage = this.validatePage(params.page);
const filteredSize = this.validatePageSize(params.pageSize);
const fixedFields: any = {};
if (+params.page !== validPage) {
fixedFields.page = validPage;
}
});
} else {
// (+) converts string to a number
if (this.currentPage !== +page) {
this.currentPage = +page;
this.pageChange.emit(this.currentPage);
}
if (this.pageSize !== +pageSize) {
this.pageSize = +pageSize;
this.pageSizeChange.emit(this.pageSize);
}
if (this.sortDirection !== +sortDirection) {
this.sortDirection = +sortDirection;
this.sortDirectionChange.emit(this.sortDirection);
}
if (this.sortField !== sortField) {
this.sortField = sortField;
this.sortFieldChange.emit(this.sortField);
}
this.cdRef.detectChanges();
if (+params.pageSize !== filteredSize) {
fixedFields.pageSize = filteredSize;
}
return fixedFields;
}
/**
* Ensure options passed contains the required properties.
* Method to update all pagination variables to the current query parameters
*/
private setFields() {
// (+) converts string to a number
const page = this.currentQueryParams.page;
if (this.currentPage !== +page) {
this.setPage(+page);
}
const pageSize = this.currentQueryParams.pageSize;
if (this.pageSize !== +pageSize) {
this.setPageSize(+pageSize);
}
const sortDirection = this.currentQueryParams.sortDirection;
if (this.sortDirection !== +sortDirection) {
this.setSortDirection(+sortDirection);
}
const sortField = this.currentQueryParams.sortField;
if (this.sortField !== sortField) {
this.setSortField(sortField);
}
this.cdRef.detectChanges();
}
/**
* Method to validate the current page value
*
* @param page
* The page number to validate
* @returns returns valid page value
*/
private validatePage(page: any): number {
let result = this.currentPage;
if (isNumeric(page)) {
result = +page;
}
return result;
}
/**
* Method to validate the current page size value
*
* @param page size
* The page size to validate
* @returns returns valid page size value
*/
private validatePageSize(pageSize: any): number {
const filteredPageSize = this.pageSizeOptions.find((x) => x === +pageSize);
let result = this.pageSize;
if (filteredPageSize) {
result = +pageSize;
}
return result;
}
/**
* Method to ensure options passed contains the required properties.
*
* @param paginateOptions
* The paginate options object.
@@ -391,11 +456,35 @@ export class PaginationComponent implements OnChanges, OnDestroy, OnInit {
}
}
/**
* Method to check if none of the query params necessary for pagination are filled out.
*
* @param paginateOptions
* The paginate options object.
*/
private isEmptyPaginationParams(paginateOptions): boolean {
const properties = ['id', 'currentPage', 'pageSize', 'pageSizeOptions'];
const missing = properties.filter((prop) => {
return !(prop in paginateOptions);
});
return properties.length === missing.length;
}
/**
* Property to check whether the current pagination object has multiple pages
* @returns true if there are multiple pages, else returns false
*/
get hasMultiplePages(): boolean {
return this.collectionSize > this.pageSize;
}
/**
* Property to check whether the current pagination should show a bottom pages
* @returns true if a bottom pages should be shown, else returns false
*/
get shouldShowBottomPager(): boolean {
return this.hasMultiplePages || !this.hidePagerWhenSinglePage
}
}

View File

@@ -0,0 +1,16 @@
<form #form="ngForm" (ngSubmit)="onSubmit(form.value)" class="row">
<div *ngIf="isNotEmpty(scopes | async)" class="col-12 col-sm-3">
<select [(ngModel)]="selectedId" name="scope" class="form-control" aria-label="Search scope" [compareWith]="byId">
<option value>{{'search.form.search_dspace' | translate}}</option>
<option *ngFor="let scopeOption of scopes | async" [value]="scopeOption.id">{{scopeOption?.name ? scopeOption.name : 'search.form.search_dspace' | translate}}</option>
</select>
</div>
<div [ngClass]="{'col-sm-9': isNotEmpty(scopes | async)}" class="col-12">
<div class="form-group input-group">
<input type="text" [(ngModel)]="query" name="query" class="form-control" aria-label="Search input">
<span class="input-group-btn">
<button type="submit" class="search-button btn btn-secondary">{{ ('search.form.search' | translate) }}</button>
</span>
</div>
</div>
</form>

View File

@@ -0,0 +1,7 @@
@import '../../../styles/variables.scss';
// temporary fix for bootstrap 4 beta btn color issue
.btn-secondary {
background-color: $input-bg;
color: $input-color;
}

View File

@@ -0,0 +1,83 @@
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { Router } from '@angular/router';
import { isNotEmpty, hasValue, isEmpty } from '../empty.util';
import { Observable } from 'rxjs/Observable';
/**
* This component renders a simple item page.
* The route parameter 'id' is used to request the item it represents.
* All fields of the item that should be displayed, are defined in its template.
*/
@Component({
selector: 'ds-search-form',
styleUrls: ['./search-form.component.scss'],
templateUrl: './search-form.component.html',
})
export class SearchFormComponent implements OnInit, OnDestroy {
@Input() query: string;
selectedId = '';
// Optional existing search parameters
@Input() currentParams: {};
@Input() scopes: Observable<DSpaceObject[]>;
scopeOptions: string[] = [];
sub;
@Input()
set scope(dso: DSpaceObject) {
if (hasValue(dso)) {
this.selectedId = dso.id;
}
}
ngOnInit(): void {
if (this.scopes) {
this.sub =
this.scopes
.filter((scopes: DSpaceObject[]) => isEmpty(scopes))
.subscribe((scopes: DSpaceObject[]) => {
this.scopeOptions = scopes
.map((scope: DSpaceObject) => scope.id);
}
);
}
}
constructor(private router: Router) {
}
onSubmit(data: any) {
this.updateSearch(data);
}
updateSearch(data: any) {
this.router.navigate(['/search'], {
queryParams: Object.assign({}, this.currentParams,
{
query: data.query,
scope: data.scope || undefined,
page: data.page || 1
}
)
})
;
}
isNotEmpty(object: any) {
return isNotEmpty(object);
}
byId(id1: string, id2: string) {
if (isEmpty(id1) && isEmpty(id2)) {
return true;
}
return id1 === id2;
}
ngOnDestroy(): void {
if (this.sub) {
this.sub.unsubscribe();
}
}
}

View File

@@ -24,6 +24,9 @@ import { ItemListElementComponent } from '../object-list/item-list-element/item-
import { CommunityListElementComponent } from '../object-list/community-list-element/community-list-element.component';
import { CollectionListElementComponent } from '../object-list/collection-list-element/collection-list-element.component';
import { TruncatePipe } from './utils/truncate.pipe';
import { WrapperListElementComponent } from '../object-list/wrapper-list-element/wrapper-list-element.component';
import { SearchResultListElementComponent } from '../object-list/search-result-list-element/search-result-list-element.component';
import { SearchFormComponent } from './search-form/search-form.component';
const MODULES = [
// Do NOT include UniversalModule, HttpModule, or JsonpModule here
@@ -53,9 +56,16 @@ const COMPONENTS = [
ComcolPageLogoComponent,
ObjectListComponent,
ObjectListElementComponent,
WrapperListElementComponent,
SearchFormComponent
];
const ENTRY_COMPONENTS = [
// put shared entry components (components that are created dynamically) here
ItemListElementComponent,
CollectionListElementComponent,
CommunityListElementComponent
CommunityListElementComponent,
SearchResultListElementComponent
];
@NgModule({
@@ -64,12 +74,16 @@ const COMPONENTS = [
],
declarations: [
...PIPES,
...COMPONENTS
...COMPONENTS,
...ENTRY_COMPONENTS
],
exports: [
...MODULES,
...PIPES,
...COMPONENTS
],
entryComponents: [
...ENTRY_COMPONENTS
]
})
export class SharedModule {

View File

@@ -3,5 +3,6 @@ export const ROUTES: string[] = [
'items/:id',
'collections/:id',
'communities/:id',
'search',
'**'
];

View File

@@ -0,0 +1,31 @@
/* Fonts */
$fa-font-path: "../assets/fonts";
/* Images */
$image-path: "../assets/images";
/* Colors */
$gray-base: #000 !default;
$gray-900: lighten($gray-base, 13.5%) !default; // #222
$gray-800: lighten($gray-base, 26.6%) !default; // #444
$gray-700: lighten($gray-base, 46.6%) !default; // #777
$gray-600: lighten($gray-base, 73.3%) !default; // #bbb
$gray-100: lighten($gray-base, 93.5%) !default; // #eee
/* Reassign color vars to semantic color scheme */
$blue: #2B4E72 !default;
$green: #94BA65 !default;
$cyan: #2790B0 !default;
$yellow: #EBBB54 !default;
$red: #CF4444 !default;
$theme-colors: (
primary: $blue,
secondary: $gray-700,
success: $green,
info: $cyan,
warning: $yellow,
danger: $red,
light: $gray-100,
dark: $blue
) !default;
/* Fonts */
$link-color: map-get($theme-colors, info) !default;

View File

@@ -0,0 +1 @@
$content-spacing: $spacer * 1.5;

View File

@@ -1,12 +1,4 @@
@import './variables.scss';
@import '../../node_modules/bootstrap/scss/variables';
@import '../../node_modules/bootstrap/scss/mixins';
@mixin negate-gutters($gutters: $grid-gutter-widths) {
@each $breakpoint in map-keys($gutters){
@include media-breakpoint-up($breakpoint) {
$gutter: map-get($gutters, $breakpoint);
margin-right: ($gutter / -2);
margin-left: ($gutter / -2);
}
}
}
@import '../../node_modules/bootstrap/scss/functions.scss';
@import '../../node_modules/bootstrap/scss/mixins.scss';
/* Custom mixins go here */

View File

@@ -0,0 +1,5 @@
@import 'bootstrap_variables.scss';
@import '../../node_modules/font-awesome/scss/variables.scss';
@import '../../node_modules/bootstrap/scss/functions.scss';
@import '../../node_modules/bootstrap/scss/variables.scss';
@import 'custom_variables.scss';

View File

@@ -1,20 +0,0 @@
/* Fonts */
$fa-font-path: "../assets/fonts";
/* Images */
$image-path: "../assets/images";
/* Colors */
$gray-base: #000 !default;
$gray-darker: lighten($gray-base, 13.5%) !default; // #222
$gray-dark: lighten($gray-base, 26.6%) !default; // #444
$gray: lighten($gray-base, 46.6%) !default; // #777
$gray-light: lighten($gray-base, 73.3%) !default; // #bbb
$gray-lighter: lighten($gray-base, 93.5%) !default; // #eee
/* Reassign color vars to semantic color scheme */
$brand-primary: #2B4E72 !default;
$brand-success: #94BA65 !default;
$brand-info: #2790B0 !default;
$brand-warning: #EBBB54 !default;
$brand-danger: #CF4444 !default;
$brand-inverse: $brand-primary !default;
/* Fonts */
$link-color: $brand-info !default;

View File

@@ -53,7 +53,7 @@
"no-debugger": true,
"no-duplicate-variable": true,
"no-empty": true,
"no-empty-interface": true,
"no-empty-interface": false,
"no-eval": true,
"no-forward-ref": true,
"no-inferrable-types": [

1734
yarn.lock

File diff suppressed because it is too large Load Diff