Merge branch 'master' into w2p-65272_Edit-collection-item-template

Conflicts:
	resources/i18n/en.json5
	src/app/+collection-page/collection-page-routing.module.ts
	src/app/+collection-page/collection-page.module.ts
	src/app/core/core.module.ts
	src/app/core/data/data.service.ts
	src/app/shared/shared.module.ts
This commit is contained in:
Kristof De Langhe
2019-11-29 11:04:06 +01:00
551 changed files with 45914 additions and 5158 deletions

View File

@@ -17,13 +17,12 @@ before_install:
- curl -L https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose - curl -L https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose
- chmod +x docker-compose - chmod +x docker-compose
- sudo mv docker-compose /usr/local/bin - sudo mv docker-compose /usr/local/bin
- git clone https://github.com/DSpace-Labs/DSpace-Docker-Images.git
install: install:
# Start up DSpace 7 using the entities database dump # Start up DSpace 7 using the entities database dump
- docker-compose -f DSpace-Docker-Images/docker-compose-files/dspace-compose-v2/d7.travis.ci.yml up -d - docker-compose -f ./docker/docker-compose-travis.yml up -d
# Use the dspace-cli image to populate the assetstore. Trigger a discovery and oai update # Use the dspace-cli image to populate the assetstore. Trigger a discovery and oai update
- docker-compose -f DSpace-Docker-Images/docker-compose-files/dspace-compose-v2/d7.cli.yml -f DSpace-Docker-Images/docker-compose-files/dspace-compose-v2/d7.cli.assetstore.yml run --rm dspace-cli - docker-compose -f ./docker/cli.yml -f ./docker/cli.assetstore.yml run --rm dspace-cli
- travis_retry yarn install - travis_retry yarn install
before_script: before_script:
@@ -32,7 +31,7 @@ before_script:
#- curl http://localhost:8080/ #- curl http://localhost:8080/
after_script: after_script:
- docker-compose -f DSpace-Docker-Images/docker-compose-files/dspace-compose-v2/d7.travis.ci.yml down - docker-compose -f ./docker/docker-compose-travis.yml down
addons: addons:
apt: apt:

View File

@@ -3,13 +3,12 @@
dspace-angular dspace-angular
============== ==============
> The next UI for DSpace, based on Angular Universal. > The next UI for DSpace 7, based on Angular Universal.
This project is currently in pre-alpha. This project is currently under active development. For more information on the DSpace 7 release see the [DSpace 7.0 Release Status wiki page](https://wiki.lyrasis.org/display/DSPACE/DSpace+Release+7.0+Status)
You can find additional information on the [wiki](https://wiki.duraspace.org/display/DSPACE/DSpace+7+-+Angular+UI) or [the project board (waffle.io)](https://waffle.io/DSpace/dspace-angular). You can find additional information on the DSpace 7 Angular UI on the [wiki](https://wiki.lyrasis.org/display/DSPACE/DSpace+7+-+Angular+UI+Development).
If you're looking for the 2016 Angular 2 DSpace UI prototype, you can find it [here](https://github.com/DSpace-Labs/angular2-ui-prototype)
Quick start Quick start
----------- -----------
@@ -32,8 +31,6 @@ yarn start
Then go to [http://localhost:3000](http://localhost:3000) in your browser Then go to [http://localhost:3000](http://localhost:3000) in your browser
NOTE: currently there's not much to see at that URL. We really do need your help. If you're interested in jumping in, and you've made it this far, please look at the [the project board (waffle.io)](https://waffle.io/DSpace/dspace-angular), grab a card, and get to work. Thanks!
Not sure where to start? watch the training videos linked in the [Introduction to the technology](#introduction-to-the-technology) section below. Not sure where to start? watch the training videos linked in the [Introduction to the technology](#introduction-to-the-technology) section below.
Table of Contents Table of Contents
@@ -42,24 +39,27 @@ Table of Contents
- [Introduction to the technology](#introduction-to-the-technology) - [Introduction to the technology](#introduction-to-the-technology)
- [Requirements](#requirements) - [Requirements](#requirements)
- [Installing](#installing) - [Installing](#installing)
- [Configuring](#configuring) - [Configuring](#configuring)
- [Running the app](#running-the-app) - [Running the app](#running-the-app)
- [Running in production mode](#running-in-production-mode) - [Running in production mode](#running-in-production-mode)
- [Deploy](#deploy)
- [Running the application with Docker](#running-the-application-with-docker)
- [Cleaning](#cleaning) - [Cleaning](#cleaning)
- [Testing](#testing) - [Testing](#testing)
- [Test a Pull Request](#test-a-pull-request)
- [Documentation](#documentation) - [Documentation](#documentation)
- [Other commands](#other-commands) - [Other commands](#other-commands)
- [Recommended Editors/IDEs](#recommended-editorsides) - [Recommended Editors/IDEs](#recommended-editorsides)
- [Collaborating](#collaborating) - [Collaborating](#collaborating)
- [File Structure](#file-structure) - [File Structure](#file-structure)
- [3rd Party Library Installation](#3rd-party-library-installation) - [Managing Dependencies (via yarn)](#managing-dependencies-via-yarn)
- [Frequently asked questions](#frequently-asked-questions) - [Frequently asked questions](#frequently-asked-questions)
- [License](#license) - [License](#license)
Introduction to the technology Introduction to the technology
------------------------------ ------------------------------
You can find more information on the technologies used in this project (Angular 2, Typescript, Angular Universal, RxJS, etc) on the [DuraSpace wiki](https://wiki.duraspace.org/display/DSPACE/DSpace+7+UI+Technology+Stack) You can find more information on the technologies used in this project (Angular.io, Typescript, Angular Universal, RxJS, etc) on the [LYRASIS wiki](https://wiki.lyrasis.org/display/DSPACE/DSpace+7+UI+Technology+Stack)
Requirements Requirements
------------ ------------
@@ -75,8 +75,7 @@ Installing
- `yarn run global` to install the required global dependencies - `yarn run global` to install the required global dependencies
- `yarn install` to install the local dependencies - `yarn install` to install the local dependencies
Configuring ### Configuring
-----------
Default configuration file is located in `config/` folder. Default configuration file is located in `config/` folder.
@@ -98,8 +97,7 @@ Running the app
After you have installed all dependencies you can now run the app. Run `yarn run watch` to start a local server which will watch for changes, rebuild the code, and reload the server for you. You can visit it at `http://localhost:3000`. After you have installed all dependencies you can now run the app. Run `yarn run watch` to start a local server which will watch for changes, rebuild the code, and reload the server for you. You can visit it at `http://localhost:3000`.
Running in production mode ### Running in production mode
--------------------------
When building for production we're using Ahead of Time (AoT) compilation. With AoT, the browser downloads a pre-compiled version of the application, so it can render the application immediately, without waiting to compile the app first. The compiler is roughly half the size of Angular itself, so omitting it dramatically reduces the application payload. When building for production we're using Ahead of Time (AoT) compilation. With AoT, the browser downloads a pre-compiled version of the application, so it can render the application immediately, without waiting to compile the app first. The compiler is roughly half the size of Angular itself, so omitting it dramatically reduces the application payload.
@@ -117,6 +115,19 @@ yarn run build:prod
This will build the application and put the result in the `dist` folder This will build the application and put the result in the `dist` folder
### Deploy
```bash
# deploy production in standalone pm2 container
yarn run deploy
# remove production from standalone pm2 container
yarn run undeploy
```
### Running the application with Docker
See [Docker Runtime Options](docker/README.md)
Cleaning Cleaning
-------- --------
@@ -131,6 +142,7 @@ yarn run clean:prod
yarn run clean:dist yarn run clean:dist
``` ```
Testing Testing
------- -------
@@ -184,21 +196,14 @@ To run all the tests (e.g.: to run tests with Continuous Integration software) y
Documentation Documentation
-------------- --------------
See [`./docs`](docs) for further documentation.
### Building code documentation
To build the code documentation we use [TYPEDOC](http://typedoc.org). TYPEDOC is a documentation generator for TypeScript projects. It extracts informations from properly formatted comments that can be written within the code files. Follow the instructions [here](http://typedoc.org/guides/doccomments/) to know how to make those comments. To build the code documentation we use [TYPEDOC](http://typedoc.org). TYPEDOC is a documentation generator for TypeScript projects. It extracts informations from properly formatted comments that can be written within the code files. Follow the instructions [here](http://typedoc.org/guides/doccomments/) to know how to make those comments.
Run:`yarn run docs` to produce the documentation that will be available in the 'doc' folder. Run:`yarn run docs` to produce the documentation that will be available in the 'doc' folder.
Deploy
------
```bash
# deploy production in standalone pm2 container
yarn run deploy
# remove production from standalone pm2 container
yarn run undeploy
```
Other commands Other commands
-------------- --------------
@@ -224,7 +229,7 @@ To get the most out of TypeScript, you'll need a TypeScript-aware editor. We've
Collaborating Collaborating
------------- -------------
See [the guide on the wiki](https://wiki.duraspace.org/display/DSPACE/DSpace+7+-+Angular+2+UI#DSpace7-Angular2UI-Howtocontribute) See [the guide on the wiki](https://wiki.lyrasis.org/display/DSPACE/DSpace+7+-+Angular+UI+Development#DSpace7-AngularUIDevelopment-Howtocontribute)
File Structure File Structure
-------------- --------------
@@ -330,10 +335,20 @@ dspace-angular
└── yarn.lock * Yarn lockfile (https://yarnpkg.com/en/docs/yarn-lock) └── yarn.lock * Yarn lockfile (https://yarnpkg.com/en/docs/yarn-lock)
``` ```
3rd Party Library Installation Managing Dependencies (via yarn)
------------------------------ -------------
Install your library via `yarn add lib-name --save` and import it in your code. `--save` will add it to `package.json`. This project makes use of [`yarn`](https://yarnpkg.com/en/) to ensure that the exact same dependency versions are used every time you install it.
* `yarn` creates a [`yarn.lock`](https://yarnpkg.com/en/docs/yarn-lock) to track those versions. That file is updated automatically by whenever dependencies are added/updated/removed via yarn.
* **Adding new dependencies**: To install/add a new dependency (third party library), use [`yarn add`](https://yarnpkg.com/en/docs/cli/add). For example: `yarn add some-lib`.
* If you are adding a new build tool dependency (to `devDependencies`), use `yarn add some-lib --dev`
* **Upgrading existing dependencies**: To upgrade existing dependencies, you can use [`yarn upgrade`](https://yarnpkg.com/en/docs/cli/upgrade). For example: `yarn upgrade some-lib` or `yarn upgrade some-lib@version`
* **Removing dependencies**: If a dependency is no longer needed, or replaced, use [`yarn remove`](https://yarnpkg.com/en/docs/cli/remove) to remove it.
As you can see above, using `yarn` commandline tools means that you should never need to modify the `package.json` manually. *We recommend always using `yarn` to keep dependencies updated / in sync.*
### Adding Typings for libraries
If the library does not include typings, you can install them using yarn: If the library does not include typings, you can install them using yarn:
@@ -365,24 +380,6 @@ If you're importing a module that uses CommonJS you need to import as
import * as _ from 'lodash'; import * as _ from 'lodash';
``` ```
Managing Dependencies (via yarn)
-------------
This project makes use of [`yarn`](https://yarnpkg.com/en/) to ensure that the exact same dependency versions are used every time you install it.
* `yarn` creates a [`yarn.lock`](https://yarnpkg.com/en/docs/yarn-lock) to track those versions. That file is updated automatically by whenever dependencies are added/updated/removed via yarn.
* **Adding new dependencies**: To install/add a new dependency (third party library), use [`yarn add`](https://yarnpkg.com/en/docs/cli/add). For example: `yarn add some-lib`.
* If you are adding a new build tool dependency (to `devDependencies`), use `yarn add some-lib --dev`
* **Upgrading existing dependencies**: To upgrade existing dependencies, you can use [`yarn upgrade`](https://yarnpkg.com/en/docs/cli/upgrade). For example: `yarn upgrade some-lib` or `yarn upgrade some-lib@version`
* **Removing dependencies**: If a dependency is no longer needed, or replaced, use [`yarn remove`](https://yarnpkg.com/en/docs/cli/remove) to remove it.
As you can see above, using `yarn` commandline tools means that you should never need to modify the `package.json` manually. *We recommend always using `yarn` to keep dependencies updated / in sync.*
Further Documentation
---------------------
See [`./docs`](docs) for further documentation.
Frequently asked questions Frequently asked questions
-------------------------- --------------------------
@@ -406,5 +403,4 @@ Frequently asked questions
License License
------- -------
This project's source code is made available under the DSpace BSD License: http://www.dspace.org/license
http://www.dspace.org/license

View File

@@ -141,6 +141,10 @@ module.exports = {
code: 'nl', code: 'nl',
label: 'Nederlands', label: 'Nederlands',
active: false, active: false,
}, {
code: 'pt',
label: 'Português',
active: true,
}], }],
// Browse-By Pages // Browse-By Pages
browseBy: { browseBy: {

79
docker/README.md Normal file
View File

@@ -0,0 +1,79 @@
# Docker Compose files
## docker directory
- docker-compose.yml
- Starts DSpace Angular with Docker Compose from the current branch. This file assumes that a DSpace 7 REST instance will also be started in Docker.
- docker-compose-rest.yml
- Runs a published instance of the DSpace 7 REST API - persists data in Docker volumes
- docker-compose-travis.yml
- Runs a published instance of the DSpace 7 REST API for CI testing. The database is re-populated from a SQL dump on each startup.
- cli.yml
- Docker compose file that provides a DSpace CLI container to work with a running DSpace REST container.
- cli.assetstore.yml
- Docker compose file that will download and install data into a DSpace REST assetstore. This script points to a default dataset that will be utilized for CI testing.
- environment.dev.js
- Environment file for running DSpace Angular in Docker
- local.cfg
- Environment file for running the DSpace 7 REST API in Docker.
## To refresh / pull DSpace images from Dockerhub
```
docker-compose -f docker/docker-compose.yml pull
```
## To build DSpace images using code in your branch
```
docker-compose -f docker/docker-compose.yml build
```
## To start DSpace (REST and Angular) from your branch
```
docker-compose -p d7 -f docker/docker-compose.yml -f docker/docker-compose-rest.yml up -d
```
## Run DSpace REST and DSpace Angular from local branches.
_The system will be started in 2 steps. Each step shares the same docker network._
From DSpace/DSpace (build as needed)
```
docker-compose -p d7 up -d
```
From DSpace/DSpace-angular
```
docker-compose -p d7 -f docker/docker-compose.yml up -d
```
## Ingest test data from AIPDIR
Create an administrator
```
docker-compose -p d7 -f docker/cli.yml run --rm dspace-cli create-administrator -e test@test.edu -f admin -l user -p admin -c en
```
Load content from AIP files
```
docker-compose -p d7 -f docker/cli.yml -f ./docker/cli.ingest.yml run --rm dspace-cli
```
## Alternative Ingest - Use Entities dataset
_Delete your docker volumes or use a unique project (-p) name_
Start DSpace with Database Content from a database dump
```
docker-compose -p d7 -f docker/docker-compose.yml -f docker/docker-compose-rest.yml -f docker/db.entities.yml up -d
```
Load assetstore content and trigger a re-index of the repository
```
docker-compose -p d7 -f docker/cli.yml -f docker/cli.assetstore.yml run --rm dspace-cli
```
## End to end testing of the rest api (runs in travis).
_In this instance, only the REST api runs in Docker using the Entities dataset. Travis will perform CI testing of Angular using Node to drive the tests._
```
docker-compose -p d7ci -f docker/docker-compose-travis.yml up -d
```

23
docker/cli.assetstore.yml Normal file
View File

@@ -0,0 +1,23 @@
version: "3.7"
networks:
dspacenet:
services:
dspace-cli:
networks:
dspacenet: {}
environment:
- LOADASSETS=https://www.dropbox.com/s/zv7lj8j2lp3egjs/assetstore.tar.gz?dl=1
entrypoint:
- /bin/bash
- '-c'
- |
if [ ! -z $${LOADASSETS} ]
then
curl $${LOADASSETS} -L -s --output /tmp/assetstore.tar.gz
cd /dspace
tar xvfz /tmp/assetstore.tar.gz
fi
/dspace/bin/dspace index-discovery

32
docker/cli.ingest.yml Normal file
View File

@@ -0,0 +1,32 @@
#
# The contents of this file are subject to the license and copyright
# detailed in the LICENSE and NOTICE files at the root of the source
# tree and available online at
#
# http://www.dspace.org/license/
#
version: "3.7"
services:
dspace-cli:
environment:
- AIPZIP=https://github.com/DSpace-Labs/AIP-Files/raw/master/dogAndReport.zip
- ADMIN_EMAIL=test@test.edu
- AIPDIR=/tmp/aip-dir
entrypoint:
- /bin/bash
- '-c'
- |
rm -rf $${AIPDIR}
mkdir $${AIPDIR} /dspace/upload
cd $${AIPDIR}
pwd
curl $${AIPZIP} -L -s --output aip.zip
unzip aip.zip
cd $${AIPDIR}
/dspace/bin/dspace packager -r -a -t AIP -e $${ADMIN_EMAIL} -f -u SITE*.zip
/dspace/bin/dspace database update-sequences
/dspace/bin/dspace index-discovery

22
docker/cli.yml Normal file
View File

@@ -0,0 +1,22 @@
version: "3.7"
services:
dspace-cli:
image: "${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-dspace-7_x}"
container_name: dspace-cli
#environment:
volumes:
- "assetstore:/dspace/assetstore"
- "./local.cfg:/dspace/config/local.cfg"
entrypoint: /dspace/bin/dspace
command: help
networks:
- dspacenet
tty: true
stdin_open: true
volumes:
assetstore:
networks:
dspacenet:

16
docker/db.entities.yml Normal file
View File

@@ -0,0 +1,16 @@
#
# The contents of this file are subject to the license and copyright
# detailed in the LICENSE and NOTICE files at the root of the source
# tree and available online at
#
# http://www.dspace.org/license/
#
version: "3.7"
services:
dspacedb:
image: dspace/dspace-postgres-pgcrypto:loadsql
environment:
# Double underbars in env names will be replaced with periods for apache commons
- LOADSQL=https://www.dropbox.com/s/xh3ack0vg0922p2/configurable-entities-2019-05-08.sql?dl=1

View File

@@ -0,0 +1,59 @@
networks:
dspacenet:
services:
dspace:
container_name: dspace
depends_on:
- dspacedb
image: dspace/dspace:dspace-7_x-jdk8-test
networks:
dspacenet:
ports:
- published: 8080
target: 8080
stdin_open: true
tty: true
volumes:
- assetstore:/dspace/assetstore
- "./local.cfg:/dspace/config/local.cfg"
# Ensure that the database is ready before starting tomcat
entrypoint:
- /bin/bash
- '-c'
- |
/dspace/bin/dspace database migrate
catalina.sh run
dspacedb:
container_name: dspacedb
image: dspace/dspace-postgres-pgcrypto
environment:
PGDATA: /pgdata
networks:
dspacenet:
stdin_open: true
tty: true
volumes:
- pgdata:/pgdata
dspacesolr:
container_name: dspacesolr
image: dspace/dspace-solr
networks:
dspacenet:
ports:
- published: 8983
target: 8983
stdin_open: true
tty: true
volumes:
- solr_authority:/opt/solr/server/solr/authority/data
- solr_oai:/opt/solr/server/solr/oai/data
- solr_search:/opt/solr/server/solr/search/data
- solr_statistics:/opt/solr/server/solr/statistics/data
version: '3.7'
volumes:
assetstore:
pgdata:
solr_authority:
solr_oai:
solr_search:
solr_statistics:

View File

@@ -0,0 +1,53 @@
networks:
dspacenet:
services:
dspace:
container_name: dspace
depends_on:
- dspacedb
image: dspace/dspace:dspace-7_x-jdk8-test
networks:
dspacenet:
ports:
- published: 8080
target: 8080
stdin_open: true
tty: true
volumes:
- assetstore:/dspace/assetstore
- "./local.cfg:/dspace/config/local.cfg"
dspacedb:
container_name: dspacedb
environment:
LOADSQL: https://www.dropbox.com/s/xh3ack0vg0922p2/configurable-entities-2019-05-08.sql?dl=1
PGDATA: /pgdata
image: dspace/dspace-postgres-pgcrypto:loadsql
networks:
dspacenet:
stdin_open: true
tty: true
volumes:
- pgdata:/pgdata
dspacesolr:
container_name: dspacesolr
image: dspace/dspace-solr
networks:
dspacenet:
ports:
- published: 8983
target: 8983
stdin_open: true
tty: true
volumes:
- solr_authority:/opt/solr/server/solr/authority/data
- solr_oai:/opt/solr/server/solr/oai/data
- solr_search:/opt/solr/server/solr/search/data
- solr_statistics:/opt/solr/server/solr/statistics/data
version: '3.7'
volumes:
assetstore:
pgdata:
solr_authority:
solr_oai:
solr_search:
solr_statistics:

26
docker/docker-compose.yml Normal file
View File

@@ -0,0 +1,26 @@
version: '3.7'
networks:
dspacenet:
services:
dspace-angular:
container_name: dspace-angular
environment:
DSPACE_HOST: dspace-angular
DSPACE_NAMESPACE: /
DSPACE_PORT: '3000'
DSPACE_SSL: "false"
image: dspace/dspace-angular:latest
build:
context: ..
dockerfile: Dockerfile
networks:
dspacenet:
ports:
- published: 3000
target: 3000
- published: 9876
target: 9876
stdin_open: true
tty: true
volumes:
- ./environment.dev.js:/app/config/environment.dev.js

16
docker/environment.dev.js Normal file
View File

@@ -0,0 +1,16 @@
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
module.exports = {
rest: {
ssl: false,
host: 'localhost',
port: 8080,
// NOTE: Space is capitalized because 'namespace' is a reserved string in TypeScript
nameSpace: '/server/api'
}
};

6
docker/local.cfg Normal file
View File

@@ -0,0 +1,6 @@
dspace.dir=/dspace
db.url=jdbc:postgresql://dspacedb:5432/dspace
dspace.hostname=dspace
dspace.baseUrl=http://localhost:8080/server
dspace.name=DSpace Started with Docker Compose
solr.server=http://dspacesolr:8983/solr

View File

@@ -70,7 +70,8 @@
"docs": "typedoc --options typedoc.json ./src/", "docs": "typedoc --options typedoc.json ./src/",
"coverage": "http-server -c-1 -o -p 9875 ./coverage", "coverage": "http-server -c-1 -o -p 9875 ./coverage",
"postinstall": "yarn run patch-protractor", "postinstall": "yarn run patch-protractor",
"patch-protractor": "ncp node_modules/webdriver-manager node_modules/protractor/node_modules/webdriver-manager" "patch-protractor": "ncp node_modules/webdriver-manager node_modules/protractor/node_modules/webdriver-manager",
"sync-i18n": "node ./scripts/sync-i18n-files.js"
}, },
"dependencies": { "dependencies": {
"@angular/animations": "^6.1.4", "@angular/animations": "^6.1.4",
@@ -174,7 +175,9 @@
"angular2-template-loader": "0.6.2", "angular2-template-loader": "0.6.2",
"autoprefixer": "^9.1.3", "autoprefixer": "^9.1.3",
"caniuse-lite": "^1.0.30000697", "caniuse-lite": "^1.0.30000697",
"cli-progress": "^3.3.1",
"codelyzer": "^4.4.4", "codelyzer": "^4.4.4",
"commander": "^3.0.2",
"compression-webpack-plugin": "^1.1.6", "compression-webpack-plugin": "^1.1.6",
"copy-webpack-plugin": "^4.4.1", "copy-webpack-plugin": "^4.4.1",
"copyfiles": "^2.1.1", "copyfiles": "^2.1.1",
@@ -236,7 +239,7 @@
"tslint": "5.11.0", "tslint": "5.11.0",
"typedoc": "^0.9.0", "typedoc": "^0.9.0",
"typescript": "^2.9.1", "typescript": "^2.9.1",
"webdriver-manager": "^12.1.6", "webdriver-manager": "^12.1.7",
"webpack": "^4.17.1", "webpack": "^4.17.1",
"webpack-bundle-analyzer": "^3.3.2", "webpack-bundle-analyzer": "^3.3.2",
"webpack-dev-middleware": "3.2.0", "webpack-dev-middleware": "3.2.0",

3220
resources/i18n/ar.json5 Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1610
resources/i18n/es.json5 Normal file

File diff suppressed because it is too large Load Diff

3220
resources/i18n/fi.json5 Normal file

File diff suppressed because it is too large Load Diff

3220
resources/i18n/fr.json5 Normal file

File diff suppressed because it is too large Load Diff

3220
resources/i18n/ja.json5 Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

3220
resources/i18n/pl.json5 Normal file

File diff suppressed because it is too large Load Diff

2457
resources/i18n/pt.json5 Normal file

File diff suppressed because it is too large Load Diff

3220
resources/i18n/sw.json5 Normal file

File diff suppressed because it is too large Load Diff

3220
resources/i18n/tr.json5 Normal file

File diff suppressed because it is too large Load Diff

342
scripts/sync-i18n-files.js Executable file
View File

@@ -0,0 +1,342 @@
#!/usr/bin/env node
const commander = require('commander');
const fs = require('fs');
const JSON5 = require('json5');
const _cliProgress = require('cli-progress');
const _ = require('lodash');
const {projectRoot} = require('../webpack/helpers');
const program = new commander.Command();
program.version('1.0.0', '-v, --version');
const NEW_MESSAGE_TODO = '// TODO New key - Add a translation';
const MESSAGE_CHANGED_TODO = '// TODO Source message changed - Revise the translation';
const COMMENTS_CHANGED_TODO = '// TODO Source comments changed - Revise the translation';
const DEFAULT_SOURCE_FILE_LOCATION = 'resources/i18n/en.json5';
const LANGUAGE_FILES_LOCATION = 'resources/i18n';
parseCliInput();
/**
* Parses the CLI input given by the user
* If no parameters are set (standard usage) -> source file is default (set to DEFAULT_SOURCE_FILE_LOCATION) and all
* other language files in the LANGUAGE_FILES_LOCATION are synced with this one in-place
* (replaced with newly synced file)
* If only target-file -t is set -> either -i in-place or -o output-file must be set
* Source file can be set with -s if it should be something else than DEFAULT_SOURCE_FILE_LOCATION
*
* If any of the paths to files/dirs given by user are not valid, an error message is printed and script gets aborted
*/
function parseCliInput() {
program
.option('-d, --output-dir <output-dir>', 'output dir when running script on all language files; mutually exclusive with -o')
.option('-t, --target-file <target>', 'target file we compare with and where completed output ends up if -o is not configured and -i is')
.option('-i, --edit-in-place', 'edit-in-place; store output straight in target file; mutually exclusive with -o')
.option('-s, --source-file <source>', 'source file to be parsed for translation', projectRoot(DEFAULT_SOURCE_FILE_LOCATION))
.option('-o, --output-file <output>', 'where output of script ends up; mutually exclusive with -i')
.usage('([-d <output-dir>] [-s <source-file>]) || (-t <target-file> (-i | -o <output>) [-s <source-file>])')
.parse(process.argv);
if (!program.targetFile) {
fs.readdirSync(projectRoot(LANGUAGE_FILES_LOCATION)).forEach(file => {
if (!program.sourceFile.toString().endsWith(file)) {
const targetFileLocation = projectRoot(LANGUAGE_FILES_LOCATION + "/" + file);
console.log('Syncing file at: ' + targetFileLocation + ' with source file at: ' + program.sourceFile);
if (program.outputDir) {
if (!fs.existsSync(program.outputDir)) {
fs.mkdirSync(program.outputDir);
}
const outputFileLocation = program.outputDir + "/" + file;
console.log('Output location: ' + outputFileLocation);
syncFileWithSource(targetFileLocation, outputFileLocation);
} else {
console.log('Replacing in target location');
syncFileWithSource(targetFileLocation, targetFileLocation);
}
}
});
} else {
if (program.targetFile && !checkIfPathToFileIsValid(program.targetFile)) {
console.error('Directory path of target file is not valid.');
console.log(program.outputHelp());
process.exit(1);
}
if (program.targetFile && checkIfFileExists(program.targetFile) && !(program.editInPlace || program.outputFile)) {
console.error('This target file already exists, if you want to overwrite this add option -i, or add an -o output location');
console.log(program.outputHelp());
process.exit(1);
}
if (!checkIfFileExists(program.sourceFile)) {
console.error('Path of source file is not valid.');
console.log(program.outputHelp());
process.exit(1);
}
if (program.outputFile && !checkIfPathToFileIsValid(program.outputFile)) {
console.error('Directory path of output file is not valid.');
console.log(program.outputHelp());
process.exit(1);
}
syncFileWithSource(program.targetFile, getOutputFileLocationIfExistsElseTargetFileLocation(program.targetFile));
}
}
/**
* Creates chunk lists for both the source and the target files (for example en.json5 and nl.json5 respectively)
* > Creates output chunks by comparing the source chunk with corresponding target chunk (based on key of translation)
* > Writes the output chunks to a new valid lang.json5 file, either replacing the target file (-i in-place)
* or sending it to an output file specified by the user
* @param pathToTargetFile Valid path to target file to generate target chunks from
* @param pathToOutputFile Valid path to output file to write output chunks to
*/
function syncFileWithSource(pathToTargetFile, pathToOutputFile) {
const progressBar = new _cliProgress.SingleBar({}, _cliProgress.Presets.shades_classic);
progressBar.start(100, 0);
const sourceLines = [];
const targetLines = [];
const existingTargetFile = readFileIfExists(pathToTargetFile);
existingTargetFile.toString().split("\n").forEach((function (line) {
targetLines.push(line.trim());
}));
progressBar.update(10);
const sourceFile = readFileIfExists(program.sourceFile);
sourceFile.toString().split("\n").forEach((function (line) {
sourceLines.push(line.trim());
}));
progressBar.update(20);
const sourceChunks = createChunks(sourceLines, progressBar, false);
const targetChunks = createChunks(targetLines, progressBar, true);
const outputChunks = compareChunksAndCreateOutput(sourceChunks, targetChunks, progressBar);
const file = fs.createWriteStream(pathToOutputFile);
file.on('error', function (err) {
console.error('Something went wrong writing to output file at: ' + pathToOutputFile + err)
});
file.on('open', function() {
file.write("{\n");
outputChunks.forEach(function (chunk) {
progressBar.increment();
chunk.split("\n").forEach(function (line) {
file.write(" " + line + "\n");
});
});
file.write("\n}");
file.end();
});
file.on('finish', function() {
const osName = process.platform;
if (osName.startsWith("win")) {
replaceLineEndingsToCRLF(pathToOutputFile);
}
});
progressBar.update(100);
progressBar.stop();
}
/**
* For each of the source chunks:
* - Determine if it's a new key-value => Add it to output, with source comments, source key-value commented, a message indicating it's new and the source-key value uncommented
* - If it's not new, compare it with the corresponding target chunk and log the differences, see createNewChunkComparingSourceAndTarget
* @param sourceChunks All the source chunks, split per key-value pair group
* @param targetChunks All the target chunks, split per key-value pair group
* @param progressBar The progressbar for the CLI
* @return {Array} All the output chunks, split per key-value pair group
*/
function compareChunksAndCreateOutput(sourceChunks, targetChunks, progressBar) {
const outputChunks = [];
sourceChunks.map((sourceChunk) => {
progressBar.increment();
if (sourceChunk.trim().length !== 0) {
let newChunk = [];
const sourceList = sourceChunk.split("\n");
const keyValueSource = sourceList[sourceList.length - 1];
const keySource = getSubStringBeforeLastString(keyValueSource, ":");
const commentSource = getSubStringBeforeLastString(sourceChunk, keyValueSource);
const correspondingTargetChunk = targetChunks.find((targetChunk) => {
return targetChunk.includes(keySource);
});
// Create new chunk with: the source comments, the commented source key-value, the todos and either the old target key-value pair or if it's a new pair, the source key-value pair
newChunk.push(removeWhiteLines(commentSource));
newChunk.push("// " + keyValueSource);
if (correspondingTargetChunk === undefined) {
newChunk.push(NEW_MESSAGE_TODO);
newChunk.push(keyValueSource);
} else {
createNewChunkComparingSourceAndTarget(correspondingTargetChunk, sourceChunk, commentSource, keyValueSource, newChunk);
}
outputChunks.push(newChunk.filter(Boolean).join("\n"));
} else {
outputChunks.push(sourceChunk);
}
});
return outputChunks;
}
/**
* If a corresponding target chunk is found:
* - If old key value is not found in comments > Assumed it is new key
* - If the target comments do not contain the source comments (because they have changed since last time) => Add comments changed message
* - If the key-value in the target comments is not the same as the source key-value (because it changes since last time) => Add message changed message
* - Add the old todos if they haven't been added already
* - End with the original target key-value
*/
function createNewChunkComparingSourceAndTarget(correspondingTargetChunk, sourceChunk, commentSource, keyValueSource, newChunk) {
let commentsOfSourceHaveChanged = false;
let messageOfSourceHasChanged = false;
const targetList = correspondingTargetChunk.split("\n");
const oldKeyValueInTargetComments = getSubStringWithRegex(correspondingTargetChunk, "\\s*\\/\\/\\s*\".*");
const keyValueTarget = targetList[targetList.length - 1];
if (oldKeyValueInTargetComments != null) {
const oldKeyValueUncommented = getSubStringWithRegex(oldKeyValueInTargetComments[0], "\".*")[0];
if (!(_.isEmpty(correspondingTargetChunk) && _.isEmpty(commentSource)) && !removeWhiteLines(correspondingTargetChunk).includes(removeWhiteLines(commentSource.trim()))) {
commentsOfSourceHaveChanged = true;
newChunk.push(COMMENTS_CHANGED_TODO);
}
const parsedOldKey = JSON5.stringify("{" + oldKeyValueUncommented + "}");
const parsedSourceKey = JSON5.stringify("{" + keyValueSource + "}");
if (!_.isEqual(parsedOldKey, parsedSourceKey)) {
messageOfSourceHasChanged = true;
newChunk.push(MESSAGE_CHANGED_TODO);
}
addOldTodosIfNeeded(targetList, newChunk, commentsOfSourceHaveChanged, messageOfSourceHasChanged);
}
newChunk.push(keyValueTarget);
}
// Adds old todos found in target comments if they've not been added already
function addOldTodosIfNeeded(targetList, newChunk, commentsOfSourceHaveChanged, messageOfSourceHasChanged) {
targetList.map((targetLine) => {
const foundTODO = getSubStringWithRegex(targetLine, "\\s*//\\s*TODO.*");
if (foundTODO != null) {
const todo = foundTODO[0];
if (!((todo.includes(COMMENTS_CHANGED_TODO) && commentsOfSourceHaveChanged)
|| (todo.includes(MESSAGE_CHANGED_TODO) && messageOfSourceHasChanged))) {
newChunk.push(todo);
}
}
});
}
/**
* Creates chunks from an array of lines, each chunk contains either an empty line or a grouping of comments with their corresponding key-value pair
* @param lines Array of lines, to be grouped into chunks
* @param progressBar Progressbar of the CLI
* @return {Array} Array of chunks, grouped by key-value and their corresponding comments or an empty line
*/
function createChunks(lines, progressBar, creatingTarget) {
const chunks = [];
let nextChunk = [];
let onMultiLineComment = false;
lines.map((line) => {
progressBar.increment();
if (line.length === 0) {
chunks.push(line);
}
if (isOneLineCommentLine(line)) {
nextChunk.push(line);
}
if (onMultiLineComment) {
nextChunk.push(line);
if (isEndOfMultiLineComment(line)) {
onMultiLineComment = false;
}
}
if (isStartOfMultiLineComment(line)) {
nextChunk.push(line);
onMultiLineComment = true;
}
if (isKeyValuePair(line)) {
nextChunk.push(line);
const newMessageLineIfExists = nextChunk.find((lineInChunk) => lineInChunk.trim().startsWith(NEW_MESSAGE_TODO));
if (newMessageLineIfExists === undefined || !creatingTarget) {
chunks.push(nextChunk.join("\n"));
}
nextChunk = [];
}
});
return chunks;
}
function readFileIfExists(pathToFile) {
if (checkIfFileExists(pathToFile)) {
try {
return fs.readFileSync(pathToFile, 'utf8');
} catch (e) {
console.error('Error:', e.stack);
}
}
return null;
}
function isOneLineCommentLine(line) {
return (line.startsWith("//"));
}
function isStartOfMultiLineComment(line) {
return (line.startsWith("/*"));
}
function isEndOfMultiLineComment(line) {
return (line.endsWith("*/"));
}
function isKeyValuePair(line) {
return (line.startsWith("\""));
}
function getSubStringWithRegex(string, regex) {
return string.match(regex);
}
function getSubStringBeforeLastString(string, char) {
const lastCharIndex = string.lastIndexOf(char);
return string.substr(0, lastCharIndex);
}
function getOutputFileLocationIfExistsElseTargetFileLocation(targetLocation) {
if (program.outputFile) {
return program.outputFile;
}
return targetLocation;
}
function checkIfPathToFileIsValid(pathToCheck) {
if (!pathToCheck.includes("/")) {
return true;
}
return checkIfFileExists(getPathOfDirectory(pathToCheck));
}
function checkIfFileExists(pathToCheck) {
return fs.existsSync(pathToCheck);
}
function getPathOfDirectory(pathToCheck) {
return getSubStringBeforeLastString(pathToCheck, "/");
}
function removeWhiteLines(string) {
return string.replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm, "")
}
/**
* Replaces UNIX \n LF line endings to windows \r\n CRLF line endings.
* @param filePath Path to file whose line endings are being converted
*/
function replaceLineEndingsToCRLF(filePath) {
const data = readFileIfExists(filePath);
const result = data.replace(/\n/g,"\r\n");
fs.writeFileSync(filePath, result, 'utf8');
}

View File

@@ -11,7 +11,6 @@ import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.serv
import { MockRouter } from '../../shared/mocks/mock-router'; import { MockRouter } from '../../shared/mocks/mock-router';
import { ChangeDetectorRef, NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectorRef, NO_ERRORS_SCHEMA } from '@angular/core';
import { of as observableOf } from 'rxjs/internal/observable/of'; import { of as observableOf } from 'rxjs/internal/observable/of';
import { RemoteData } from '../../core/data/remote-data';
import { ActivatedRouteStub } from '../../shared/testing/active-router-stub'; import { ActivatedRouteStub } from '../../shared/testing/active-router-stub';
import { Community } from '../../core/shared/community.model'; import { Community } from '../../core/shared/community.model';
import { Item } from '../../core/shared/item.model'; import { Item } from '../../core/shared/item.model';
@@ -19,6 +18,7 @@ import { ENV_CONFIG, GLOBAL_CONFIG } from '../../../config';
import { BrowseEntrySearchOptions } from '../../core/browse/browse-entry-search-options.model'; import { BrowseEntrySearchOptions } from '../../core/browse/browse-entry-search-options.model';
import { toRemoteData } from '../+browse-by-metadata-page/browse-by-metadata-page.component.spec'; import { toRemoteData } from '../+browse-by-metadata-page/browse-by-metadata-page.component.spec';
import { createSuccessfulRemoteDataObject$ } from '../../shared/testing/utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/testing/utils';
import { VarDirective } from '../../shared/utils/var.directive';
describe('BrowseByDatePageComponent', () => { describe('BrowseByDatePageComponent', () => {
let comp: BrowseByDatePageComponent; let comp: BrowseByDatePageComponent;
@@ -69,7 +69,7 @@ describe('BrowseByDatePageComponent', () => {
beforeEach(async(() => { beforeEach(async(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()],
declarations: [BrowseByDatePageComponent, EnumKeysPipe], declarations: [BrowseByDatePageComponent, EnumKeysPipe, VarDirective],
providers: [ providers: [
{ provide: GLOBAL_CONFIG, useValue: ENV_CONFIG }, { provide: GLOBAL_CONFIG, useValue: ENV_CONFIG },
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },

View File

@@ -82,7 +82,8 @@ export class BrowseByDatePageComponent extends BrowseByMetadataPageComponent {
const date = firstItemRD.payload.firstMetadataValue(metadataField); const date = firstItemRD.payload.firstMetadataValue(metadataField);
if (hasValue(date)) { if (hasValue(date)) {
const dateObj = new Date(date); const dateObj = new Date(date);
lowerLimit = dateObj.getFullYear(); // TODO: it appears that getFullYear (based on local time) is sometimes unreliable. Switching to UTC.
lowerLimit = dateObj.getUTCFullYear();
} }
} }
const options = []; const options = [];

View File

@@ -1,7 +1,31 @@
<div class="container"> <div class="container">
<div class="browse-by-metadata w-100"> <ng-container *ngVar="(parent$ | async) as parent">
<ng-container *ngIf="parent?.payload as parentContext">
<header class="comcol-header border-bottom mb-4 pb-4">
<!-- Parent Name -->
<ds-comcol-page-header [name]="parentContext.name">
</ds-comcol-page-header>
<!-- Handle -->
<ds-comcol-page-handle
[content]="parentContext.handle"
[title]="parentContext.type+'.page.handle'" >
</ds-comcol-page-handle>
<!-- Introductory text -->
<ds-comcol-page-content [content]="parentContext.introductoryText" [hasInnerHtml]="true">
</ds-comcol-page-content>
<!-- News -->
<ds-comcol-page-content [content]="parentContext.sidebarText" [hasInnerHtml]="true" [title]="'community.page.news'">
</ds-comcol-page-content>
</header>
<!-- Browse-By Links -->
<ds-comcol-page-browse-by [id]="parentContext.id" [contentType]="parentContext.type"></ds-comcol-page-browse-by>
</ng-container></ng-container>
<section class="comcol-page-browse-section">
<div class="browse-by-metadata w-100">
<ds-browse-by *ngIf="startsWithOptions" class="col-xs-12 w-100" <ds-browse-by *ngIf="startsWithOptions" class="col-xs-12 w-100"
title="{{'browse.title' | translate:{collection: (parent$ | async)?.payload?.name || '', field: 'browse.metadata.' + browseId | translate, value: (value)? '&quot;' + value + '&quot;': ''} }}" title="{{'browse.title' | translate:{collection: (parent$ | async)?.payload?.name || '', field: 'browse.metadata.' + browseId | translate, value: (value)? '&quot;' + value + '&quot;': ''} }}"
parentname="{{(parent$ | async)?.payload?.name || ''}}"
[objects$]="(items$ !== undefined)? items$ : browseEntries$" [objects$]="(items$ !== undefined)? items$ : browseEntries$"
[paginationConfig]="paginationConfig" [paginationConfig]="paginationConfig"
[sortConfig]="sortConfig" [sortConfig]="sortConfig"
@@ -15,4 +39,17 @@
</ds-browse-by> </ds-browse-by>
<ds-loading *ngIf="!startsWithOptions" message="{{'loading.browse-by-page' | translate}}"></ds-loading> <ds-loading *ngIf="!startsWithOptions" message="{{'loading.browse-by-page' | translate}}"></ds-loading>
</div> </div>
</section>
<ng-container *ngVar="(parent$ | async) as parent">
<ng-container *ngIf="parent?.payload as parentContext">
<footer *ngIf="parentContext.copyrightText" class="border-top my-5 pt-4">
<div >
<!-- Copyright -->
<ds-comcol-page-content [content]="parentContext.copyrightText" [hasInnerHtml]="true">
</ds-comcol-page-content>
</div>
</footer>
</ng-container>
</ng-container>
</div> </div>

View File

@@ -23,6 +23,7 @@ import { MockRouter } from '../../shared/mocks/mock-router';
import { ResourceType } from '../../core/shared/resource-type'; import { ResourceType } from '../../core/shared/resource-type';
import { createSuccessfulRemoteDataObject$ } from '../../shared/testing/utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/testing/utils';
import { BrowseEntry } from '../../core/shared/browse-entry.model'; import { BrowseEntry } from '../../core/shared/browse-entry.model';
import { VarDirective } from '../../shared/utils/var.directive';
describe('BrowseByMetadataPageComponent', () => { describe('BrowseByMetadataPageComponent', () => {
let comp: BrowseByMetadataPageComponent; let comp: BrowseByMetadataPageComponent;
@@ -86,7 +87,7 @@ describe('BrowseByMetadataPageComponent', () => {
beforeEach(async(() => { beforeEach(async(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()],
declarations: [BrowseByMetadataPageComponent, EnumKeysPipe], declarations: [BrowseByMetadataPageComponent, EnumKeysPipe, VarDirective],
providers: [ providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: BrowseService, useValue: mockBrowseService }, { provide: BrowseService, useValue: mockBrowseService },

View File

@@ -18,6 +18,7 @@ import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.serv
import { BrowseService } from '../../core/browse/browse.service'; import { BrowseService } from '../../core/browse/browse.service';
import { MockRouter } from '../../shared/mocks/mock-router'; import { MockRouter } from '../../shared/mocks/mock-router';
import { createSuccessfulRemoteDataObject$ } from '../../shared/testing/utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/testing/utils';
import { VarDirective } from '../../shared/utils/var.directive';
describe('BrowseByTitlePageComponent', () => { describe('BrowseByTitlePageComponent', () => {
let comp: BrowseByTitlePageComponent; let comp: BrowseByTitlePageComponent;
@@ -64,7 +65,7 @@ describe('BrowseByTitlePageComponent', () => {
beforeEach(async(() => { beforeEach(async(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()],
declarations: [BrowseByTitlePageComponent, EnumKeysPipe], declarations: [BrowseByTitlePageComponent, EnumKeysPipe, VarDirective],
providers: [ providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: BrowseService, useValue: mockBrowseService }, { provide: BrowseService, useValue: mockBrowseService },

View File

@@ -0,0 +1,57 @@
<div class="container">
<div class="row">
<div class="col-12">
<h2>{{'collection.edit.item-mapper.head' | translate}}</h2>
<p [innerHTML]="'collection.edit.item-mapper.collection' | translate:{ name: (collectionRD$ | async)?.payload?.name }" id="collection-name"></p>
<p>{{'collection.edit.item-mapper.description' | translate}}</p>
<ngb-tabset (tabChange)="tabChange($event)" [destroyOnHide]="true" #tabs="ngbTabset">
<ngb-tab title="{{'collection.edit.item-mapper.tabs.browse' | translate}}" id="browseTab">
<ng-template ngbTabContent>
<div class="mt-2">
<ds-item-select class="mt-2"
[key]="'browse'"
[dsoRD$]="collectionItemsRD$"
[paginationOptions]="(searchOptions$ | async)?.pagination"
[confirmButton]="'collection.edit.item-mapper.remove'"
[cancelButton]="'collection.edit.item-mapper.cancel'"
[dangerConfirm]="true"
[hideCollection]="true"
(confirm)="mapItems($event, true)"
(cancel)="onCancel()"></ds-item-select>
</div>
</ng-template>
</ngb-tab>
<ngb-tab title="{{'collection.edit.item-mapper.tabs.map' | translate}}" id="mapTab">
<ng-template ngbTabContent>
<div class="row mt-2">
<div class="col-12 col-lg-6">
<ds-search-form id="search-form"
[query]="(searchOptions$ | async)?.query"
[scope]="(searchOptions$ | async)?.scope"
[currentUrl]="'./'"
[inPlaceSearch]="true"
(submitSearch)="performedSearch = true">
</ds-search-form>
</div>
</div>
<div *ngIf="performedSearch">
<ds-item-select class="mt-2"
[key]="'map'"
[dsoRD$]="mappedItemsRD$"
[paginationOptions]="(searchOptions$ | async)?.pagination"
[confirmButton]="'collection.edit.item-mapper.confirm'"
[cancelButton]="'collection.edit.item-mapper.cancel'"
(confirm)="mapItems($event)"
(cancel)="onCancel()"></ds-item-select>
</div>
<div *ngIf="!performedSearch" class="alert alert-info w-100" role="alert">
{{'collection.edit.item-mapper.no-search' | translate}}
</div>
</ng-template>
</ngb-tab>
</ngb-tabset>
</div>
</div>
</div>

View File

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

View File

@@ -0,0 +1,214 @@
import { CollectionItemMapperComponent } from './collection-item-mapper.component';
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { CommonModule } from '@angular/common';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { SearchFormComponent } from '../../shared/search-form/search-form.component';
import { SearchPageModule } from '../../+search-page/search-page.module';
import { ObjectCollectionComponent } from '../../shared/object-collection/object-collection.component';
import { ActivatedRoute, Router } from '@angular/router';
import { ActivatedRouteStub } from '../../shared/testing/active-router-stub';
import { RouterStub } from '../../shared/testing/router-stub';
import { SearchConfigurationService } from '../../+search-page/search-service/search-configuration.service';
import { SearchService } from '../../+search-page/search-service/search.service';
import { SearchServiceStub } from '../../shared/testing/search-service-stub';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service-stub';
import { ItemDataService } from '../../core/data/item-data.service';
import { FormsModule } from '@angular/forms';
import { SharedModule } from '../../shared/shared.module';
import { Collection } from '../../core/shared/collection.model';
import { RemoteData } from '../../core/data/remote-data';
import { PaginatedSearchOptions } from '../../+search-page/paginated-search-options.model';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { EventEmitter, NgModule } from '@angular/core';
import { HostWindowService } from '../../shared/host-window.service';
import { HostWindowServiceStub } from '../../shared/testing/host-window-service-stub';
import { By } from '@angular/platform-browser';
import { PaginatedList } from '../../core/data/paginated-list';
import { PageInfo } from '../../core/shared/page-info.model';
import { CollectionDataService } from '../../core/data/collection-data.service';
import { PaginationComponent } from '../../shared/pagination/pagination.component';
import { EnumKeysPipe } from '../../shared/utils/enum-keys-pipe';
import { ItemSelectComponent } from '../../shared/object-select/item-select/item-select.component';
import { ObjectSelectService } from '../../shared/object-select/object-select.service';
import { ObjectSelectServiceStub } from '../../shared/testing/object-select-service-stub';
import { VarDirective } from '../../shared/utils/var.directive';
import { Observable } from 'rxjs/internal/Observable';
import { of as observableOf, of } from 'rxjs/internal/observable/of';
import { RestResponse } from '../../core/cache/response.models';
import { SearchFixedFilterService } from '../../+search-page/search-filters/search-filter/search-fixed-filter.service';
import { RouteService } from '../../core/services/route.service';
import { ErrorComponent } from '../../shared/error/error.component';
import { LoadingComponent } from '../../shared/loading/loading.component';
describe('CollectionItemMapperComponent', () => {
let comp: CollectionItemMapperComponent;
let fixture: ComponentFixture<CollectionItemMapperComponent>;
let route: ActivatedRoute;
let router: Router;
let searchConfigService: SearchConfigurationService;
let searchService: SearchService;
let notificationsService: NotificationsService;
let itemDataService: ItemDataService;
const mockCollection: Collection = Object.assign(new Collection(), {
id: 'ce41d451-97ed-4a9c-94a1-7de34f16a9f4',
name: 'test-collection'
});
const mockCollectionRD: RemoteData<Collection> = new RemoteData<Collection>(false, false, true, null, mockCollection);
const mockSearchOptions = of(new PaginatedSearchOptions({
pagination: Object.assign(new PaginationComponentOptions(), {
id: 'search-page-configuration',
pageSize: 10,
currentPage: 1
}),
sort: new SortOptions('dc.title', SortDirection.ASC),
scope: mockCollection.id
}));
const url = 'http://test.url';
const urlWithParam = url + '?param=value';
const routerStub = Object.assign(new RouterStub(), {
url: urlWithParam,
navigateByUrl: {},
navigate: {}
});
const searchConfigServiceStub = {
paginatedSearchOptions: mockSearchOptions
};
const itemDataServiceStub = {
mapToCollection: () => of(new RestResponse(true, 200, 'OK'))
};
const activatedRouteStub = new ActivatedRouteStub({}, { collection: mockCollectionRD });
const translateServiceStub = {
get: () => of('test-message of collection ' + mockCollection.name),
onLangChange: new EventEmitter(),
onTranslationChange: new EventEmitter(),
onDefaultLangChange: new EventEmitter()
};
const emptyList = new RemoteData(false, false, true, null, new PaginatedList(new PageInfo(), []));
const searchServiceStub = Object.assign(new SearchServiceStub(), {
search: () => of(emptyList),
/* tslint:disable:no-empty */
clearDiscoveryRequests: () => {}
/* tslint:enable:no-empty */
});
const collectionDataServiceStub = {
getMappedItems: () => of(emptyList),
/* tslint:disable:no-empty */
clearMappedItemsRequests: () => {}
/* tslint:enable:no-empty */
};
const routeServiceStub = {
getRouteParameterValue: () => {
return observableOf('');
},
getQueryParameterValue: () => {
return observableOf('')
},
getQueryParamsWithPrefix: () => {
return observableOf('')
}
};
const fixedFilterServiceStub = {
getQueryByFilterName: () => {
return observableOf('')
}
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CommonModule, FormsModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()],
declarations: [CollectionItemMapperComponent, ItemSelectComponent, SearchFormComponent, PaginationComponent, EnumKeysPipe, VarDirective, ErrorComponent, LoadingComponent],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: Router, useValue: routerStub },
{ provide: SearchConfigurationService, useValue: searchConfigServiceStub },
{ provide: SearchService, useValue: searchServiceStub },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: ItemDataService, useValue: itemDataServiceStub },
{ provide: CollectionDataService, useValue: collectionDataServiceStub },
{ provide: TranslateService, useValue: translateServiceStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: ObjectSelectService, useValue: new ObjectSelectServiceStub() },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: SearchFixedFilterService, useValue: fixedFilterServiceStub }
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CollectionItemMapperComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
route = (comp as any).route;
router = (comp as any).router;
searchConfigService = (comp as any).searchConfigService;
searchService = (comp as any).searchService;
notificationsService = (comp as any).notificationsService;
itemDataService = (comp as any).itemDataService;
});
it('should display the correct collection name', () => {
const name: HTMLElement = fixture.debugElement.query(By.css('#collection-name')).nativeElement;
expect(name.innerHTML).toContain(mockCollection.name);
});
describe('mapItems', () => {
const ids = ['id1', 'id2', 'id3', 'id4'];
it('should display a success message if at least one mapping was successful', () => {
comp.mapItems(ids);
expect(notificationsService.success).toHaveBeenCalled();
expect(notificationsService.error).not.toHaveBeenCalled();
});
it('should display an error message if at least one mapping was unsuccessful', () => {
spyOn(itemDataService, 'mapToCollection').and.returnValue(of(new RestResponse(false, 404, 'Not Found')));
comp.mapItems(ids);
expect(notificationsService.success).not.toHaveBeenCalled();
expect(notificationsService.error).toHaveBeenCalled();
});
});
describe('tabChange', () => {
beforeEach(() => {
spyOn(routerStub, 'navigateByUrl');
comp.tabChange({});
});
it('should navigate to the same page to remove parameters', () => {
expect(router.navigateByUrl).toHaveBeenCalledWith(url);
});
});
describe('buildQuery', () => {
const query = 'query';
const expected = `-location.coll:\"${mockCollection.id}\" AND ${query}`;
let result;
beforeEach(() => {
result = comp.buildQuery(mockCollection.id, query);
});
it('should build a solr query to exclude the provided collection', () => {
expect(result).toEqual(expected);
})
});
describe('onCancel', () => {
beforeEach(() => {
spyOn(routerStub, 'navigate');
comp.onCancel();
});
it('should navigate to the collection page', () => {
expect(router.navigate).toHaveBeenCalledWith(['/collections/', mockCollection.id]);
});
});
});

View File

@@ -0,0 +1,256 @@
import { combineLatest as observableCombineLatest, Observable } from 'rxjs';
import { ChangeDetectionStrategy, Component, Inject, OnInit, ViewChild } from '@angular/core';
import { fadeIn, fadeInOut } from '../../shared/animations/fade';
import { ActivatedRoute, Router } from '@angular/router';
import { RemoteData } from '../../core/data/remote-data';
import { Collection } from '../../core/shared/collection.model';
import { SearchConfigurationService } from '../../+search-page/search-service/search-configuration.service';
import { PaginatedSearchOptions } from '../../+search-page/paginated-search-options.model';
import { PaginatedList } from '../../core/data/paginated-list';
import { map, startWith, switchMap, take, tap } from 'rxjs/operators';
import { getRemoteDataPayload, getSucceededRemoteData, toDSpaceObjectListRD } from '../../core/shared/operators';
import { SearchService } from '../../+search-page/search-service/search.service';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { DSpaceObjectType } from '../../core/shared/dspace-object-type.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { ItemDataService } from '../../core/data/item-data.service';
import { TranslateService } from '@ngx-translate/core';
import { CollectionDataService } from '../../core/data/collection-data.service';
import { isNotEmpty } from '../../shared/empty.util';
import { RestResponse } from '../../core/cache/response.models';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component';
@Component({
selector: 'ds-collection-item-mapper',
styleUrls: ['./collection-item-mapper.component.scss'],
templateUrl: './collection-item-mapper.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
animations: [
fadeIn,
fadeInOut
],
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService
}
]
})
/**
* Component used to map items to a collection
*/
export class CollectionItemMapperComponent implements OnInit {
/**
* A view on the tabset element
* Used to switch tabs programmatically
*/
@ViewChild('tabs') tabs;
/**
* The collection to map items to
*/
collectionRD$: Observable<RemoteData<Collection>>;
/**
* Search options
*/
searchOptions$: Observable<PaginatedSearchOptions>;
/**
* List of items to show under the "Browse" tab
* Items inside the collection
*/
collectionItemsRD$: Observable<RemoteData<PaginatedList<DSpaceObject>>>;
/**
* List of items to show under the "Map" tab
* Items outside the collection
*/
mappedItemsRD$: Observable<RemoteData<PaginatedList<DSpaceObject>>>;
/**
* Sort on title ASC by default
* @type {SortOptions}
*/
defaultSortOptions: SortOptions = new SortOptions('dc.title', SortDirection.ASC);
/**
* Firing this observable (shouldUpdate$.next(true)) forces the two lists to reload themselves
* Usually fired after the lists their cache is cleared (to force a new request to the REST API)
*/
shouldUpdate$: BehaviorSubject<boolean>;
/**
* Track whether at least one search has been performed or not
* As soon as at least one search has been performed, we display the search results
*/
performedSearch = false;
constructor(private route: ActivatedRoute,
private router: Router,
@Inject(SEARCH_CONFIG_SERVICE) private searchConfigService: SearchConfigurationService,
private searchService: SearchService,
private notificationsService: NotificationsService,
private itemDataService: ItemDataService,
private collectionDataService: CollectionDataService,
private translateService: TranslateService) {
}
ngOnInit(): void {
this.collectionRD$ = this.route.data.pipe(map((data) => data.collection)).pipe(getSucceededRemoteData()) as Observable<RemoteData<Collection>>;
this.searchOptions$ = this.searchConfigService.paginatedSearchOptions;
this.loadItemLists();
}
/**
* Load collectionItemsRD$ with a fixed scope to only obtain the items this collection owns
* Load mappedItemsRD$ to only obtain items this collection doesn't own
*/
loadItemLists() {
this.shouldUpdate$ = new BehaviorSubject<boolean>(true);
const collectionAndOptions$ = observableCombineLatest(
this.collectionRD$,
this.searchOptions$,
this.shouldUpdate$
);
this.collectionItemsRD$ = collectionAndOptions$.pipe(
switchMap(([collectionRD, options, shouldUpdate]) => {
if (shouldUpdate) {
return this.collectionDataService.getMappedItems(collectionRD.payload.id, Object.assign(options, {
sort: this.defaultSortOptions
}))
}
})
);
this.mappedItemsRD$ = collectionAndOptions$.pipe(
switchMap(([collectionRD, options, shouldUpdate]) => {
if (shouldUpdate) {
return this.searchService.search(Object.assign(new PaginatedSearchOptions(options), {
query: this.buildQuery(collectionRD.payload.id, options.query),
scope: undefined,
dsoType: DSpaceObjectType.ITEM,
sort: this.defaultSortOptions
}), 10000).pipe(
toDSpaceObjectListRD(),
startWith(undefined)
);
}
})
);
}
/**
* Map/Unmap the selected items to the collection and display notifications
* @param ids The list of item UUID's to map/unmap to the collection
* @param remove Whether or not it's supposed to remove mappings
*/
mapItems(ids: string[], remove?: boolean) {
const responses$ = this.collectionRD$.pipe(
getSucceededRemoteData(),
map((collectionRD: RemoteData<Collection>) => collectionRD.payload),
switchMap((collection: Collection) =>
observableCombineLatest(ids.map((id: string) =>
remove ? this.itemDataService.removeMappingFromCollection(id, collection.id) : this.itemDataService.mapToCollection(id, collection.self)
))
)
);
this.showNotifications(responses$, remove);
}
/**
* Display notifications
* @param {Observable<RestResponse[]>} responses$ The responses after adding/removing a mapping
* @param {boolean} remove Whether or not the goal was to remove mappings
*/
private showNotifications(responses$: Observable<RestResponse[]>, remove?: boolean) {
const messageInsertion = remove ? 'unmap' : 'map';
responses$.subscribe((responses: RestResponse[]) => {
const successful = responses.filter((response: RestResponse) => response.isSuccessful);
const unsuccessful = responses.filter((response: RestResponse) => !response.isSuccessful);
if (successful.length > 0) {
const successMessages = observableCombineLatest(
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.success.head`),
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.success.content`, { amount: successful.length })
);
successMessages.subscribe(([head, content]) => {
this.notificationsService.success(head, content);
});
}
if (unsuccessful.length > 0) {
const unsuccessMessages = observableCombineLatest(
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.error.head`),
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.error.content`, { amount: unsuccessful.length })
);
unsuccessMessages.subscribe(([head, content]) => {
this.notificationsService.error(head, content);
});
}
// Force an update on all lists and switch back to the first tab
this.shouldUpdate$.next(true);
this.switchToFirstTab();
});
}
/**
* Clear url parameters on tab change (temporary fix until pagination is improved)
* @param event
*/
tabChange(event) {
this.performedSearch = false;
this.router.navigateByUrl(this.getCurrentUrl());
}
/**
* Get current url without parameters
* @returns {string}
*/
getCurrentUrl(): string {
if (this.router.url.indexOf('?') > -1) {
return this.router.url.substring(0, this.router.url.indexOf('?'));
}
return this.router.url;
}
/**
* Build a query where items that are already mapped to a collection are excluded from
* @param collectionId The collection's UUID
* @param query The query to add to it
*/
buildQuery(collectionId: string, query: string): string {
const excludeColQuery = `-location.coll:\"${collectionId}\"`;
if (isNotEmpty(query)) {
return `${excludeColQuery} AND ${query}`;
} else {
return excludeColQuery;
}
}
/**
* Switch the view to focus on the first tab
*/
switchToFirstTab() {
this.tabs.select('browseTab');
}
/**
* When a cancel event is fired, return to the collection page
*/
onCancel() {
this.collectionRD$.pipe(
getSucceededRemoteData(),
getRemoteDataPayload(),
take(1)
).subscribe((collection: Collection) => {
this.router.navigate(['/collections/', collection.id])
});
}
}

View File

@@ -11,6 +11,7 @@ import { URLCombiner } from '../core/url-combiner/url-combiner';
import { getCollectionModulePath } from '../app-routing.module'; import { getCollectionModulePath } from '../app-routing.module';
import { EditItemTemplatePageComponent } from './edit-item-template-page/edit-item-template-page.component'; import { EditItemTemplatePageComponent } from './edit-item-template-page/edit-item-template-page.component';
import { ItemTemplatePageResolver } from './edit-item-template-page/item-template-page.resolver'; import { ItemTemplatePageResolver } from './edit-item-template-page/item-template-page.resolver';
import { CollectionItemMapperComponent } from './collection-item-mapper/collection-item-mapper.component';
export const COLLECTION_PARENT_PARAMETER = 'parent'; export const COLLECTION_PARENT_PARAMETER = 'parent';
@@ -68,6 +69,15 @@ const ITEMTEMPLATE_PATH = ':id/itemtemplate';
resolve: { resolve: {
collection: CollectionPageResolver collection: CollectionPageResolver
} }
},
{
path: ':id/edit/mapper',
component: CollectionItemMapperComponent,
pathMatch: 'full',
resolve: {
collection: CollectionPageResolver
},
canActivate: [AuthenticatedGuard]
} }
]) ])
], ],

View File

@@ -3,18 +3,22 @@
*ngVar="(collectionRD$ | async) as collectionRD"> *ngVar="(collectionRD$ | async) as collectionRD">
<div *ngIf="collectionRD?.hasSucceeded" @fadeInOut> <div *ngIf="collectionRD?.hasSucceeded" @fadeInOut>
<div *ngIf="collectionRD?.payload as collection"> <div *ngIf="collectionRD?.payload as collection">
<header class="comcol-header border-bottom mb-4 pb-4">
<!-- Collection logo -->
<ds-comcol-page-logo *ngIf="logoRD$"
[logo]="(logoRD$ | async)?.payload" [alternateText]="'Collection Logo'">
[alternateText]="'Collection Logo'">
</ds-comcol-page-logo>
<!-- Collection Name --> <!-- Collection Name -->
<ds-comcol-page-header <ds-comcol-page-header
[name]="collection.name"> [name]="collection.name">
</ds-comcol-page-header> </ds-comcol-page-header>
<!-- Browse-By Links --> <!-- Handle -->
<ds-comcol-page-browse-by [id]="collection.id"></ds-comcol-page-browse-by> <ds-comcol-page-handle
<!-- Collection logo --> [content]="collection.handle"
<ds-comcol-page-logo *ngIf="logoRD$" [title]="'collection.page.handle'" >
[logo]="(logoRD$ | async)?.payload" </ds-comcol-page-handle>
[alternateText]="'Collection Logo'"> <!-- Introductory text -->
</ds-comcol-page-logo>
<!-- Introductionary text -->
<ds-comcol-page-content <ds-comcol-page-content
[content]="collection.introductoryText" [content]="collection.introductoryText"
[hasInnerHtml]="true"> [hasInnerHtml]="true">
@@ -23,23 +27,20 @@
<ds-comcol-page-content <ds-comcol-page-content
[content]="collection.sidebarText" [content]="collection.sidebarText"
[hasInnerHtml]="true" [hasInnerHtml]="true"
[title]="'community.page.news'"> [title]="'collection.page.news'">
</ds-comcol-page-content> </ds-comcol-page-content>
<!-- Copyright -->
<ds-comcol-page-content </header>
[content]="collection.copyrightText" <section class="comcol-page-browse-section">
[hasInnerHtml]="true"> <!-- Browse-By Links -->
</ds-comcol-page-content> <ds-comcol-page-browse-by
<!-- Licence --> [id]="collection.id"
<ds-comcol-page-content [contentType]="collection.type">
[content]="collection.dcLicense" </ds-comcol-page-browse-by>
[title]="'collection.page.license'">
</ds-comcol-page-content>
</div>
<br>
<ng-container *ngVar="(itemRD$ | async) as itemRD"> <ng-container *ngVar="(itemRD$ | async) as itemRD">
<div *ngIf="itemRD?.hasSucceeded" @fadeIn> <div class="mt-4" *ngIf="itemRD?.hasSucceeded" @fadeIn>
<h2>{{'collection.page.browse.recent.head' | translate}}</h2> <h3 class="sr-only">{{'collection.page.browse.recent.head' | translate}}</h3>
<ds-viewable-collection <ds-viewable-collection
[config]="paginationConfig" [config]="paginationConfig"
[sortConfig]="sortConfig" [sortConfig]="sortConfig"
@@ -56,10 +57,19 @@
{{'collection.page.browse.recent.empty' | translate}} {{'collection.page.browse.recent.empty' | translate}}
</div> </div>
</ng-container> </ng-container>
</div> </section>
<ds-error *ngIf="collectionRD?.hasFailed" <footer *ngIf="collection.copyrightText" class="border-top my-5 pt-4">
message="{{'error.collection' | translate}}"></ds-error> <!-- Copyright -->
<ds-loading *ngIf="collectionRD?.isLoading" <ds-comcol-page-content
message="{{'loading.collection' | translate}}"></ds-loading> [content]="collection.copyrightText"
[hasInnerHtml]="true">
</ds-comcol-page-content>
</footer>
</div>
</div> </div>
<ds-error *ngIf="collectionRD?.hasFailed"
message="{{'error.collection' | translate}}"></ds-error>
<ds-loading *ngIf="collectionRD?.isLoading"
message="{{'loading.collection' | translate}}"></ds-loading>
</div>
</div> </div>

View File

@@ -11,26 +11,30 @@ import { DeleteCollectionPageComponent } from './delete-collection-page/delete-c
import { SearchService } from '../+search-page/search-service/search.service'; import { SearchService } from '../+search-page/search-service/search.service';
import { EditItemTemplatePageComponent } from './edit-item-template-page/edit-item-template-page.component'; import { EditItemTemplatePageComponent } from './edit-item-template-page/edit-item-template-page.component';
import { EditItemPageModule } from '../+item-page/edit-item-page/edit-item-page.module'; import { EditItemPageModule } from '../+item-page/edit-item-page/edit-item-page.module';
import { CollectionItemMapperComponent } from './collection-item-mapper/collection-item-mapper.component';
import { SearchFixedFilterService } from '../+search-page/search-filters/search-filter/search-fixed-filter.service';
@NgModule({ @NgModule({
imports: [ imports: [
CommonModule, CommonModule,
SharedModule, SharedModule,
EditItemPageModule, CollectionPageRoutingModule,
CollectionPageRoutingModule EditItemPageModule
], ],
declarations: [ declarations: [
CollectionPageComponent, CollectionPageComponent,
CreateCollectionPageComponent, CreateCollectionPageComponent,
DeleteCollectionPageComponent, DeleteCollectionPageComponent,
CollectionFormComponent, CollectionFormComponent,
EditItemTemplatePageComponent EditItemTemplatePageComponent,
CollectionItemMapperComponent
], ],
exports: [ exports: [
CollectionFormComponent CollectionFormComponent
], ],
providers: [ providers: [
SearchService SearchService,
SearchFixedFilterService
] ]
}) })
export class CollectionPageModule { export class CollectionPageModule {

View File

@@ -1,33 +1,38 @@
<div class="container" *ngVar="(communityRD$ | async) as communityRD"> <div class="container" *ngVar="(communityRD$ | async) as communityRD">
<div class="community-page" *ngIf="communityRD?.hasSucceeded" @fadeInOut> <div class="community-page" *ngIf="communityRD?.hasSucceeded" @fadeInOut>
<div *ngIf="communityRD?.payload; let communityPayload"> <div *ngIf="communityRD?.payload; let communityPayload">
<!-- Community name --> <header class="comcol-header border-bottom mb-4 pb-4">
<ds-comcol-page-header [name]="communityPayload.name"></ds-comcol-page-header> <!-- Community logo -->
<!-- Browse-By Links --> <ds-comcol-page-logo *ngIf="logoRD$" [logo]="(logoRD$ | async)?.payload" [alternateText]="'Community Logo'">
<ds-comcol-page-browse-by [id]="communityPayload.id"></ds-comcol-page-browse-by> </ds-comcol-page-logo>
<!-- Community logo -->
<ds-comcol-page-logo *ngIf="logoRD$" <!-- Community name -->
[logo]="(logoRD$ | async)?.payload" <ds-comcol-page-header [name]="communityPayload.name"></ds-comcol-page-header>
[alternateText]="'Community Logo'"> <!-- Handle -->
</ds-comcol-page-logo> <ds-comcol-page-handle [content]="communityPayload.handle" [title]="'community.page.handle'">
<!-- Introductory text --> </ds-comcol-page-handle>
<ds-comcol-page-content <!-- Introductory text -->
[content]="communityPayload.introductoryText" <ds-comcol-page-content [content]="communityPayload.introductoryText" [hasInnerHtml]="true">
[hasInnerHtml]="true"> </ds-comcol-page-content>
</ds-comcol-page-content> <!-- News -->
<!-- News --> <ds-comcol-page-content [content]="communityPayload.sidebarText" [hasInnerHtml]="true"
<ds-comcol-page-content [title]="'community.page.news'">
[content]="communityPayload.sidebarText" </ds-comcol-page-content>
[hasInnerHtml]="true"
[title]="'community.page.news'"> </header>
</ds-comcol-page-content> <section class="comcol-page-browse-section">
<!-- Copyright --> <!-- Browse-By Links -->
<ds-comcol-page-content <ds-comcol-page-browse-by [id]="communityPayload.id" [contentType]="communityPayload.type">
[content]="communityPayload.copyrightText" </ds-comcol-page-browse-by>
[hasInnerHtml]="true">
</ds-comcol-page-content> <ds-community-page-sub-community-list [community]="communityPayload"></ds-community-page-sub-community-list>
<ds-community-page-sub-community-list [community]="communityPayload"></ds-community-page-sub-community-list> <ds-community-page-sub-collection-list [community]="communityPayload"></ds-community-page-sub-collection-list>
<ds-community-page-sub-collection-list [community]="communityPayload"></ds-community-page-sub-collection-list> </section>
<footer *ngIf="communityPayload.copyrightText" class="border-top my-5 pt-4">
<!-- Copyright -->
<ds-comcol-page-content [content]="communityPayload.copyrightText" [hasInnerHtml]="true">
</ds-comcol-page-content>
</footer>
</div> </div>
</div> </div>

View File

@@ -15,6 +15,8 @@ import { ItemDeleteComponent } from './item-delete/item-delete.component';
import { ItemMetadataComponent } from './item-metadata/item-metadata.component'; import { ItemMetadataComponent } from './item-metadata/item-metadata.component';
import { EditInPlaceFieldComponent } from './item-metadata/edit-in-place-field/edit-in-place-field.component'; import { EditInPlaceFieldComponent } from './item-metadata/edit-in-place-field/edit-in-place-field.component';
import { ItemBitstreamsComponent } from './item-bitstreams/item-bitstreams.component'; import { ItemBitstreamsComponent } from './item-bitstreams/item-bitstreams.component';
import { SearchPageModule } from '../../+search-page/search-page.module';
import { ItemCollectionMapperComponent } from './item-collection-mapper/item-collection-mapper.component';
import { ItemRelationshipsComponent } from './item-relationships/item-relationships.component'; import { ItemRelationshipsComponent } from './item-relationships/item-relationships.component';
import { EditRelationshipComponent } from './item-relationships/edit-relationship/edit-relationship.component'; import { EditRelationshipComponent } from './item-relationships/edit-relationship/edit-relationship.component';
import { EditRelationshipListComponent } from './item-relationships/edit-relationship-list/edit-relationship-list.component'; import { EditRelationshipListComponent } from './item-relationships/edit-relationship-list/edit-relationship-list.component';
@@ -27,7 +29,8 @@ import { ItemMoveComponent } from './item-move/item-move.component';
imports: [ imports: [
CommonModule, CommonModule,
SharedModule, SharedModule,
EditItemPageRoutingModule EditItemPageRoutingModule,
SearchPageModule
], ],
declarations: [ declarations: [
EditItemPageComponent, EditItemPageComponent,
@@ -46,6 +49,7 @@ import { ItemMoveComponent } from './item-move/item-move.component';
EditInPlaceFieldComponent, EditInPlaceFieldComponent,
EditRelationshipComponent, EditRelationshipComponent,
EditRelationshipListComponent, EditRelationshipListComponent,
ItemCollectionMapperComponent,
ItemMoveComponent, ItemMoveComponent,
], ],
exports: [ exports: [

View File

@@ -10,6 +10,7 @@ import { ItemDeleteComponent } from './item-delete/item-delete.component';
import { ItemStatusComponent } from './item-status/item-status.component'; import { ItemStatusComponent } from './item-status/item-status.component';
import { ItemMetadataComponent } from './item-metadata/item-metadata.component'; import { ItemMetadataComponent } from './item-metadata/item-metadata.component';
import { ItemBitstreamsComponent } from './item-bitstreams/item-bitstreams.component'; import { ItemBitstreamsComponent } from './item-bitstreams/item-bitstreams.component';
import { ItemCollectionMapperComponent } from './item-collection-mapper/item-collection-mapper.component';
import { ItemMoveComponent } from './item-move/item-move.component'; import { ItemMoveComponent } from './item-move/item-move.component';
import { ItemRelationshipsComponent } from './item-relationships/item-relationships.component'; import { ItemRelationshipsComponent } from './item-relationships/item-relationships.component';
@@ -72,6 +73,13 @@ const ITEM_EDIT_MOVE_PATH = 'move';
}, },
] ]
}, },
{
path: 'mapper',
component: ItemCollectionMapperComponent,
resolve: {
item: ItemPageResolver
}
},
{ {
path: ITEM_EDIT_WITHDRAW_PATH, path: ITEM_EDIT_WITHDRAW_PATH,
component: ItemWithdrawComponent, component: ItemWithdrawComponent,

View File

@@ -0,0 +1,56 @@
<div class="container">
<div class="row">
<div class="col-12">
<h2>{{'item.edit.item-mapper.head' | translate}}</h2>
<p [innerHTML]="'item.edit.item-mapper.item' | translate:{ name: (itemRD$ | async)?.payload?.name }" id="item-name"></p>
<p>{{'item.edit.item-mapper.description' | translate}}</p>
<ngb-tabset (tabChange)="tabChange($event)" [destroyOnHide]="true" #tabs="ngbTabset">
<ngb-tab title="{{'item.edit.item-mapper.tabs.browse' | translate}}" id="browseTab">
<ng-template ngbTabContent>
<div class="mt-2">
<ds-collection-select class="mt-2"
[key]="'browse'"
[dsoRD$]="itemCollectionsRD$"
[paginationOptions]="(searchOptions$ | async)?.pagination"
[confirmButton]="'item.edit.item-mapper.buttons.remove'"
[cancelButton]="'item.edit.item-mapper.cancel'"
[dangerConfirm]="true"
(confirm)="removeMappings($event)"
(cancel)="onCancel()"></ds-collection-select>
</div>
</ng-template>
</ngb-tab>
<ngb-tab title="{{'item.edit.item-mapper.tabs.map' | translate}}" id="mapTab">
<ng-template ngbTabContent>
<div class="row mt-2">
<div class="col-12 col-lg-6">
<ds-search-form id="search-form"
[query]="(searchOptions$ | async)?.query"
[currentUrl]="'./'"
[inPlaceSearch]="true"
(submitSearch)="performedSearch = true">
</ds-search-form>
</div>
</div>
<div *ngIf="performedSearch">
<ds-collection-select class="mt-2"
[key]="'map'"
[dsoRD$]="mappedCollectionsRD$"
[paginationOptions]="(searchOptions$ | async)?.pagination"
[sortOptions]="(searchOptions$ | async)?.sort"
[confirmButton]="'item.edit.item-mapper.buttons.add'"
[cancelButton]="'item.edit.item-mapper.cancel'"
(confirm)="mapCollections($event)"
(cancel)="onCancel()"></ds-collection-select>
</div>
<div *ngIf="!performedSearch" class="alert alert-info w-100" role="alert">
{{'item.edit.item-mapper.no-search' | translate}}
</div>
</ng-template>
</ngb-tab>
</ngb-tabset>
</div>
</div>
</div>

View File

@@ -0,0 +1,207 @@
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { CommonModule } from '@angular/common';
import { ItemCollectionMapperComponent } from './item-collection-mapper.component';
import { ActivatedRoute, Router } from '@angular/router';
import { SearchConfigurationService } from '../../../+search-page/search-service/search-configuration.service';
import { SearchService } from '../../../+search-page/search-service/search.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { ItemDataService } from '../../../core/data/item-data.service';
import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedSearchOptions } from '../../../+search-page/paginated-search-options.model';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
import { RouterStub } from '../../../shared/testing/router-stub';
import { ActivatedRouteStub } from '../../../shared/testing/active-router-stub';
import { EventEmitter } from '@angular/core';
import { SearchServiceStub } from '../../../shared/testing/search-service-stub';
import { PaginatedList } from '../../../core/data/paginated-list';
import { PageInfo } from '../../../core/shared/page-info.model';
import { FormsModule } from '@angular/forms';
import { SharedModule } from '../../../shared/shared.module';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service-stub';
import { HostWindowService } from '../../../shared/host-window.service';
import { HostWindowServiceStub } from '../../../shared/testing/host-window-service-stub';
import { By } from '@angular/platform-browser';
import { Item } from '../../../core/shared/item.model';
import { ObjectSelectService } from '../../../shared/object-select/object-select.service';
import { ObjectSelectServiceStub } from '../../../shared/testing/object-select-service-stub';
import { Observable } from 'rxjs/internal/Observable';
import { of } from 'rxjs/internal/observable/of';
import { RestResponse } from '../../../core/cache/response.models';
import { CollectionSelectComponent } from '../../../shared/object-select/collection-select/collection-select.component';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { EnumKeysPipe } from '../../../shared/utils/enum-keys-pipe';
import { VarDirective } from '../../../shared/utils/var.directive';
import { SearchFormComponent } from '../../../shared/search-form/search-form.component';
import { Collection } from '../../../core/shared/collection.model';
import { ErrorComponent } from '../../../shared/error/error.component';
import { LoadingComponent } from '../../../shared/loading/loading.component';
describe('ItemCollectionMapperComponent', () => {
let comp: ItemCollectionMapperComponent;
let fixture: ComponentFixture<ItemCollectionMapperComponent>;
let route: ActivatedRoute;
let router: Router;
let searchConfigService: SearchConfigurationService;
let searchService: SearchService;
let notificationsService: NotificationsService;
let itemDataService: ItemDataService;
const mockCollection = Object.assign(new Collection(), { id: 'collection1' });
const mockItem: Item = Object.assign(new Item(), {
id: '932c7d50-d85a-44cb-b9dc-b427b12877bd',
name: 'test-item'
});
const mockItemRD: RemoteData<Item> = new RemoteData<Item>(false, false, true, null, mockItem);
const mockSearchOptions = of(new PaginatedSearchOptions({
pagination: Object.assign(new PaginationComponentOptions(), {
id: 'search-page-configuration',
pageSize: 10,
currentPage: 1
}),
sort: new SortOptions('dc.title', SortDirection.ASC)
}));
const url = 'http://test.url';
const urlWithParam = url + '?param=value';
const routerStub = Object.assign(new RouterStub(), {
url: urlWithParam,
navigateByUrl: {},
navigate: {}
});
const searchConfigServiceStub = {
paginatedSearchOptions: mockSearchOptions
};
const mockCollectionsRD = new RemoteData(false, false, true, null, new PaginatedList(new PageInfo(), []));
const itemDataServiceStub = {
mapToCollection: () => of(new RestResponse(true, 200, 'OK')),
removeMappingFromCollection: () => of(new RestResponse(true, 200, 'OK')),
getMappedCollections: () => of(mockCollectionsRD),
/* tslint:disable:no-empty */
clearMappedCollectionsRequests: () => {}
/* tslint:enable:no-empty */
};
const searchServiceStub = Object.assign(new SearchServiceStub(), {
search: () => of(mockCollectionsRD),
/* tslint:disable:no-empty */
clearDiscoveryRequests: () => {}
/* tslint:enable:no-empty */
});
const activatedRouteStub = new ActivatedRouteStub({}, { item: mockItemRD });
const translateServiceStub = {
get: () => of('test-message of item ' + mockItem.name),
onLangChange: new EventEmitter(),
onTranslationChange: new EventEmitter(),
onDefaultLangChange: new EventEmitter()
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CommonModule, FormsModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule.forRoot()],
declarations: [ItemCollectionMapperComponent, CollectionSelectComponent, SearchFormComponent, PaginationComponent, EnumKeysPipe, VarDirective, ErrorComponent, LoadingComponent],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: Router, useValue: routerStub },
{ provide: SearchConfigurationService, useValue: searchConfigServiceStub },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: ItemDataService, useValue: itemDataServiceStub },
{ provide: SearchService, useValue: searchServiceStub },
{ provide: ObjectSelectService, useValue: new ObjectSelectServiceStub() },
{ provide: TranslateService, useValue: translateServiceStub },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ItemCollectionMapperComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
route = (comp as any).route;
router = (comp as any).router;
searchConfigService = (comp as any).searchConfigService;
notificationsService = (comp as any).notificationsService;
itemDataService = (comp as any).itemDataService;
searchService = (comp as any).searchService;
});
it('should display the correct collection name', () => {
const name: HTMLElement = fixture.debugElement.query(By.css('#item-name')).nativeElement;
expect(name.innerHTML).toContain(mockItem.name);
});
describe('mapCollections', () => {
const ids = ['id1', 'id2', 'id3', 'id4'];
it('should display a success message if at least one mapping was successful', () => {
comp.mapCollections(ids);
expect(notificationsService.success).toHaveBeenCalled();
expect(notificationsService.error).not.toHaveBeenCalled();
});
it('should display an error message if at least one mapping was unsuccessful', () => {
spyOn(itemDataService, 'mapToCollection').and.returnValue(of(new RestResponse(false, 404, 'Not Found')));
comp.mapCollections(ids);
expect(notificationsService.success).not.toHaveBeenCalled();
expect(notificationsService.error).toHaveBeenCalled();
});
});
describe('removeMappings', () => {
const ids = ['id1', 'id2', 'id3', 'id4'];
it('should display a success message if the removal of at least one mapping was successful', () => {
comp.removeMappings(ids);
expect(notificationsService.success).toHaveBeenCalled();
expect(notificationsService.error).not.toHaveBeenCalled();
});
it('should display an error message if the removal of at least one mapping was unsuccessful', () => {
spyOn(itemDataService, 'removeMappingFromCollection').and.returnValue(of(new RestResponse(false, 404, 'Not Found')));
comp.removeMappings(ids);
expect(notificationsService.success).not.toHaveBeenCalled();
expect(notificationsService.error).toHaveBeenCalled();
});
});
describe('tabChange', () => {
beforeEach(() => {
spyOn(routerStub, 'navigateByUrl');
comp.tabChange({});
});
it('should navigate to the same page to remove parameters', () => {
expect(router.navigateByUrl).toHaveBeenCalledWith(url);
});
});
describe('buildQuery', () => {
const query = 'query';
const expected = `${query} AND -search.resourceid:${mockCollection.id}`;
let result;
beforeEach(() => {
result = comp.buildQuery([mockCollection], query);
});
it('should build a solr query to exclude the provided collection', () => {
expect(result).toEqual(expected);
})
});
describe('onCancel', () => {
beforeEach(() => {
spyOn(routerStub, 'navigate');
comp.onCancel();
});
it('should navigate to the item page', () => {
expect(router.navigate).toHaveBeenCalledWith(['/items/', mockItem.id]);
});
});
});

View File

@@ -0,0 +1,283 @@
import { combineLatest as observableCombineLatest, Observable } from 'rxjs';
import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { fadeIn, fadeInOut } from '../../../shared/animations/fade';
import { PaginatedSearchOptions } from '../../../+search-page/paginated-search-options.model';
import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list';
import { Collection } from '../../../core/shared/collection.model';
import { Item } from '../../../core/shared/item.model';
import { getRemoteDataPayload, getSucceededRemoteData, toDSpaceObjectListRD } from '../../../core/shared/operators';
import { ActivatedRoute, Router } from '@angular/router';
import { SearchService } from '../../../+search-page/search-service/search.service';
import { SearchConfigurationService } from '../../../+search-page/search-service/search-configuration.service';
import { map, startWith, switchMap, take } from 'rxjs/operators';
import { ItemDataService } from '../../../core/data/item-data.service';
import { TranslateService } from '@ngx-translate/core';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { DSpaceObjectType } from '../../../core/shared/dspace-object-type.model';
import { isNotEmpty } from '../../../shared/empty.util';
import { RestResponse } from '../../../core/cache/response.models';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
@Component({
selector: 'ds-item-collection-mapper',
styleUrls: ['./item-collection-mapper.component.scss'],
templateUrl: './item-collection-mapper.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
animations: [
fadeIn,
fadeInOut
]
})
/**
* Component for mapping collections to an item
*/
export class ItemCollectionMapperComponent implements OnInit {
/**
* A view on the tabset element
* Used to switch tabs programmatically
*/
@ViewChild('tabs') tabs;
/**
* The item to map to collections
*/
itemRD$: Observable<RemoteData<Item>>;
/**
* Search options
*/
searchOptions$: Observable<PaginatedSearchOptions>;
/**
* List of collections to show under the "Browse" tab
* Collections that are mapped to the item
*/
itemCollectionsRD$: Observable<RemoteData<PaginatedList<Collection>>>;
/**
* List of collections to show under the "Map" tab
* Collections that are not mapped to the item
*/
mappedCollectionsRD$: Observable<RemoteData<PaginatedList<Collection>>>;
/**
* Firing this observable (shouldUpdate$.next(true)) forces the two lists to reload themselves
* Usually fired after the lists their cache is cleared (to force a new request to the REST API)
*/
shouldUpdate$: BehaviorSubject<boolean>;
/**
* Track whether at least one search has been performed or not
* As soon as at least one search has been performed, we display the search results
*/
performedSearch = false;
constructor(private route: ActivatedRoute,
private router: Router,
private searchConfigService: SearchConfigurationService,
private searchService: SearchService,
private notificationsService: NotificationsService,
private itemDataService: ItemDataService,
private translateService: TranslateService) {
}
ngOnInit(): void {
this.itemRD$ = this.route.data.pipe(map((data) => data.item)).pipe(getSucceededRemoteData()) as Observable<RemoteData<Item>>;
this.searchOptions$ = this.searchConfigService.paginatedSearchOptions;
this.loadCollectionLists();
}
/**
* Load itemCollectionsRD$ with a fixed scope to only obtain the collections that own this item
* Load mappedCollectionsRD$ to only obtain collections that don't own this item
*/
loadCollectionLists() {
this.shouldUpdate$ = new BehaviorSubject<boolean>(true);
this.itemCollectionsRD$ = observableCombineLatest(this.itemRD$, this.shouldUpdate$).pipe(
map(([itemRD, shouldUpdate]) => {
if (shouldUpdate) {
return itemRD.payload
}
}),
switchMap((item: Item) => this.itemDataService.getMappedCollections(item.id))
);
const owningCollectionRD$ = this.itemRD$.pipe(
switchMap((itemRD: RemoteData<Item>) => itemRD.payload.owningCollection)
);
const itemCollectionsAndOptions$ = observableCombineLatest(
this.itemCollectionsRD$,
owningCollectionRD$,
this.searchOptions$
);
this.mappedCollectionsRD$ = itemCollectionsAndOptions$.pipe(
switchMap(([itemCollectionsRD, owningCollectionRD, searchOptions]) => {
return this.searchService.search(Object.assign(new PaginatedSearchOptions(searchOptions), {
query: this.buildQuery([...itemCollectionsRD.payload.page, owningCollectionRD.payload], searchOptions.query),
dsoType: DSpaceObjectType.COLLECTION
}), 10000).pipe(
toDSpaceObjectListRD(),
startWith(undefined)
);
})
) as Observable<RemoteData<PaginatedList<Collection>>>;
}
/**
* Map the item to the selected collections and display notifications
* @param {string[]} ids The list of collection UUID's to map the item to
*/
mapCollections(ids: string[]) {
const itemIdAndExcludingIds$ = observableCombineLatest(
this.itemRD$.pipe(
getSucceededRemoteData(),
take(1),
map((rd: RemoteData<Item>) => rd.payload),
map((item: Item) => item.id)
),
this.itemCollectionsRD$.pipe(
getSucceededRemoteData(),
take(1),
map((rd: RemoteData<PaginatedList<Collection>>) => rd.payload.page),
map((collections: Collection[]) => collections.map((collection: Collection) => collection.id))
)
);
// Map the item to the collections found in ids, excluding the collections the item is already mapped to
const responses$ = itemIdAndExcludingIds$.pipe(
switchMap(([itemId, excludingIds]) => observableCombineLatest(this.filterIds(ids, excludingIds).map((id: string) => this.itemDataService.mapToCollection(itemId, id))))
);
this.showNotifications(responses$, 'item.edit.item-mapper.notifications.add');
}
/**
* Remove the mapping of the item to the selected collections and display notifications
* @param {string[]} ids The list of collection UUID's to remove the mapping of the item for
*/
removeMappings(ids: string[]) {
const responses$ = this.itemRD$.pipe(
getSucceededRemoteData(),
map((itemRD: RemoteData<Item>) => itemRD.payload.id),
switchMap((itemId: string) => observableCombineLatest(ids.map((id: string) => this.itemDataService.removeMappingFromCollection(itemId, id))))
);
this.showNotifications(responses$, 'item.edit.item-mapper.notifications.remove');
}
/**
* Filters ids from a given list of ids, which exist in a second given list of ids
* @param {string[]} ids The list of ids to filter out of
* @param {string[]} excluding The ids that should be excluded from the first list
* @returns {string[]}
*/
private filterIds(ids: string[], excluding: string[]): string[] {
return ids.filter((id: string) => excluding.indexOf(id) < 0);
}
/**
* Display notifications
* @param {Observable<RestResponse[]>} responses$ The responses after adding/removing a mapping
* @param {string} messagePrefix The prefix to build the notification messages with
*/
private showNotifications(responses$: Observable<RestResponse[]>, messagePrefix: string) {
responses$.subscribe((responses: RestResponse[]) => {
const successful = responses.filter((response: RestResponse) => response.isSuccessful);
const unsuccessful = responses.filter((response: RestResponse) => !response.isSuccessful);
if (successful.length > 0) {
const successMessages = observableCombineLatest(
this.translateService.get(`${messagePrefix}.success.head`),
this.translateService.get(`${messagePrefix}.success.content`, { amount: successful.length })
);
successMessages.subscribe(([head, content]) => {
this.notificationsService.success(head, content);
});
}
if (unsuccessful.length > 0) {
const unsuccessMessages = observableCombineLatest(
this.translateService.get(`${messagePrefix}.error.head`),
this.translateService.get(`${messagePrefix}.error.content`, { amount: unsuccessful.length })
);
unsuccessMessages.subscribe(([head, content]) => {
this.notificationsService.error(head, content);
});
}
// Force an update on all lists and switch back to the first tab
this.shouldUpdate$.next(true);
this.switchToFirstTab();
});
}
/**
* Clear url parameters on tab change (temporary fix until pagination is improved)
* @param event
*/
tabChange(event) {
this.performedSearch = false;
this.router.navigateByUrl(this.getCurrentUrl());
}
/**
* Get current url without parameters
* @returns {string}
*/
getCurrentUrl(): string {
if (this.router.url.indexOf('?') > -1) {
return this.router.url.substring(0, this.router.url.indexOf('?'));
}
return this.router.url;
}
/**
* Build a query to exclude collections from
* @param collections The collections their UUIDs
* @param query The query to add to it
*/
buildQuery(collections: Collection[], query: string): string {
let result = query;
for (const collection of collections) {
result = this.addExcludeCollection(collection.id, result);
}
return result;
}
/**
* Add an exclusion of a collection to a query
* @param collectionId The collection's UUID
* @param query The query to add the exclusion to
*/
addExcludeCollection(collectionId: string, query: string): string {
const excludeQuery = `-search.resourceid:${collectionId}`;
if (isNotEmpty(query)) {
return `${query} AND ${excludeQuery}`;
} else {
return excludeQuery;
}
}
/**
* Switch the view to focus on the first tab
*/
switchToFirstTab() {
this.tabs.select('browseTab');
}
/**
* When a cancel event is fired, return to the item page
*/
onCancel() {
this.itemRD$.pipe(
getSucceededRemoteData(),
getRemoteDataPayload(),
take(1)
).subscribe((item: Item) => {
this.router.navigate(['/items/', item.id])
});
}
}

View File

@@ -97,7 +97,7 @@ describe('EditRelationshipListComponent', () => {
relationshipService = jasmine.createSpyObj('relationshipService', relationshipService = jasmine.createSpyObj('relationshipService',
{ {
getRelatedItemsByLabel: observableOf([author1, author2]), getRelatedItemsByLabel: observableOf(new RemoteData(false, false, true, null, new PaginatedList(new PageInfo(), [author1, author2]))),
} }
); );

View File

@@ -4,8 +4,10 @@ import { Observable } from 'rxjs/internal/Observable';
import { FieldUpdate, FieldUpdates } from '../../../../core/data/object-updates/object-updates.reducer'; import { FieldUpdate, FieldUpdates } from '../../../../core/data/object-updates/object-updates.reducer';
import { RelationshipService } from '../../../../core/data/relationship.service'; import { RelationshipService } from '../../../../core/data/relationship.service';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';
import { switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { hasValue } from '../../../../shared/empty.util'; import { hasValue } from '../../../../shared/empty.util';
import { RemoteData } from '../../../../core/data/remote-data';
import { PaginatedList } from '../../../../core/data/paginated-list';
@Component({ @Component({
selector: 'ds-edit-relationship-list', selector: 'ds-edit-relationship-list',
@@ -63,7 +65,7 @@ export class EditRelationshipListComponent implements OnInit, OnChanges {
* Transform the item's relationships of a specific type into related items * Transform the item's relationships of a specific type into related items
* @param label The relationship type's label * @param label The relationship type's label
*/ */
public getRelatedItemsByLabel(label: string): Observable<Item[]> { public getRelatedItemsByLabel(label: string): Observable<RemoteData<PaginatedList<Item>>> {
return this.relationshipService.getRelatedItemsByLabel(this.item, label); return this.relationshipService.getRelatedItemsByLabel(this.item, label);
} }
@@ -73,7 +75,7 @@ export class EditRelationshipListComponent implements OnInit, OnChanges {
*/ */
public getUpdatesByLabel(label: string): Observable<FieldUpdates> { public getUpdatesByLabel(label: string): Observable<FieldUpdates> {
return this.getRelatedItemsByLabel(label).pipe( return this.getRelatedItemsByLabel(label).pipe(
switchMap((items: Item[]) => this.objectUpdatesService.getFieldUpdatesExclusive(this.url, items)) switchMap((itemsRD) => this.objectUpdatesService.getFieldUpdatesExclusive(this.url, itemsRD.payload.page))
) )
} }

View File

@@ -1,6 +1,6 @@
<div class="row" *ngIf="item"> <div class="row" *ngIf="item">
<div class="col-10 relationship"> <div class="col-10 relationship">
<ds-item-type-switcher [object]="item" [viewMode]="viewMode"></ds-item-type-switcher> <ds-listable-object-component-loader [object]="item" [viewMode]="viewMode"></ds-listable-object-component-loader>
</div> </div>
<div class="col-2"> <div class="col-2">
<div class="btn-group relationship-action-buttons"> <div class="btn-group relationship-action-buttons">

View File

@@ -5,7 +5,6 @@ import { ObjectUpdatesService } from '../../../../core/data/object-updates/objec
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { NO_ERRORS_SCHEMA } from '@angular/core';
import { EditRelationshipComponent } from './edit-relationship.component'; import { EditRelationshipComponent } from './edit-relationship.component';
import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model'; import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model';
import { ResourceType } from '../../../../core/shared/resource-type';
import { Relationship } from '../../../../core/shared/item-relationships/relationship.model'; import { Relationship } from '../../../../core/shared/item-relationships/relationship.model';
import { RemoteData } from '../../../../core/data/remote-data'; import { RemoteData } from '../../../../core/data/remote-data';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';

View File

@@ -4,7 +4,7 @@ import { cloneDeep } from 'lodash';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';
import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service'; import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service';
import { FieldChangeType } from '../../../../core/data/object-updates/object-updates.actions'; import { FieldChangeType } from '../../../../core/data/object-updates/object-updates.actions';
import { ItemViewMode } from '../../../../shared/items/item-type-decorator'; import { ViewMode } from '../../../../core/shared/view-mode.model';
@Component({ @Component({
// tslint:disable-next-line:component-selector // tslint:disable-next-line:component-selector
@@ -31,7 +31,7 @@ export class EditRelationshipComponent implements OnChanges {
/** /**
* The view-mode we're currently on * The view-mode we're currently on
*/ */
viewMode = ItemViewMode.Element; viewMode = ViewMode.ListElement;
constructor(private objectUpdatesService: ObjectUpdatesService) { constructor(private objectUpdatesService: ObjectUpdatesService) {
} }

View File

@@ -68,6 +68,7 @@ export class ItemStatusComponent implements OnInit {
The value is supposed to be a href for the button The value is supposed to be a href for the button
*/ */
this.operations = []; this.operations = [];
this.operations.push(new ItemOperation('mappedCollections', this.getCurrentUrl(item) + '/mapper'));
if (item.isWithdrawn) { if (item.isWithdrawn) {
this.operations.push(new ItemOperation('reinstate', this.getCurrentUrl(item) + '/reinstate')); this.operations.push(new ItemOperation('reinstate', this.getCurrentUrl(item) + '/reinstate'));
} else { } else {

View File

@@ -23,7 +23,7 @@ import {
} from '../../shared/testing/utils'; } from '../../shared/testing/utils';
const mockItem: Item = Object.assign(new Item(), { const mockItem: Item = Object.assign(new Item(), {
bitstreams: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])), bundles: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])),
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ {

View File

@@ -31,8 +31,8 @@ import { MetadataFieldWrapperComponent } from './field-components/metadata-field
imports: [ imports: [
CommonModule, CommonModule,
SharedModule, SharedModule,
EditItemPageModule,
ItemPageRoutingModule, ItemPageRoutingModule,
EditItemPageModule,
SearchPageModule SearchPageModule
], ],
declarations: [ declarations: [

View File

@@ -10,7 +10,7 @@ import { ItemPageFieldComponent } from '../item-page-field.component';
/** /**
* This component can be used to represent metadata on a simple item page. * This component can be used to represent metadata on a simple item page.
* It is the most generic way of displaying metadata values * It is the most generic way of displaying metadata values
* It expects 4 parameters: The item, a seperator, the metadata keys and an i18n key * It expects 4 parameters: The item, a separator, the metadata keys and an i18n key
*/ */
export class GenericItemPageFieldComponent extends ItemPageFieldComponent { export class GenericItemPageFieldComponent extends ItemPageFieldComponent {

View File

@@ -4,12 +4,9 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';
import { PaginatedList } from '../../../../core/data/paginated-list'; import { PaginatedList } from '../../../../core/data/paginated-list';
import { MockTranslateLoader } from '../../../../shared/mocks/mock-translate-loader'; import { MockTranslateLoader } from '../../../../shared/mocks/mock-translate-loader';
import { Observable } from 'rxjs';
import { PageInfo } from '../../../../core/shared/page-info.model'; import { PageInfo } from '../../../../core/shared/page-info.model';
import { RemoteData } from '../../../../core/data/remote-data';
import { ItemPageFieldComponent } from './item-page-field.component'; import { ItemPageFieldComponent } from './item-page-field.component';
import { MetadataValuesComponent } from '../../../field-components/metadata-values/metadata-values.component'; import { MetadataValuesComponent } from '../../../field-components/metadata-values/metadata-values.component';
import { of as observableOf } from 'rxjs';
import { MetadataMap, MetadataValue } from '../../../../core/shared/metadata.models'; import { MetadataMap, MetadataValue } from '../../../../core/shared/metadata.models';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/testing/utils'; import { createSuccessfulRemoteDataObject$ } from '../../../../shared/testing/utils';
@@ -53,7 +50,7 @@ describe('ItemPageFieldComponent', () => {
export function mockItemWithMetadataFieldAndValue(field: string, value: string): Item { export function mockItemWithMetadataFieldAndValue(field: string, value: string): Item {
const item = Object.assign(new Item(), { const item = Object.assign(new Item(), {
bitstreams: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])), bundles: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])),
metadata: new MetadataMap() metadata: new MetadataMap()
}); });
item.metadata[field] = [{ item.metadata[field] = [{

View File

@@ -1,7 +1,7 @@
<div class="container" *ngVar="(itemRD$ | async) as itemRD"> <div class="container" *ngVar="(itemRD$ | async) as itemRD">
<div class="item-page" *ngIf="itemRD?.hasSucceeded" @fadeInOut> <div class="item-page" *ngIf="itemRD?.hasSucceeded" @fadeInOut>
<div *ngIf="itemRD?.payload as item"> <div *ngIf="itemRD?.payload as item">
<ds-item-type-switcher [object]="item" [viewMode]="viewMode"></ds-item-type-switcher> <ds-listable-object-component-loader [object]="item" [viewMode]="viewMode"></ds-listable-object-component-loader>
</div> </div>
</div> </div>
<ds-error *ngIf="itemRD?.hasFailed" message="{{'error.item' | translate}}"></ds-error> <ds-error *ngIf="itemRD?.hasFailed" message="{{'error.item' | translate}}"></ds-error>

View File

@@ -22,7 +22,7 @@ import {
} from '../../shared/testing/utils'; } from '../../shared/testing/utils';
const mockItem: Item = Object.assign(new Item(), { const mockItem: Item = Object.assign(new Item(), {
bitstreams: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])), bundles: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])),
metadata: [], metadata: [],
relationships: createRelationshipsObservable() relationships: createRelationshipsObservable()
}); });

View File

@@ -1,21 +1,18 @@
import { map } from 'rxjs/operators';
import { mergeMap, filter, map, take, tap } from 'rxjs/operators';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { ItemDataService } from '../../core/data/item-data.service'; import { ItemDataService } from '../../core/data/item-data.service';
import { RemoteData } from '../../core/data/remote-data'; import { RemoteData } from '../../core/data/remote-data';
import { Bitstream } from '../../core/shared/bitstream.model';
import { Item } from '../../core/shared/item.model'; import { Item } from '../../core/shared/item.model';
import { MetadataService } from '../../core/metadata/metadata.service'; import { MetadataService } from '../../core/metadata/metadata.service';
import { fadeInOut } from '../../shared/animations/fade'; import { fadeInOut } from '../../shared/animations/fade';
import { hasValue } from '../../shared/empty.util';
import { redirectToPageNotFoundOn404 } from '../../core/shared/operators'; import { redirectToPageNotFoundOn404 } from '../../core/shared/operators';
import { ItemViewMode } from '../../shared/items/item-type-decorator'; import { ViewMode } from '../../core/shared/view-mode.model';
/** /**
* This component renders a simple item page. * This component renders a simple item page.
@@ -44,7 +41,7 @@ export class ItemPageComponent implements OnInit {
/** /**
* The view-mode we're currently on * The view-mode we're currently on
*/ */
viewMode = ItemViewMode.Full; viewMode = ViewMode.StandalonePage;
constructor( constructor(
private route: ActivatedRoute, private route: ActivatedRoute,
@@ -53,6 +50,9 @@ export class ItemPageComponent implements OnInit {
private metadataService: MetadataService, private metadataService: MetadataService,
) { } ) { }
/**
* Initialize instance variables
*/
ngOnInit(): void { ngOnInit(): void {
this.itemRD$ = this.route.data.pipe( this.itemRD$ = this.route.data.pipe(
map((data) => data.item as RemoteData<Item>), map((data) => data.item as RemoteData<Item>),

View File

@@ -1,67 +1,72 @@
<h2 class="item-page-title-field"> <h2 class="item-page-title-field">
{{'publication.page.titleprefix' | translate}}<ds-metadata-values [mdValues]="item?.allMetadata(['dc.title'])"></ds-metadata-values> {{'publication.page.titleprefix' | translate}}<ds-metadata-values [mdValues]="object?.allMetadata(['dc.title'])"></ds-metadata-values>
</h2> </h2>
<div class="row"> <div class="row">
<div class="col-xs-12 col-md-4"> <div class="col-xs-12 col-md-4">
<ds-metadata-field-wrapper> <ds-metadata-field-wrapper>
<ds-thumbnail [thumbnail]="this.item.getThumbnail() | async"></ds-thumbnail> <ds-thumbnail [thumbnail]="object.getThumbnail() | async"></ds-thumbnail>
</ds-metadata-field-wrapper> </ds-metadata-field-wrapper>
<ds-item-page-file-section [item]="item"></ds-item-page-file-section> <ds-item-page-file-section [item]="object"></ds-item-page-file-section>
<ds-item-page-date-field [item]="item"></ds-item-page-date-field> <ds-item-page-date-field [item]="object"></ds-item-page-date-field>
<ds-item-page-author-field *ngIf="!(authors$ | async)" [item]="item"></ds-item-page-author-field> <ds-item-page-author-field [item]="object"></ds-item-page-author-field>
<ds-generic-item-page-field [item]="item" <ds-generic-item-page-field [item]="object"
[fields]="['journal.title']" [fields]="['journal.title']"
[label]="'publication.page.journal-title'"> [label]="'publication.page.journal-title'">
</ds-generic-item-page-field> </ds-generic-item-page-field>
<ds-generic-item-page-field [item]="item" <ds-generic-item-page-field [item]="object"
[fields]="['journal.identifier.issn']" [fields]="['journal.identifier.issn']"
[label]="'publication.page.journal-issn'"> [label]="'publication.page.journal-issn'">
</ds-generic-item-page-field> </ds-generic-item-page-field>
<ds-generic-item-page-field [item]="item" <ds-generic-item-page-field [item]="object"
[fields]="['journalvolume.identifier.name']" [fields]="['journalvolume.identifier.name']"
[label]="'publication.page.volume-title'"> [label]="'publication.page.volume-title'">
</ds-generic-item-page-field> </ds-generic-item-page-field>
<ds-generic-item-page-field [item]="item" <ds-generic-item-page-field [item]="object"
[fields]="['dc.publisher']" [fields]="['dc.publisher']"
[label]="'publication.page.publisher'"> [label]="'publication.page.publisher'">
</ds-generic-item-page-field> </ds-generic-item-page-field>
</div> </div>
<div class="col-xs-12 col-md-6"> <div class="col-xs-12 col-md-6">
<ds-metadata-representation-list <ds-metadata-representation-list
[label]="'relationships.isAuthorOf' | translate" [parentItem]="object"
[representations]="authors$ | async"> [itemType]="'Person'"
[metadataField]="'dc.contributor.author'"
[label]="'relationships.isAuthorOf' | translate">
</ds-metadata-representation-list> </ds-metadata-representation-list>
<ds-related-items <ds-related-items
[items]="projects$ | async" [parentItem]="object"
[relationType]="'isProjectOfPublication'"
[label]="'relationships.isProjectOf' | translate"> [label]="'relationships.isProjectOf' | translate">
</ds-related-items> </ds-related-items>
<ds-related-items <ds-related-items
[items]="orgUnits$ | async" [parentItem]="object"
[relationType]="'isOrgUnitOfPublication'"
[label]="'relationships.isOrgUnitOf' | translate"> [label]="'relationships.isOrgUnitOf' | translate">
</ds-related-items> </ds-related-items>
<ds-related-items <ds-related-items
[items]="journalIssues$ | async" [parentItem]="object"
[relationType]="'isJournalIssueOfPublication'"
[label]="'relationships.isJournalIssueOf' | translate"> [label]="'relationships.isJournalIssueOf' | translate">
</ds-related-items> </ds-related-items>
<ds-item-page-abstract-field [item]="item"></ds-item-page-abstract-field> <ds-item-page-abstract-field [item]="object"></ds-item-page-abstract-field>
<ds-generic-item-page-field [item]="item" <ds-generic-item-page-field [item]="object"
[fields]="['dc.description']" [fields]="['dc.description']"
[label]="'publication.page.description'"> [label]="'publication.page.description'">
</ds-generic-item-page-field> </ds-generic-item-page-field>
<ds-generic-item-page-field [item]="item" <ds-generic-item-page-field [item]="object"
[fields]="['dc.subject']" [fields]="['dc.subject']"
[separator]="','" [separator]="','"
[label]="'item.page.subject'"> [label]="'item.page.subject'">
</ds-generic-item-page-field> </ds-generic-item-page-field>
<ds-generic-item-page-field [item]="item" <ds-generic-item-page-field [item]="object"
[fields]="['dc.identifier.citation']" [fields]="['dc.identifier.citation']"
[label]="'item.page.citation'"> [label]="'item.page.citation'">
</ds-generic-item-page-field> </ds-generic-item-page-field>
<ds-item-page-uri-field [item]="item"></ds-item-page-uri-field> <ds-item-page-uri-field [item]="object"></ds-item-page-uri-field>
<ds-item-page-collections [item]="item"></ds-item-page-collections> <ds-item-page-collections [item]="object"></ds-item-page-collections>
<div> <div>
<a class="btn btn-outline-primary" [routerLink]="['/items/' + item.id + '/full']"> <a class="btn btn-outline-primary" [routerLink]="['/items/' + object.id + '/full']">
{{"item.page.link.full" | translate}} {{"item.page.link.full" | translate}}
</a> </a>
</div> </div>

View File

@@ -3,24 +3,21 @@ import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { MockTranslateLoader } from '../../../../shared/mocks/mock-translate-loader'; import { MockTranslateLoader } from '../../../../shared/mocks/mock-translate-loader';
import { GenericItemPageFieldComponent } from '../../field-components/specific-field/generic/generic-item-page-field.component'; import { GenericItemPageFieldComponent } from '../../field-components/specific-field/generic/generic-item-page-field.component';
import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe';
import { ITEM } from '../../../../shared/items/switcher/item-type-switcher.component';
import { ItemDataService } from '../../../../core/data/item-data.service'; import { ItemDataService } from '../../../../core/data/item-data.service';
import { SearchFixedFilterService } from '../../../../+search-page/search-filters/search-filter/search-fixed-filter.service'; import { SearchFixedFilterService } from '../../../../+search-page/search-filters/search-filter/search-fixed-filter.service';
import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service';
import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';
import { RemoteData } from '../../../../core/data/remote-data';
import { PaginatedList } from '../../../../core/data/paginated-list'; import { PaginatedList } from '../../../../core/data/paginated-list';
import { PageInfo } from '../../../../core/shared/page-info.model'; import { PageInfo } from '../../../../core/shared/page-info.model';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { createRelationshipsObservable } from '../shared/item.component.spec'; import { createRelationshipsObservable } from '../shared/item.component.spec';
import { PublicationComponent } from './publication.component'; import { PublicationComponent } from './publication.component';
import { of as observableOf } from 'rxjs';
import { MetadataMap } from '../../../../core/shared/metadata.models'; import { MetadataMap } from '../../../../core/shared/metadata.models';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/testing/utils'; import { createSuccessfulRemoteDataObject$ } from '../../../../shared/testing/utils';
const mockItem: Item = Object.assign(new Item(), { const mockItem: Item = Object.assign(new Item(), {
bitstreams: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])), bundles: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])),
metadata: new MetadataMap(), metadata: new MetadataMap(),
relationships: createRelationshipsObservable() relationships: createRelationshipsObservable()
}); });
@@ -45,7 +42,6 @@ describe('PublicationComponent', () => {
})], })],
declarations: [PublicationComponent, GenericItemPageFieldComponent, TruncatePipe], declarations: [PublicationComponent, GenericItemPageFieldComponent, TruncatePipe],
providers: [ providers: [
{provide: ITEM, useValue: mockItem},
{provide: ItemDataService, useValue: {}}, {provide: ItemDataService, useValue: {}},
{provide: SearchFixedFilterService, useValue: searchFixedFilterServiceStub}, {provide: SearchFixedFilterService, useValue: searchFixedFilterServiceStub},
{provide: TruncatableService, useValue: {}} {provide: TruncatableService, useValue: {}}
@@ -60,6 +56,7 @@ describe('PublicationComponent', () => {
beforeEach(async(() => { beforeEach(async(() => {
fixture = TestBed.createComponent(PublicationComponent); fixture = TestBed.createComponent(PublicationComponent);
comp = fixture.componentInstance; comp = fixture.componentInstance;
comp.object = mockItem;
fixture.detectChanges(); fixture.detectChanges();
})); }));

View File

@@ -1,62 +1,20 @@
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Observable } from 'rxjs';
import { Item } from '../../../../core/shared/item.model';
import {
DEFAULT_ITEM_TYPE, ItemViewMode,
rendersItemType
} from '../../../../shared/items/item-type-decorator';
import { ItemComponent } from '../shared/item.component'; import { ItemComponent } from '../shared/item.component';
import { MetadataRepresentation } from '../../../../core/shared/metadata-representation/metadata-representation.model'; import { listableObjectComponent } from '../../../../shared/object-collection/shared/listable-object/listable-object.decorator';
import { getRelatedItemsByTypeLabel } from '../shared/item-relationships-utils'; import { Item } from '../../../../core/shared/item.model';
import { ViewMode } from '../../../../core/shared/view-mode.model';
@rendersItemType('Publication', ItemViewMode.Full) /**
@rendersItemType(DEFAULT_ITEM_TYPE, ItemViewMode.Full) * Component that represents a publication Item page
*/
@listableObjectComponent('Publication', ViewMode.StandalonePage)
@listableObjectComponent(Item, ViewMode.StandalonePage)
@Component({ @Component({
selector: 'ds-publication', selector: 'ds-publication',
styleUrls: ['./publication.component.scss'], styleUrls: ['./publication.component.scss'],
templateUrl: './publication.component.html', templateUrl: './publication.component.html',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class PublicationComponent extends ItemComponent implements OnInit { export class PublicationComponent extends ItemComponent {
/**
* The authors related to this publication
*/
authors$: Observable<MetadataRepresentation[]>;
/**
* The projects related to this publication
*/
projects$: Observable<Item[]>;
/**
* The organisation units related to this publication
*/
orgUnits$: Observable<Item[]>;
/**
* The journal issues related to this publication
*/
journalIssues$: Observable<Item[]>;
ngOnInit(): void {
super.ngOnInit();
if (this.resolvedRelsAndTypes$) {
this.authors$ = this.buildRepresentations('Person', 'dc.contributor.author');
this.projects$ = this.resolvedRelsAndTypes$.pipe(
getRelatedItemsByTypeLabel(this.item.id, 'isProjectOfPublication')
);
this.orgUnits$ = this.resolvedRelsAndTypes$.pipe(
getRelatedItemsByTypeLabel(this.item.id, 'isOrgUnitOfPublication')
);
this.journalIssues$ = this.resolvedRelsAndTypes$.pipe(
getRelatedItemsByTypeLabel(this.item.id, 'isJournalIssueOfPublication')
);
}
}
} }

View File

@@ -1,18 +1,14 @@
import { ItemMetadataRepresentation } from '../../../../core/shared/metadata-representation/item/item-metadata-representation.model';
import { MetadataRepresentation } from '../../../../core/shared/metadata-representation/metadata-representation.model';
import { MetadatumRepresentation } from '../../../../core/shared/metadata-representation/metadatum/metadatum-representation.model';
import { MetadataValue } from '../../../../core/shared/metadata.models';
import { getRemoteDataPayload, getSucceededRemoteData } from '../../../../core/shared/operators'; import { getRemoteDataPayload, getSucceededRemoteData } from '../../../../core/shared/operators';
import { hasNoValue, hasValue } from '../../../../shared/empty.util'; import { hasNoValue, hasValue } from '../../../../shared/empty.util';
import { Observable } from 'rxjs/internal/Observable'; import { Observable } from 'rxjs/internal/Observable';
import { Relationship } from '../../../../core/shared/item-relationships/relationship.model'; import { Relationship } from '../../../../core/shared/item-relationships/relationship.model';
import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model'; import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model';
import { distinctUntilChanged, filter, flatMap, map, switchMap, tap } from 'rxjs/operators'; import { distinctUntilChanged, flatMap, map, switchMap } from 'rxjs/operators';
import { of as observableOf, zip as observableZip, combineLatest as observableCombineLatest } from 'rxjs'; import { zip as observableZip, combineLatest as observableCombineLatest } from 'rxjs';
import { ItemDataService } from '../../../../core/data/item-data.service';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';
import { RemoteData } from '../../../../core/data/remote-data'; import { RemoteData } from '../../../../core/data/remote-data';
import { RelationshipService } from '../../../../core/data/relationship.service'; import { RelationshipService } from '../../../../core/data/relationship.service';
import { PaginatedList } from '../../../../core/data/paginated-list';
/** /**
* Operator for comparing arrays using a mapping function * Operator for comparing arrays using a mapping function
@@ -100,54 +96,37 @@ export const relationsToItems = (thisId: string) =>
); );
/** /**
* Operator for turning a list of relationships and their relationship-types into a list of relevant items by relationship label * Operator for turning a paginated list of relationships into a paginated list of the relevant items
* @param thisId The item's id of which the relations belong to * The result is wrapped in the original RemoteData and PaginatedList
* @param label The label of the relationship-type to filter on * @param {string} thisId The item's id of which the relations belong to
* @param side Filter only on one side of the relationship (for example: child-parent relationships) * @returns {(source: Observable<Relationship[]>) => Observable<Item[]>}
*/ */
export const getRelatedItemsByTypeLabel = (thisId: string, label: string) => export const paginatedRelationsToItems = (thisId: string) =>
(source: Observable<[Relationship[], RelationshipType[]]>): Observable<Item[]> => (source: Observable<RemoteData<PaginatedList<Relationship>>>): Observable<RemoteData<PaginatedList<Item>>> =>
source.pipe( source.pipe(
filterRelationsByTypeLabel(label, thisId), getSucceededRemoteData(),
relationsToItems(thisId) switchMap((relationshipsRD: RemoteData<PaginatedList<Relationship>>) => {
); return observableZip(
...relationshipsRD.payload.page.map((rel: Relationship) => observableCombineLatest(rel.leftItem, rel.rightItem))
/** ).pipe(
* Operator for turning a list of relationships into a list of metadatarepresentations given the original metadata map((arr) =>
* @param parentId The id of the parent item arr
* @param itemType The type of relation this list resembles (for creating representations) .filter(([leftItem, rightItem]) => leftItem.hasSucceeded && rightItem.hasSucceeded)
* @param metadata The list of original Metadatum objects .map(([leftItem, rightItem]) => {
* @param ids The ItemDataService to use for fetching Items from the Rest API if (leftItem.payload.id === thisId) {
*/ return rightItem.payload;
export const relationsToRepresentations = (parentId: string, itemType: string, metadata: MetadataValue[], ids: ItemDataService) => } else if (rightItem.payload.id === thisId) {
(source: Observable<Relationship[]>): Observable<MetadataRepresentation[]> => return leftItem.payload;
source.pipe(
flatMap((rels: Relationship[]) =>
observableZip(
...metadata
.map((metadatum: any) => Object.assign(new MetadataValue(), metadatum))
.map((metadatum: MetadataValue) => {
if (metadatum.isVirtual) {
const matchingRels = rels.filter((rel: Relationship) => ('' + rel.id) === metadatum.virtualValue);
if (matchingRels.length > 0) {
const matchingRel = matchingRels[0];
return observableCombineLatest(matchingRel.leftItem, matchingRel.rightItem).pipe(
map(([leftItem, rightItem]) => {
if (leftItem.payload.id === parentId) {
return rightItem.payload;
} else if (rightItem.payload.id === parentId) {
return leftItem.payload;
}
}),
map((item: Item) => Object.assign(new ItemMetadataRepresentation(), item))
);
} }
} else { })
return observableOf(Object.assign(new MetadatumRepresentation(itemType), metadatum)); .filter((item: Item) => hasValue(item))
} ),
}) distinctUntilChanged(compareArraysUsingIds()),
map((relatedItems: Item[]) =>
Object.assign(relationshipsRD, { payload: Object.assign(relationshipsRD.payload, { page: relatedItems } )})
)
) )
) })
); );
/** /**

View File

@@ -7,17 +7,14 @@ import { ItemDataService } from '../../../../core/data/item-data.service';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { MockTranslateLoader } from '../../../../shared/mocks/mock-translate-loader'; import { MockTranslateLoader } from '../../../../shared/mocks/mock-translate-loader';
import { ChangeDetectionStrategy, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectionStrategy, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { ITEM } from '../../../../shared/items/switcher/item-type-switcher.component';
import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe';
import { isNotEmpty } from '../../../../shared/empty.util'; import { isNotEmpty } from '../../../../shared/empty.util';
import { SearchFixedFilterService } from '../../../../+search-page/search-filters/search-filter/search-fixed-filter.service'; import { SearchFixedFilterService } from '../../../../+search-page/search-filters/search-filter/search-fixed-filter.service';
import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model'; import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model';
import { PaginatedList } from '../../../../core/data/paginated-list'; import { PaginatedList } from '../../../../core/data/paginated-list';
import { RemoteData } from '../../../../core/data/remote-data';
import { Relationship } from '../../../../core/shared/item-relationships/relationship.model'; import { Relationship } from '../../../../core/shared/item-relationships/relationship.model';
import { PageInfo } from '../../../../core/shared/page-info.model'; import { PageInfo } from '../../../../core/shared/page-info.model';
import { ItemComponent } from './item.component'; import { ItemComponent } from './item.component';
import { of as observableOf } from 'rxjs';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { VarDirective } from '../../../../shared/utils/var.directive'; import { VarDirective } from '../../../../shared/utils/var.directive';
import { Observable } from 'rxjs/internal/Observable'; import { Observable } from 'rxjs/internal/Observable';
@@ -56,7 +53,6 @@ export function getItemPageFieldsTest(mockItem: Item, component) {
})], })],
declarations: [component, GenericItemPageFieldComponent, TruncatePipe], declarations: [component, GenericItemPageFieldComponent, TruncatePipe],
providers: [ providers: [
{provide: ITEM, useValue: mockItem},
{provide: ItemDataService, useValue: {}}, {provide: ItemDataService, useValue: {}},
{provide: SearchFixedFilterService, useValue: searchFixedFilterServiceStub}, {provide: SearchFixedFilterService, useValue: searchFixedFilterServiceStub},
{provide: TruncatableService, useValue: {}} {provide: TruncatableService, useValue: {}}
@@ -71,6 +67,7 @@ export function getItemPageFieldsTest(mockItem: Item, component) {
beforeEach(async(() => { beforeEach(async(() => {
fixture = TestBed.createComponent(component); fixture = TestBed.createComponent(component);
comp = fixture.componentInstance; comp = fixture.componentInstance;
comp.object = mockItem;
fixture.detectChanges(); fixture.detectChanges();
})); }));
@@ -317,115 +314,4 @@ describe('ItemComponent', () => {
}); });
}); });
describe('when calling buildRepresentations', () => {
let comp: ItemComponent;
let fixture: ComponentFixture<ItemComponent>;
const metadataField = 'dc.contributor.author';
const relatedItem = Object.assign(new Item(), {
id: '2',
metadata: Object.assign(new MetadataMap(), {
'dc.title': [
{
language: 'en_US',
value: 'related item'
}
]
})
});
const mockItem = Object.assign(new Item(), {
id: '1',
uuid: '1',
metadata: new MetadataMap()
});
mockItem.relationships = createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [
Object.assign(new Relationship(), {
uuid: '123',
id: '123',
leftItem: createSuccessfulRemoteDataObject$(mockItem),
rightItem: createSuccessfulRemoteDataObject$(relatedItem),
relationshipType: createSuccessfulRemoteDataObject$(new RelationshipType())
})
]));
mockItem.metadata[metadataField] = [
{
value: 'Second value',
place: 1
},
{
value: 'Third value',
place: 2,
authority: 'virtual::123'
},
{
value: 'First value',
place: 0
},
{
value: 'Fourth value',
place: 3,
authority: '123'
}
] as MetadataValue[];
const mockItemDataService = Object.assign({
findById: (id) => {
if (id === relatedItem.id) {
return createSuccessfulRemoteDataObject$(relatedItem)
}
}
}) as ItemDataService;
let representations: Observable<MetadataRepresentation[]>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: MockTranslateLoader
}
}), BrowserAnimationsModule],
declarations: [ItemComponent, VarDirective],
providers: [
{provide: ITEM, useValue: mockItem}
],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(ItemComponent, {
set: {changeDetection: ChangeDetectionStrategy.Default}
}).compileComponents();
}));
beforeEach(async(() => {
fixture = TestBed.createComponent(ItemComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
representations = comp.buildRepresentations('bogus', metadataField);
}));
it('should contain exactly 4 metadata-representations', () => {
representations.subscribe((reps: MetadataRepresentation[]) => {
expect(reps.length).toEqual(4);
});
});
it('should have all the representations in the correct order', () => {
representations.subscribe((reps: MetadataRepresentation[]) => {
expect(reps[0].getValue()).toEqual('First value');
expect(reps[1].getValue()).toEqual('Second value');
expect(reps[2].getValue()).toEqual('related item');
expect(reps[3].getValue()).toEqual('Fourth value');
});
});
it('should have created the correct MetadatumRepresentation and ItemMetadataRepresentation objects for the correct Metadata', () => {
representations.subscribe((reps: MetadataRepresentation[]) => {
expect(reps[0] instanceof MetadatumRepresentation).toEqual(true);
expect(reps[1] instanceof MetadatumRepresentation).toEqual(true);
expect(reps[2] instanceof ItemMetadataRepresentation).toEqual(true);
expect(reps[3] instanceof MetadatumRepresentation).toEqual(true);
});
});
})
}); });

View File

@@ -1,58 +1,5 @@
import { Component, Inject, OnInit } from '@angular/core'; import { Component, Inject, Input } from '@angular/core';
import { Observable , zip as observableZip, combineLatest as observableCombineLatest } from 'rxjs';
import { distinctUntilChanged, filter, flatMap, map } from 'rxjs/operators';
import { ItemDataService } from '../../../../core/data/item-data.service';
import { PaginatedList } from '../../../../core/data/paginated-list';
import { RemoteData } from '../../../../core/data/remote-data';
import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model';
import { Relationship } from '../../../../core/shared/item-relationships/relationship.model';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';
import { getRemoteDataPayload, getSucceededRemoteData } from '../../../../core/shared/operators';
import { ITEM } from '../../../../shared/items/switcher/item-type-switcher.component';
import { MetadataRepresentation } from '../../../../core/shared/metadata-representation/metadata-representation.model';
import { ItemMetadataRepresentation } from '../../../../core/shared/metadata-representation/item/item-metadata-representation.model';
import { MetadatumRepresentation } from '../../../../core/shared/metadata-representation/metadatum/metadatum-representation.model';
import { of } from 'rxjs/internal/observable/of';
import { MetadataValue } from '../../../../core/shared/metadata.models';
import { compareArraysUsingIds } from './item-relationships-utils';
/**
* Operator for turning a list of relationships into a list of metadatarepresentations given the original metadata
* @param thisId The id of the parent item
* @param itemType The type of relation this list resembles (for creating representations)
* @param metadata The list of original Metadatum objects
*/
export const relationsToRepresentations = (thisId: string, itemType: string, metadata: MetadataValue[]) =>
(source: Observable<Relationship[]>): Observable<MetadataRepresentation[]> =>
source.pipe(
flatMap((rels: Relationship[]) =>
observableZip(
...metadata
.map((metadatum: any) => Object.assign(new MetadataValue(), metadatum))
.map((metadatum: MetadataValue) => {
if (metadatum.isVirtual) {
const matchingRels = rels.filter((rel: Relationship) => ('' + rel.id) === metadatum.virtualValue);
if (matchingRels.length > 0) {
const matchingRel = matchingRels[0];
return observableCombineLatest(matchingRel.leftItem, matchingRel.rightItem).pipe(
filter(([leftItem, rightItem]) => leftItem.hasSucceeded && rightItem.hasSucceeded),
map(([leftItem, rightItem]) => {
if (leftItem.payload.id === thisId) {
return rightItem.payload;
} else if (rightItem.payload.id === thisId) {
return leftItem.payload;
}
}),
map((item: Item) => Object.assign(new ItemMetadataRepresentation(), item))
);
}
} else {
return of(Object.assign(new MetadatumRepresentation(itemType), metadatum));
}
})
)
)
);
@Component({ @Component({
selector: 'ds-item', selector: 'ds-item',
@@ -61,60 +8,6 @@ export const relationsToRepresentations = (thisId: string, itemType: string, met
/** /**
* A generic component for displaying metadata and relations of an item * A generic component for displaying metadata and relations of an item
*/ */
export class ItemComponent implements OnInit { export class ItemComponent {
/** @Input() object: Item;
* Resolved relationships and types together in one observable
*/
resolvedRelsAndTypes$: Observable<[Relationship[], RelationshipType[]]>;
constructor(
@Inject(ITEM) public item: Item
) {}
ngOnInit(): void {
const relationships$ = this.item.relationships;
if (relationships$) {
const relsCurrentPage$ = relationships$.pipe(
filter((rd: RemoteData<PaginatedList<Relationship>>) => rd.hasSucceeded),
getRemoteDataPayload(),
map((pl: PaginatedList<Relationship>) => pl.page),
distinctUntilChanged(compareArraysUsingIds())
);
const relTypesCurrentPage$ = relsCurrentPage$.pipe(
flatMap((rels: Relationship[]) =>
observableZip(...rels.map((rel: Relationship) => rel.relationshipType)).pipe(
map(([...arr]: Array<RemoteData<RelationshipType>>) => arr.map((d: RemoteData<RelationshipType>) => d.payload))
)
),
distinctUntilChanged(compareArraysUsingIds())
);
this.resolvedRelsAndTypes$ = observableCombineLatest(
relsCurrentPage$,
relTypesCurrentPage$
);
}
}
/**
* Build a list of MetadataRepresentations for the current item. This combines all metadata and relationships of a
* certain type.
* @param itemType The type of item we're building representations of. Used for matching templates.
* @param metadataField The metadata field that resembles the item type.
*/
buildRepresentations(itemType: string, metadataField: string): Observable<MetadataRepresentation[]> {
const metadata = this.item.findMetadataSortedByPlace(metadataField);
const relsCurrentPage$ = this.item.relationships.pipe(
getSucceededRemoteData(),
getRemoteDataPayload(),
map((pl: PaginatedList<Relationship>) => pl.page),
distinctUntilChanged(compareArraysUsingIds())
);
return relsCurrentPage$.pipe(
relationsToRepresentations(this.item.id, itemType, metadata)
);
}
} }

View File

@@ -1,5 +1,11 @@
<ds-metadata-field-wrapper *ngIf="representations && representations.length > 0" [label]="label"> <ds-metadata-field-wrapper *ngIf="representations$ && (representations$ | async)?.length > 0" [label]="label">
<ds-item-type-switcher *ngFor="let rep of representations" <ds-metadata-representation-loader *ngFor="let rep of (representations$ | async)"
[object]="rep" [viewMode]="viewMode"> [mdRepresentation]="rep">
</ds-item-type-switcher> </ds-metadata-representation-loader>
<div *ngIf="(representations$ | async)?.length < total" class="mt-2">
<a [routerLink]="" (click)="viewMore()">{{'item.page.related-items.view-more' | translate}}</a>
</div>
<div *ngIf="limit > originalLimit" class="mt-2">
<a [routerLink]="" (click)="viewLess()">{{'item.page.related-items.view-less' | translate}}</a>
</div>
</ds-metadata-field-wrapper> </ds-metadata-field-wrapper>

View File

@@ -2,23 +2,72 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { MetadataRepresentationListComponent } from './metadata-representation-list.component'; import { MetadataRepresentationListComponent } from './metadata-representation-list.component';
import { MetadatumRepresentation } from '../../../core/shared/metadata-representation/metadatum/metadatum-representation.model'; import { RelationshipService } from '../../../core/data/relationship.service';
import { ItemMetadataRepresentation } from '../../../core/shared/metadata-representation/item/item-metadata-representation.model'; import { Item } from '../../../core/shared/item.model';
import { Relationship } from '../../../core/shared/item-relationships/relationship.model';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/testing/utils';
import { TranslateModule } from '@ngx-translate/core';
const itemType = 'type'; const itemType = 'Person';
const metadataRepresentation1 = new MetadatumRepresentation(itemType); const metadataField = 'dc.contributor.author';
const metadataRepresentation2 = new ItemMetadataRepresentation(); const parentItem: Item = Object.assign(new Item(), {
const representations = [metadataRepresentation1, metadataRepresentation2]; id: 'parent-item',
metadata: {
'dc.contributor.author': [
{
language: null,
value: 'Related Author with authority',
authority: 'virtual::related-author',
place: 2
},
{
language: null,
value: 'Author without authority',
place: 1
}
],
'dc.title': [
{
language: null,
value: 'Parent Item'
}
]
}
});
const relatedAuthor: Item = Object.assign(new Item(), {
id: 'related-author',
metadata: {
'dc.title': [
{
language: null,
value: 'Related Author'
}
]
}
});
const relation: Relationship = Object.assign(new Relationship(), {
leftItem: createSuccessfulRemoteDataObject$(parentItem),
rightItem: createSuccessfulRemoteDataObject$(relatedAuthor)
});
let relationshipService: RelationshipService;
describe('MetadataRepresentationListComponent', () => { describe('MetadataRepresentationListComponent', () => {
let comp: MetadataRepresentationListComponent; let comp: MetadataRepresentationListComponent;
let fixture: ComponentFixture<MetadataRepresentationListComponent>; let fixture: ComponentFixture<MetadataRepresentationListComponent>;
relationshipService = jasmine.createSpyObj('relationshipService',
{
findById: createSuccessfulRemoteDataObject$(relation)
}
);
beforeEach(async(() => { beforeEach(async(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [], imports: [TranslateModule.forRoot()],
declarations: [MetadataRepresentationListComponent], declarations: [MetadataRepresentationListComponent],
providers: [], providers: [
{ provide: RelationshipService, useValue: relationshipService }
],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(MetadataRepresentationListComponent, { }).overrideComponent(MetadataRepresentationListComponent, {
set: {changeDetection: ChangeDetectionStrategy.Default} set: {changeDetection: ChangeDetectionStrategy.Default}
@@ -28,13 +77,45 @@ describe('MetadataRepresentationListComponent', () => {
beforeEach(async(() => { beforeEach(async(() => {
fixture = TestBed.createComponent(MetadataRepresentationListComponent); fixture = TestBed.createComponent(MetadataRepresentationListComponent);
comp = fixture.componentInstance; comp = fixture.componentInstance;
comp.representations = representations; comp.parentItem = parentItem;
comp.itemType = itemType;
comp.metadataField = metadataField;
fixture.detectChanges(); fixture.detectChanges();
})); }));
it(`should load ${representations.length} item-type-switcher components`, () => { it('should load 2 ds-metadata-representation-loader components', () => {
const fields = fixture.debugElement.queryAll(By.css('ds-item-type-switcher')); const fields = fixture.debugElement.queryAll(By.css('ds-metadata-representation-loader'));
expect(fields.length).toBe(representations.length); expect(fields.length).toBe(2);
});
it('should initialize the original limit', () => {
expect(comp.originalLimit).toEqual(comp.limit);
});
describe('when viewMore is called', () => {
beforeEach(() => {
comp.viewMore();
});
it('should set the limit to a high number in order to retrieve all metadata representations', () => {
expect(comp.limit).toBeGreaterThanOrEqual(999);
});
});
describe('when viewLess is called', () => {
let originalLimit;
beforeEach(() => {
// Store the original value of limit
originalLimit = comp.limit;
// Set limit to a random number
comp.limit = 458;
comp.viewLess();
});
it('should reset the limit to the original value', () => {
expect(comp.limit).toEqual(originalLimit);
});
}); });
}); });

View File

@@ -1,6 +1,16 @@
import { Component, Input } from '@angular/core'; import { Component, Input, OnInit } from '@angular/core';
import { MetadataRepresentation } from '../../../core/shared/metadata-representation/metadata-representation.model'; import { MetadataRepresentation } from '../../../core/shared/metadata-representation/metadata-representation.model';
import { ItemViewMode } from '../../../shared/items/item-type-decorator'; import { Observable } from 'rxjs/internal/Observable';
import { RemoteData } from '../../../core/data/remote-data';
import { RelationshipService } from '../../../core/data/relationship.service';
import { Item } from '../../../core/shared/item.model';
import { combineLatest as observableCombineLatest, of as observableOf, zip as observableZip } from 'rxjs';
import { MetadataValue } from '../../../core/shared/metadata.models';
import { MetadatumRepresentation } from '../../../core/shared/metadata-representation/metadatum/metadatum-representation.model';
import { filter, map, switchMap } from 'rxjs/operators';
import { getSucceededRemoteData } from '../../../core/shared/operators';
import { Relationship } from '../../../core/shared/item-relationships/relationship.model';
import { ItemMetadataRepresentation } from '../../../core/shared/metadata-representation/item/item-metadata-representation.model';
@Component({ @Component({
selector: 'ds-metadata-representation-list', selector: 'ds-metadata-representation-list',
@@ -8,13 +18,25 @@ import { ItemViewMode } from '../../../shared/items/item-type-decorator';
}) })
/** /**
* This component is used for displaying metadata * This component is used for displaying metadata
* It expects a list of MetadataRepresentation objects and a label to put on top of the list * It expects an item and a metadataField to fetch metadata
* It expects an itemType to resolve the metadata to a an item
* It expects a label to put on top of the list
*/ */
export class MetadataRepresentationListComponent { export class MetadataRepresentationListComponent implements OnInit {
/** /**
* A list of metadata-representations to display * The parent of the list of related items to display
*/ */
@Input() representations: MetadataRepresentation[]; @Input() parentItem: Item;
/**
* The type of item to create a representation of
*/
@Input() itemType: string;
/**
* The metadata field to use for fetching metadata from the item
*/
@Input() metadataField: string;
/** /**
* An i18n label to use as a title for the list * An i18n label to use as a title for the list
@@ -22,8 +44,91 @@ export class MetadataRepresentationListComponent {
@Input() label: string; @Input() label: string;
/** /**
* The view-mode we're currently on * The max amount of representations to display
* @type {ElementViewMode} * Defaults to 10
* The default can optionally be overridden by providing the limit as input to the component
*/ */
viewMode = ItemViewMode.Metadata; @Input() limit = 10;
/**
* A list of metadata-representations to display
*/
representations$: Observable<MetadataRepresentation[]>;
/**
* The originally provided limit
* Used for resetting the limit to the original value when collapsing the list
*/
originalLimit: number;
/**
* The total amount of metadata values available
*/
total: number;
constructor(public relationshipService: RelationshipService) {
}
ngOnInit(): void {
this.originalLimit = this.limit;
this.setRepresentations();
}
/**
* Initialize the metadata representations
*/
setRepresentations() {
const metadata = this.parentItem.findMetadataSortedByPlace(this.metadataField);
this.total = metadata.length;
this.representations$ = this.resolveMetadataRepresentations(metadata);
}
/**
* Resolve a list of metadata values to a list of metadata representations
* @param metadata
*/
resolveMetadataRepresentations(metadata: MetadataValue[]): Observable<MetadataRepresentation[]> {
return observableZip(
...metadata
.slice(0, this.limit)
.map((metadatum: any) => Object.assign(new MetadataValue(), metadatum))
.map((metadatum: MetadataValue) => {
if (metadatum.isVirtual) {
return this.relationshipService.findById(metadatum.virtualValue).pipe(
getSucceededRemoteData(),
switchMap((relRD: RemoteData<Relationship>) =>
observableCombineLatest(relRD.payload.leftItem, relRD.payload.rightItem).pipe(
filter(([leftItem, rightItem]) => leftItem.hasSucceeded && rightItem.hasSucceeded),
map(([leftItem, rightItem]) => {
if (leftItem.payload.id === this.parentItem.id) {
return rightItem.payload;
} else if (rightItem.payload.id === this.parentItem.id) {
return leftItem.payload;
}
}),
map((item: Item) => Object.assign(new ItemMetadataRepresentation(metadatum), item))
)
));
} else {
return observableOf(Object.assign(new MetadatumRepresentation(this.itemType), metadatum));
}
})
);
}
/**
* Expand the list to display all metadata representations
*/
viewMore() {
this.limit = 9999;
this.setRepresentations();
}
/**
* Collapse the list to display the originally displayed metadata representations
*/
viewLess() {
this.limit = this.originalLimit;
this.setRepresentations();
}
} }

View File

@@ -1,6 +1,12 @@
import { Component, Input } from '@angular/core'; import { Component, HostBinding, Input, OnDestroy, OnInit } from '@angular/core';
import { Item } from '../../../core/shared/item.model'; import { Item } from '../../../core/shared/item.model';
import { ItemViewMode } from '../../../shared/items/item-type-decorator'; import { Observable } from 'rxjs/internal/Observable';
import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list';
import { RelationshipService } from '../../../core/data/relationship.service';
import { FindAllOptions } from '../../../core/data/request.models';
import { Subscription } from 'rxjs/internal/Subscription';
import { ViewMode } from '../../../core/shared/view-mode.model';
@Component({ @Component({
selector: 'ds-related-items', selector: 'ds-related-items',
@@ -9,22 +15,94 @@ import { ItemViewMode } from '../../../shared/items/item-type-decorator';
}) })
/** /**
* This component is used for displaying relations between items * This component is used for displaying relations between items
* It expects a list of items to display and a label to put on top * It expects a parent item and relationship type, as well as a label to display on top
*/ */
export class RelatedItemsComponent { export class RelatedItemsComponent implements OnInit, OnDestroy {
/** /**
* A list of items to display * The parent of the list of related items to display
*/ */
@Input() items: Item[]; @Input() parentItem: Item;
/**
* The label of the relationship type to display
* Used in sending a search request to the REST API
*/
@Input() relationType: string;
/**
* Default options to start a search request with
* Optional input, should you wish a different page size (or other options)
*/
@Input() options = Object.assign(new FindAllOptions(), { elementsPerPage: 5 });
/** /**
* An i18n label to use as a title for the list (usually describes the relation) * An i18n label to use as a title for the list (usually describes the relation)
*/ */
@Input() label: string; @Input() label: string;
/**
* Completely hide the component until there's at least one item visible
*/
@HostBinding('class.d-none') hidden = true;
/**
* The list of related items
*/
items$: Observable<RemoteData<PaginatedList<Item>>>;
/**
* Search options for displaying all elements in a list
*/
allOptions = Object.assign(new FindAllOptions(), { elementsPerPage: 9999 });
/** /**
* The view-mode we're currently on * The view-mode we're currently on
* @type {ElementViewMode} * @type {ElementViewMode}
*/ */
viewMode = ItemViewMode.Element; viewMode = ViewMode.ListElement;
/**
* Whether or not the list is currently expanded to show all related items
*/
showingAll = false;
/**
* Subscription on items used to update the "hidden" property of this component
*/
itemSub: Subscription;
constructor(public relationshipService: RelationshipService) {
}
ngOnInit(): void {
this.items$ = this.relationshipService.getRelatedItemsByLabel(this.parentItem, this.relationType, this.options);
this.itemSub = this.items$.subscribe((itemsRD: RemoteData<PaginatedList<Item>>) => {
this.hidden = !(itemsRD.hasSucceeded && itemsRD.payload && itemsRD.payload.page.length > 0);
});
}
/**
* Expand the list to display all related items
*/
viewMore() {
this.items$ = this.relationshipService.getRelatedItemsByLabel(this.parentItem, this.relationType, this.allOptions);
this.showingAll = true;
}
/**
* Collapse the list to display the originally displayed items
*/
viewLess() {
this.items$ = this.relationshipService.getRelatedItemsByLabel(this.parentItem, this.relationType, this.options);
this.showingAll = false;
}
/**
* Unsubscribe from the item subscription
*/
ngOnDestroy(): void {
if (this.itemSub) {
this.itemSub.unsubscribe();
}
}
} }

View File

@@ -1,5 +1,11 @@
<ds-metadata-field-wrapper *ngIf="items && items.length > 0" [label]="label"> <ds-metadata-field-wrapper *ngIf="(items$ | async)?.payload?.page?.length > 0" [label]="label">
<ds-item-type-switcher *ngFor="let item of items" <ds-listable-object-component-loader *ngFor="let item of (items$ | async)?.payload?.page"
[object]="item" [viewMode]="viewMode"> [object]="item" [viewMode]="viewMode">
</ds-item-type-switcher> </ds-listable-object-component-loader>
<div *ngIf="(items$ | async)?.payload?.page?.length < (items$ | async)?.payload?.totalElements" class="mt-2" id="view-more">
<a [routerLink]="" (click)="viewMore()">{{'item.page.related-items.view-more' | translate}}</a>
</div>
<div *ngIf="showingAll" class="mt-2" id="view-less">
<a [routerLink]="" (click)="viewLess()">{{'item.page.related-items.view-less' | translate}}</a>
</div>
</ds-metadata-field-wrapper> </ds-metadata-field-wrapper>

View File

@@ -2,35 +2,50 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core';
import { RelatedItemsComponent } from './related-items-component'; import { RelatedItemsComponent } from './related-items-component';
import { Item } from '../../../core/shared/item.model'; import { Item } from '../../../core/shared/item.model';
import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list'; import { PaginatedList } from '../../../core/data/paginated-list';
import { PageInfo } from '../../../core/shared/page-info.model'; import { PageInfo } from '../../../core/shared/page-info.model';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { createRelationshipsObservable } from '../item-types/shared/item.component.spec'; import { createRelationshipsObservable } from '../item-types/shared/item.component.spec';
import { of as observableOf } from 'rxjs';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/testing/utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/testing/utils';
import { RelationshipService } from '../../../core/data/relationship.service';
import { TranslateModule } from '@ngx-translate/core';
const parentItem: Item = Object.assign(new Item(), {
bundles: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])),
metadata: [],
relationships: createRelationshipsObservable()
});
const mockItem1: Item = Object.assign(new Item(), { const mockItem1: Item = Object.assign(new Item(), {
bitstreams: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])), bundles: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])),
metadata: [], metadata: [],
relationships: createRelationshipsObservable() relationships: createRelationshipsObservable()
}); });
const mockItem2: Item = Object.assign(new Item(), { const mockItem2: Item = Object.assign(new Item(), {
bitstreams: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])), bundles: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), [])),
metadata: [], metadata: [],
relationships: createRelationshipsObservable() relationships: createRelationshipsObservable()
}); });
const mockItems = [mockItem1, mockItem2]; const mockItems = [mockItem1, mockItem2];
const relationType = 'isItemOfItem';
let relationshipService: RelationshipService;
describe('RelatedItemsComponent', () => { describe('RelatedItemsComponent', () => {
let comp: RelatedItemsComponent; let comp: RelatedItemsComponent;
let fixture: ComponentFixture<RelatedItemsComponent>; let fixture: ComponentFixture<RelatedItemsComponent>;
beforeEach(async(() => { beforeEach(async(() => {
relationshipService = jasmine.createSpyObj('relationshipService',
{
getRelatedItemsByLabel: createSuccessfulRemoteDataObject$(new PaginatedList(new PageInfo(), mockItems)),
}
);
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [], imports: [TranslateModule.forRoot()],
declarations: [RelatedItemsComponent], declarations: [RelatedItemsComponent],
providers: [], providers: [
{ provide: RelationshipService, useValue: relationshipService }
],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(RelatedItemsComponent, { }).overrideComponent(RelatedItemsComponent, {
set: {changeDetection: ChangeDetectionStrategy.Default} set: {changeDetection: ChangeDetectionStrategy.Default}
@@ -40,13 +55,42 @@ describe('RelatedItemsComponent', () => {
beforeEach(async(() => { beforeEach(async(() => {
fixture = TestBed.createComponent(RelatedItemsComponent); fixture = TestBed.createComponent(RelatedItemsComponent);
comp = fixture.componentInstance; comp = fixture.componentInstance;
comp.items = mockItems; comp.parentItem = parentItem;
comp.relationType = relationType;
fixture.detectChanges(); fixture.detectChanges();
})); }));
it(`should load ${mockItems.length} item-type-switcher components`, () => { it(`should load ${mockItems.length} item-type-switcher components`, () => {
const fields = fixture.debugElement.queryAll(By.css('ds-item-type-switcher')); const fields = fixture.debugElement.queryAll(By.css('ds-listable-object-component-loader'));
expect(fields.length).toBe(mockItems.length); expect(fields.length).toBe(mockItems.length);
}); });
describe('when viewMore is called', () => {
beforeEach(() => {
comp.viewMore();
});
it('should call relationship-service\'s getRelatedItemsByLabel with the correct arguments', () => {
expect(relationshipService.getRelatedItemsByLabel).toHaveBeenCalledWith(parentItem, relationType, comp.allOptions);
});
it('should set showingAll to true', () => {
expect(comp.showingAll).toEqual(true);
});
});
describe('when viewLess is called', () => {
beforeEach(() => {
comp.viewLess();
});
it('should call relationship-service\'s getRelatedItemsByLabel with the correct arguments', () => {
expect(relationshipService.getRelatedItemsByLabel).toHaveBeenCalledWith(parentItem, relationType, comp.options);
});
it('should set showingAll to false', () => {
expect(comp.showingAll).toEqual(false);
});
});
}); });

View File

@@ -0,0 +1,43 @@
import { LookupGuard } from './lookup-guard';
import { NgModule } from '@angular/core';
import { RouterModule, UrlSegment } from '@angular/router';
import { ObjectNotFoundComponent } from './objectnotfound/objectnotfound.component';
import { hasValue, isNotEmpty } from '../shared/empty.util';
@NgModule({
imports: [
RouterModule.forChild([
{
matcher: urlMatcher,
canActivate: [LookupGuard],
component: ObjectNotFoundComponent }
])
],
providers: [
LookupGuard
]
})
export class LookupRoutingModule {
}
export function urlMatcher(url) {
// The expected path is :idType/:id
const idType = url[0].path;
// Allow for handles that are delimited with a forward slash.
const id = url
.slice(1)
.map((us: UrlSegment) => us.path)
.join('/');
if (isNotEmpty(idType) && isNotEmpty(id)) {
return {
consumed: url,
posParams: {
idType: new UrlSegment(idType, {}),
id: new UrlSegment(id, {})
}
};
}
return null;
}

View File

@@ -0,0 +1,23 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { LookupRoutingModule } from './lookup-by-id-routing.module';
import { ObjectNotFoundComponent } from './objectnotfound/objectnotfound.component';
import { DsoRedirectDataService } from '../core/data/dso-redirect-data.service';
@NgModule({
imports: [
LookupRoutingModule,
CommonModule,
SharedModule,
],
declarations: [
ObjectNotFoundComponent
],
providers: [
DsoRedirectDataService
]
})
export class LookupIdModule {
}

View File

@@ -0,0 +1,50 @@
import { LookupGuard } from './lookup-guard';
import { of as observableOf } from 'rxjs';
import { IdentifierType } from '../core/data/request.models';
describe('LookupGuard', () => {
let dsoService: any;
let guard: any;
beforeEach(() => {
dsoService = {
findById: jasmine.createSpy('findById').and.returnValue(observableOf({ hasFailed: false,
hasSucceeded: true }))
};
guard = new LookupGuard(dsoService);
});
it('should call findById with handle params', () => {
const scopedRoute = {
params: {
id: '1234',
idType: '123456789'
}
};
guard.canActivate(scopedRoute as any, undefined);
expect(dsoService.findById).toHaveBeenCalledWith('123456789/1234', IdentifierType.HANDLE)
});
it('should call findById with handle params', () => {
const scopedRoute = {
params: {
id: '123456789%2F1234',
idType: 'handle'
}
};
guard.canActivate(scopedRoute as any, undefined);
expect(dsoService.findById).toHaveBeenCalledWith('123456789%2F1234', IdentifierType.HANDLE)
});
it('should call findById with UUID params', () => {
const scopedRoute = {
params: {
id: '34cfed7c-f597-49ef-9cbe-ea351f0023c2',
idType: 'uuid'
}
};
guard.canActivate(scopedRoute as any, undefined);
expect(dsoService.findById).toHaveBeenCalledWith('34cfed7c-f597-49ef-9cbe-ea351f0023c2', IdentifierType.UUID)
});
});

View File

@@ -0,0 +1,53 @@
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { IdentifierType } from '../core/data/request.models';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { RemoteData } from '../core/data/remote-data';
import { FindByIDRequest } from '../core/data/request.models';
import { DsoRedirectDataService } from '../core/data/dso-redirect-data.service';
interface LookupParams {
type: IdentifierType;
id: string;
}
@Injectable()
export class LookupGuard implements CanActivate {
constructor(private dsoService: DsoRedirectDataService) {
}
canActivate(route: ActivatedRouteSnapshot, state:RouterStateSnapshot): Observable<boolean> {
const params = this.getLookupParams(route);
return this.dsoService.findById(params.id, params.type).pipe(
map((response: RemoteData<FindByIDRequest>) => response.hasFailed)
);
}
private getLookupParams(route: ActivatedRouteSnapshot): LookupParams {
let type;
let id;
const idType = route.params.idType;
// If the idType is not recognized, assume a legacy handle request (handle/prefix/id)
if (idType !== IdentifierType.HANDLE && idType !== IdentifierType.UUID) {
type = IdentifierType.HANDLE;
const prefix = route.params.idType;
const handleId = route.params.id;
id = `${prefix}/${handleId}`;
} else if (route.params.idType === IdentifierType.HANDLE) {
type = IdentifierType.HANDLE;
id = route.params.id;
} else {
type = IdentifierType.UUID;
id = route.params.id;
}
return {
type: type,
id: id
};
}
}

View File

@@ -0,0 +1,8 @@
<div class="object-not-found container">
<h1>{{"error.identifier" | translate}}</h1>
<h2><small><em>{{missingItem}}</em></small></h2>
<br />
<p class="text-center">
<a routerLink="/home" class="btn btn-primary">{{"404.link.home-page" | translate}}</a>
</p>
</div>

View File

@@ -0,0 +1,79 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ObjectNotFoundComponent } from './objectnotfound.component';
import { ActivatedRouteStub } from '../../shared/testing/active-router-stub';
import { of as observableOf } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
describe('ObjectNotFoundComponent', () => {
let comp: ObjectNotFoundComponent;
let fixture: ComponentFixture<ObjectNotFoundComponent>;
const testUUID = '34cfed7c-f597-49ef-9cbe-ea351f0023c2';
const uuidType = 'uuid';
const handlePrefix = '123456789';
const handleId = '22';
const activatedRouteStub = Object.assign(new ActivatedRouteStub(), {
params: observableOf({id: testUUID, idType: uuidType})
});
const activatedRouteStubHandle = Object.assign(new ActivatedRouteStub(), {
params: observableOf({id: handleId, idType: handlePrefix})
});
describe('uuid request', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot()
], providers: [
{provide: ActivatedRoute, useValue: activatedRouteStub}
],
declarations: [ObjectNotFoundComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ObjectNotFoundComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
});
it('should create instance', () => {
expect(comp).toBeDefined()
});
it('should have id and idType', () => {
expect(comp.id).toEqual(testUUID);
expect(comp.idType).toEqual(uuidType);
expect(comp.missingItem).toEqual('uuid: ' + testUUID);
});
});
describe( 'legacy handle request', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot()
], providers: [
{provide: ActivatedRoute, useValue: activatedRouteStubHandle}
],
declarations: [ObjectNotFoundComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ObjectNotFoundComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
});
it('should have handle prefix and id', () => {
expect(comp.id).toEqual(handleId);
expect(comp.idType).toEqual(handlePrefix);
expect(comp.missingItem).toEqual('handle: ' + handlePrefix + '/' + handleId);
});
});
});

View File

@@ -0,0 +1,43 @@
import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
/**
* This component representing the `PageNotFound` DSpace page.
*/
@Component({
selector: 'ds-objnotfound',
styleUrls: ['./objectnotfound.component.scss'],
templateUrl: './objectnotfound.component.html',
changeDetection: ChangeDetectionStrategy.Default
})
export class ObjectNotFoundComponent implements OnInit {
idType: string;
id: string;
missingItem: string;
/**
* Initialize instance variables
*
* @param {AuthService} authservice
* @param {ServerResponseService} responseService
*/
constructor(private route: ActivatedRoute) {
route.params.subscribe((params) => {
this.idType = params.idType;
this.id = params.id;
})
}
ngOnInit(): void {
if (this.idType.startsWith('handle') || this.idType.startsWith('uuid')) {
this.missingItem = this.idType + ': ' + this.id;
} else {
this.missingItem = 'handle: ' + this.idType + '/' + this.id;
}
}
}

View File

@@ -7,7 +7,6 @@ import { TranslateService } from '@ngx-translate/core';
import { SubmissionState } from '../../submission/submission.reducers'; import { SubmissionState } from '../../submission/submission.reducers';
import { AuthService } from '../../core/auth/auth.service'; import { AuthService } from '../../core/auth/auth.service';
import { MyDSpaceResult } from '../my-dspace-result.model';
import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { NotificationsService } from '../../shared/notifications/notifications.service'; import { NotificationsService } from '../../shared/notifications/notifications.service';
import { NotificationOptions } from '../../shared/notifications/models/notification-options.model'; import { NotificationOptions } from '../../shared/notifications/models/notification-options.model';
@@ -15,6 +14,7 @@ import { UploaderOptions } from '../../shared/uploader/uploader-options.model';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
import { NotificationType } from '../../shared/notifications/models/notification-type'; import { NotificationType } from '../../shared/notifications/models/notification-type';
import { hasValue } from '../../shared/empty.util'; import { hasValue } from '../../shared/empty.util';
import { SearchResult } from '../../+search-page/search-result.model';
/** /**
* This component represents the whole mydspace page header * This component represents the whole mydspace page header
@@ -25,7 +25,10 @@ import { hasValue } from '../../shared/empty.util';
templateUrl: './my-dspace-new-submission.component.html' templateUrl: './my-dspace-new-submission.component.html'
}) })
export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit { export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit {
@Output() uploadEnd = new EventEmitter<Array<MyDSpaceResult<DSpaceObject>>>(); /**
* Output that emits the workspace item when the upload has completed
*/
@Output() uploadEnd = new EventEmitter<Array<SearchResult<DSpaceObject>>>();
/** /**
* The UploaderOptions object * The UploaderOptions object

View File

@@ -39,7 +39,8 @@
</button> </button>
</div> </div>
<ds-my-dspace-results [searchResults]="resultsRD$ | async" <ds-my-dspace-results [searchResults]="resultsRD$ | async"
[searchConfig]="searchOptions$ | async"></ds-my-dspace-results> [searchConfig]="searchOptions$ | async"
[context]="context$ | async"></ds-my-dspace-results>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -15,7 +15,6 @@ import { SortDirection, SortOptions } from '../core/cache/models/sort-options.mo
import { CommunityDataService } from '../core/data/community-data.service'; import { CommunityDataService } from '../core/data/community-data.service';
import { HostWindowService } from '../shared/host-window.service'; import { HostWindowService } from '../shared/host-window.service';
import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model';
import { RemoteData } from '../core/data/remote-data';
import { MyDSpacePageComponent, SEARCH_CONFIG_SERVICE } from './my-dspace-page.component'; import { MyDSpacePageComponent, SEARCH_CONFIG_SERVICE } from './my-dspace-page.component';
import { RouteService } from '../core/services/route.service'; import { RouteService } from '../core/services/route.service';
import { routeServiceStub } from '../shared/testing/route-service-stub'; import { routeServiceStub } from '../shared/testing/route-service-stub';
@@ -23,7 +22,7 @@ import { SearchConfigurationServiceStub } from '../shared/testing/search-configu
import { SearchService } from '../+search-page/search-service/search.service'; import { SearchService } from '../+search-page/search-service/search.service';
import { SearchConfigurationService } from '../+search-page/search-service/search-configuration.service'; import { SearchConfigurationService } from '../+search-page/search-service/search-configuration.service';
import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model'; import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model';
import { SearchSidebarService } from '../+search-page/search-sidebar/search-sidebar.service'; import { SidebarService } from '../shared/sidebar/sidebar.service';
import { SearchFilterService } from '../+search-page/search-filters/search-filter/search-filter.service'; import { SearchFilterService } from '../+search-page/search-filters/search-filter/search-filter.service';
import { RoleDirective } from '../shared/roles/role.directive'; import { RoleDirective } from '../shared/roles/role.directive';
import { RoleService } from '../core/roles/role.service'; import { RoleService } from '../core/roles/role.service';
@@ -50,6 +49,7 @@ describe('MyDSpacePageComponent', () => {
const mockResults = createSuccessfulRemoteDataObject$(['test', 'data']); const mockResults = createSuccessfulRemoteDataObject$(['test', 'data']);
const searchServiceStub = jasmine.createSpyObj('SearchService', { const searchServiceStub = jasmine.createSpyObj('SearchService', {
search: mockResults, search: mockResults,
getEndpoint: observableOf('discover/search/objects'),
getSearchLink: '/mydspace', getSearchLink: '/mydspace',
getScopes: observableOf(['test-scope']), getScopes: observableOf(['test-scope']),
setServiceOptions: {} setServiceOptions: {}
@@ -76,6 +76,7 @@ describe('MyDSpacePageComponent', () => {
scope: scopeParam scope: scopeParam
}) })
}; };
const sidebarService = { const sidebarService = {
isCollapsed: observableOf(true), isCollapsed: observableOf(true),
collapse: () => this.isCollapsed = observableOf(true), collapse: () => this.isCollapsed = observableOf(true),
@@ -108,7 +109,7 @@ describe('MyDSpacePageComponent', () => {
}) })
}, },
{ {
provide: SearchSidebarService, provide: SidebarService,
useValue: sidebarService useValue: sidebarService
}, },
{ {

View File

@@ -8,7 +8,7 @@ import {
} from '@angular/core'; } from '@angular/core';
import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { switchMap, tap, } from 'rxjs/operators'; import { map, switchMap, tap, } from 'rxjs/operators';
import { PaginatedList } from '../core/data/paginated-list'; import { PaginatedList } from '../core/data/paginated-list';
import { RemoteData } from '../core/data/remote-data'; import { RemoteData } from '../core/data/remote-data';
@@ -17,10 +17,9 @@ import { pushInOut } from '../shared/animations/push';
import { HostWindowService } from '../shared/host-window.service'; import { HostWindowService } from '../shared/host-window.service';
import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model'; import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model';
import { SearchService } from '../+search-page/search-service/search.service'; import { SearchService } from '../+search-page/search-service/search.service';
import { SearchSidebarService } from '../+search-page/search-sidebar/search-sidebar.service'; import { SidebarService } from '../shared/sidebar/sidebar.service';
import { hasValue } from '../shared/empty.util'; import { hasValue } from '../shared/empty.util';
import { getSucceededRemoteData } from '../core/shared/operators'; import { getSucceededRemoteData } from '../core/shared/operators';
import { MyDSpaceResult } from './my-dspace-result.model';
import { MyDSpaceResponseParsingService } from '../core/data/mydspace-response-parsing.service'; import { MyDSpaceResponseParsingService } from '../core/data/mydspace-response-parsing.service';
import { SearchConfigurationOption } from '../+search-page/search-switch-configuration/search-configuration-option.model'; import { SearchConfigurationOption } from '../+search-page/search-switch-configuration/search-configuration-option.model';
import { RoleType } from '../core/roles/role-types'; import { RoleType } from '../core/roles/role-types';
@@ -28,6 +27,8 @@ import { SearchConfigurationService } from '../+search-page/search-service/searc
import { MyDSpaceConfigurationService } from './my-dspace-configuration.service'; import { MyDSpaceConfigurationService } from './my-dspace-configuration.service';
import { ViewMode } from '../core/shared/view-mode.model'; import { ViewMode } from '../core/shared/view-mode.model';
import { MyDSpaceRequest } from '../core/data/request.models'; import { MyDSpaceRequest } from '../core/data/request.models';
import { SearchResult } from '../+search-page/search-result.model';
import { Context } from '../core/shared/context.model';
export const MYDSPACE_ROUTE = '/mydspace'; export const MYDSPACE_ROUTE = '/mydspace';
export const SEARCH_CONFIG_SERVICE: InjectionToken<SearchConfigurationService> = new InjectionToken<SearchConfigurationService>('searchConfigurationService'); export const SEARCH_CONFIG_SERVICE: InjectionToken<SearchConfigurationService> = new InjectionToken<SearchConfigurationService>('searchConfigurationService');
@@ -63,7 +64,7 @@ export class MyDSpacePageComponent implements OnInit {
/** /**
* The current search results * The current search results
*/ */
resultsRD$: BehaviorSubject<RemoteData<PaginatedList<MyDSpaceResult<DSpaceObject>>>> = new BehaviorSubject(null); resultsRD$: BehaviorSubject<RemoteData<PaginatedList<SearchResult<DSpaceObject>>>> = new BehaviorSubject(null);
/** /**
* The current paginated search options * The current paginated search options
@@ -93,10 +94,15 @@ export class MyDSpacePageComponent implements OnInit {
/** /**
* List of available view mode * List of available view mode
*/ */
viewModeList = [ViewMode.List, ViewMode.Detail]; viewModeList = [ViewMode.ListElement, ViewMode.DetailedListElement];
/**
* The current context of this page: workspace or workflow
*/
context$: Observable<Context>;
constructor(private service: SearchService, constructor(private service: SearchService,
private sidebarService: SearchSidebarService, private sidebarService: SidebarService,
private windowService: HostWindowService, private windowService: HostWindowService,
@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: MyDSpaceConfigurationService) { @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: MyDSpaceConfigurationService) {
this.isXsOrSm$ = this.windowService.isXsOrSm(); this.isXsOrSm$ = this.windowService.isXsOrSm();
@@ -111,21 +117,35 @@ export class MyDSpacePageComponent implements OnInit {
* *
* Listen to changes in the scope * Listen to changes in the scope
* If something changes, update the list of scopes for the dropdown * If something changes, update the list of scopes for the dropdown
*
* Listen to changes in the configuration
* If something changes, update the current context
*/ */
ngOnInit(): void { ngOnInit(): void {
this.configurationList$ = this.searchConfigService.getAvailableConfigurationOptions(); this.configurationList$ = this.searchConfigService.getAvailableConfigurationOptions();
this.searchOptions$ = this.searchConfigService.paginatedSearchOptions; this.searchOptions$ = this.searchConfigService.paginatedSearchOptions;
this.sub = this.searchOptions$.pipe( this.sub = this.searchOptions$.pipe(
tap(() => this.resultsRD$.next(null)), tap(() => this.resultsRD$.next(null)),
switchMap((options: PaginatedSearchOptions) => this.service.search(options).pipe(getSucceededRemoteData()))) switchMap((options: PaginatedSearchOptions) => this.service.search(options).pipe(getSucceededRemoteData())))
.subscribe((results) => { .subscribe((results) => {
this.resultsRD$.next(results); this.resultsRD$.next(results);
}); });
this.scopeListRD$ = this.searchConfigService.getCurrentScope('').pipe( this.scopeListRD$ = this.searchConfigService.getCurrentScope('').pipe(
switchMap((scopeId) => this.service.getScopes(scopeId)) switchMap((scopeId) => this.service.getScopes(scopeId))
); );
this.context$ = this.searchConfigService.getCurrentConfiguration('workspace')
.pipe(
map((configuration: string) => {
if (configuration === 'workspace') {
return Context.Workspace
} else {
return Context.Workflow
}
})
);
} }
/** /**

View File

@@ -7,19 +7,20 @@ import { MyDspacePageRoutingModule } from './my-dspace-page-routing.module';
import { MyDSpacePageComponent } from './my-dspace-page.component'; import { MyDSpacePageComponent } from './my-dspace-page.component';
import { SearchPageModule } from '../+search-page/search-page.module'; import { SearchPageModule } from '../+search-page/search-page.module';
import { MyDSpaceResultsComponent } from './my-dspace-results/my-dspace-results.component'; import { MyDSpaceResultsComponent } from './my-dspace-results/my-dspace-results.component';
import { WorkspaceitemMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component'; import { WorkspaceItemSearchResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/workspace-item-search-result/workspace-item-search-result-list-element.component';
import { ItemMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component'; import { ClaimedSearchResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/claimed-search-result/claimed-search-result-list-element.component';
import { WorkflowitemMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component'; import { PoolSearchResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/pool-search-result/pool-search-result-list-element.component';
import { ClaimedMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component';
import { PoolMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component';
import { MyDSpaceNewSubmissionComponent } from './my-dspace-new-submission/my-dspace-new-submission.component'; import { MyDSpaceNewSubmissionComponent } from './my-dspace-new-submission/my-dspace-new-submission.component';
import { ItemMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component'; import { ItemSearchResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/item-search-result/item-search-result-detail-element.component';
import { WorkspaceitemMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component'; import { WorkspaceItemSearchResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/workspace-item-search-result/workspace-item-search-result-detail-element.component';
import { WorkflowitemMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component'; import { WorkflowItemSearchResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/workflow-item-search-result/workflow-item-search-result-detail-element.component';
import { ClaimedMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component'; import { ClaimedTaskSearchResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/claimed-task-search-result/claimed-task-search-result-detail-element.component';
import { PoolMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-lement.component';
import { MyDSpaceGuard } from './my-dspace.guard'; import { MyDSpaceGuard } from './my-dspace.guard';
import { MyDSpaceConfigurationService } from './my-dspace-configuration.service'; import { MyDSpaceConfigurationService } from './my-dspace-configuration.service';
import { SearchResultListElementComponent } from '../shared/object-list/search-result-list-element/search-result-list-element.component';
import { ItemSearchResultListElementSubmissionComponent } from '../shared/object-list/my-dspace-result-list-element/item-search-result/item-search-result-list-element-submission.component';
import { WorkflowItemSearchResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/workflow-item-search-result/workflow-item-search-result-list-element.component';
import { PoolSearchResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/pool-search-result/pool-search-result-detail-element.component';
@NgModule({ @NgModule({
imports: [ imports: [
@@ -31,33 +32,34 @@ import { MyDSpaceConfigurationService } from './my-dspace-configuration.service'
declarations: [ declarations: [
MyDSpacePageComponent, MyDSpacePageComponent,
MyDSpaceResultsComponent, MyDSpaceResultsComponent,
ItemMyDSpaceResultListElementComponent, WorkspaceItemSearchResultListElementComponent,
WorkspaceitemMyDSpaceResultListElementComponent, WorkflowItemSearchResultListElementComponent,
WorkflowitemMyDSpaceResultListElementComponent, ClaimedSearchResultListElementComponent,
ClaimedMyDSpaceResultListElementComponent, PoolSearchResultListElementComponent,
PoolMyDSpaceResultListElementComponent, ItemSearchResultDetailElementComponent,
ItemMyDSpaceResultDetailElementComponent, WorkspaceItemSearchResultDetailElementComponent,
WorkspaceitemMyDSpaceResultDetailElementComponent, WorkflowItemSearchResultDetailElementComponent,
WorkflowitemMyDSpaceResultDetailElementComponent, ClaimedTaskSearchResultDetailElementComponent,
ClaimedMyDSpaceResultDetailElementComponent, PoolSearchResultDetailElementComponent,
PoolMyDSpaceResultDetailElementComponent, MyDSpaceNewSubmissionComponent,
MyDSpaceNewSubmissionComponent ItemSearchResultListElementSubmissionComponent
], ],
providers: [ providers: [
MyDSpaceGuard, MyDSpaceGuard,
MyDSpaceConfigurationService MyDSpaceConfigurationService
], ],
entryComponents: [ entryComponents: [
ItemMyDSpaceResultListElementComponent, SearchResultListElementComponent,
WorkspaceitemMyDSpaceResultListElementComponent, WorkspaceItemSearchResultListElementComponent,
WorkflowitemMyDSpaceResultListElementComponent, WorkflowItemSearchResultListElementComponent,
ClaimedMyDSpaceResultListElementComponent, ClaimedSearchResultListElementComponent,
PoolMyDSpaceResultListElementComponent, PoolSearchResultListElementComponent,
ItemMyDSpaceResultDetailElementComponent, ItemSearchResultDetailElementComponent,
WorkspaceitemMyDSpaceResultDetailElementComponent, WorkspaceItemSearchResultDetailElementComponent,
WorkflowitemMyDSpaceResultDetailElementComponent, WorkflowItemSearchResultDetailElementComponent,
ClaimedMyDSpaceResultDetailElementComponent, ClaimedTaskSearchResultDetailElementComponent,
PoolMyDSpaceResultDetailElementComponent PoolSearchResultDetailElementComponent,
ItemSearchResultListElementSubmissionComponent
] ]
}) })

View File

@@ -1,19 +0,0 @@
import { DSpaceObject } from '../core/shared/dspace-object.model';
import { MetadataMap } from '../core/shared/metadata.models';
import { ListableObject } from '../shared/object-collection/shared/listable-object.model';
/**
* Represents a search result object of a certain (<T>) DSpaceObject
*/
export class MyDSpaceResult<T extends DSpaceObject> implements ListableObject {
/**
* The DSpaceObject that was found
*/
indexableObject: T;
/**
* The metadata that was used to find this item, hithighlighted
*/
hitHighlights: MetadataMap;
}

View File

@@ -4,7 +4,8 @@
[hasBorder]="hasBorder" [hasBorder]="hasBorder"
[sortConfig]="searchConfig.sort" [sortConfig]="searchConfig.sort"
[objects]="searchResults" [objects]="searchResults"
[hideGear]="true"> [hideGear]="true"
[context]="context">
</ds-viewable-collection> </ds-viewable-collection>
</div> </div>
<ds-loading *ngIf="isLoading()" message="{{'loading.mydspace-results' | translate}}"></ds-loading> <ds-loading *ngIf="isLoading()" message="{{'loading.mydspace-results' | translate}}"></ds-loading>

View File

@@ -1,13 +1,13 @@
import { Component, Input } from '@angular/core'; import { Component, Input } from '@angular/core';
import { RemoteData } from '../../core/data/remote-data'; import { RemoteData } from '../../core/data/remote-data';
import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { fadeIn, fadeInOut } from '../../shared/animations/fade'; import { fadeIn, fadeInOut } from '../../shared/animations/fade';
import { MyDSpaceResult } from '../my-dspace-result.model';
import { SearchOptions } from '../../+search-page/search-options.model'; import { SearchOptions } from '../../+search-page/search-options.model';
import { PaginatedList } from '../../core/data/paginated-list'; import { PaginatedList } from '../../core/data/paginated-list';
import { ViewMode } from '../../core/shared/view-mode.model'; import { ViewMode } from '../../core/shared/view-mode.model';
import { isEmpty } from '../../shared/empty.util'; import { isEmpty } from '../../shared/empty.util';
import { SearchResult } from '../../+search-page/search-result.model';
import { Context } from '../../core/shared/context.model';
/** /**
* Component that represents all results for mydspace page * Component that represents all results for mydspace page
@@ -25,7 +25,7 @@ export class MyDSpaceResultsComponent {
/** /**
* The actual search result objects * The actual search result objects
*/ */
@Input() searchResults: RemoteData<PaginatedList<MyDSpaceResult<DSpaceObject>>>; @Input() searchResults: RemoteData<PaginatedList<SearchResult<DSpaceObject>>>;
/** /**
* The current configuration of the search * The current configuration of the search
@@ -37,6 +37,10 @@ export class MyDSpaceResultsComponent {
*/ */
@Input() viewMode: ViewMode; @Input() viewMode: ViewMode;
/**
* The current context for the search results
*/
@Input() context: Context;
/** /**
* A boolean representing if search results entry are separated by a line * A boolean representing if search results entry are separated by a line
*/ */

View File

@@ -1,6 +1,6 @@
import { HostWindowService } from '../shared/host-window.service'; import { HostWindowService } from '../shared/host-window.service';
import { SearchService } from './search-service/search.service'; import { SearchService } from './search-service/search.service';
import { SearchSidebarService } from './search-sidebar/search-sidebar.service'; import { SidebarService } from '../shared/sidebar/sidebar.service';
import { SearchPageComponent } from './search-page.component'; import { SearchPageComponent } from './search-page.component';
import { ChangeDetectionStrategy, Component, Inject, Input, OnInit } from '@angular/core'; import { ChangeDetectionStrategy, Component, Inject, Input, OnInit } from '@angular/core';
import { pushInOut } from '../shared/animations/push'; import { pushInOut } from '../shared/animations/push';
@@ -36,7 +36,7 @@ export class ConfigurationSearchPageComponent extends SearchPageComponent implem
@Input() configuration: string; @Input() configuration: string;
constructor(protected service: SearchService, constructor(protected service: SearchService,
protected sidebarService: SearchSidebarService, protected sidebarService: SidebarService,
protected windowService: HostWindowService, protected windowService: HostWindowService,
@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService, @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService,
protected routeService: RouteService) { protected routeService: RouteService) {

View File

@@ -1,6 +1,6 @@
import { HostWindowService } from '../shared/host-window.service'; import { HostWindowService } from '../shared/host-window.service';
import { SearchService } from './search-service/search.service'; import { SearchService } from './search-service/search.service';
import { SearchSidebarService } from './search-sidebar/search-sidebar.service'; import { SidebarService } from '../shared/sidebar/sidebar.service';
import { SearchPageComponent } from './search-page.component'; import { SearchPageComponent } from './search-page.component';
import { ChangeDetectionStrategy, Component, Inject, Input, OnInit } from '@angular/core'; import { ChangeDetectionStrategy, Component, Inject, Input, OnInit } from '@angular/core';
import { pushInOut } from '../shared/animations/push'; import { pushInOut } from '../shared/animations/push';
@@ -38,7 +38,7 @@ export class FilteredSearchPageComponent extends SearchPageComponent implements
@Input() fixedFilterQuery: string; @Input() fixedFilterQuery: string;
constructor(protected service: SearchService, constructor(protected service: SearchService,
protected sidebarService: SearchSidebarService, protected sidebarService: SidebarService,
protected windowService: HostWindowService, protected windowService: HostWindowService,
@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService, @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService,
protected routeService: RouteService) { protected routeService: RouteService) {

View File

@@ -1,13 +1,12 @@
import { autoserialize, inheritSerialization } from 'cerialize'; import { autoserialize, inheritSerialization } from 'cerialize';
import { MetadataMap } from '../core/shared/metadata.models'; import { MetadataMap } from '../core/shared/metadata.models';
import { ListableObject } from '../shared/object-collection/shared/listable-object.model';
import { NormalizedObject } from '../core/cache/models/normalized-object.model'; import { NormalizedObject } from '../core/cache/models/normalized-object.model';
/** /**
* Represents a normalized version of a search result object of a certain DSpaceObject * Represents a normalized version of a search result object of a certain DSpaceObject
*/ */
@inheritSerialization(NormalizedObject) @inheritSerialization(NormalizedObject)
export class NormalizedSearchResult implements ListableObject { export class NormalizedSearchResult {
/** /**
* The UUID of the DSpaceObject that was found * The UUID of the DSpaceObject that was found
*/ */
@@ -19,5 +18,4 @@ export class NormalizedSearchResult implements ListableObject {
*/ */
@autoserialize @autoserialize
hitHighlights: MetadataMap; hitHighlights: MetadataMap;
} }

View File

@@ -1,7 +1,18 @@
<div class="facet-filter d-block mb-3 p-3" *ngIf="active$ | async"> <div class="facet-filter d-block mb-3 p-3" *ngIf="active$ | async">
<div (click)="toggle()" class="filter-name"><h5 class="d-inline-block mb-0">{{'search.filters.filter.' + filter.name + '.head'| translate}}</h5> <span class="filter-toggle fas float-right" <div (click)="toggle()" class="filter-name">
[ngClass]="(collapsed$ | async) ? 'fa-plus' : 'fa-minus'"></span></div> <h5 class="d-inline-block mb-0">
<div [@slide]="(collapsed$ | async) ? 'collapsed' : 'expanded'" (@slide.start)="startSlide($event)" (@slide.done)="finishSlide($event)" class="search-filter-wrapper" [ngClass]="{'closed' : closed}"> {{'search.filters.filter.' + filter.name + '.head'| translate}}
<ds-search-facet-filter-wrapper [filterConfig]="filter" [inPlaceSearch]="inPlaceSearch"></ds-search-facet-filter-wrapper> </h5>
</div> <span class="filter-toggle fas float-right"
[ngClass]="(collapsed$ | async) ? 'fa-plus' : 'fa-minus'">
</span>
</div>
<div [@slide]="(collapsed$ | async) ? 'collapsed' : 'expanded'"
(@slide.start)="startSlide($event)" (@slide.done)="finishSlide($event)"
class="search-filter-wrapper" [ngClass]="{'closed' : closed}">
<ds-search-facet-filter-wrapper
[filterConfig]="filter"
[inPlaceSearch]="inPlaceSearch">
</ds-search-facet-filter-wrapper>
</div>
</div> </div>

View File

@@ -138,7 +138,7 @@ describe('SearchFilterService', () => {
service.expand(mockFilterConfig.name); service.expand(mockFilterConfig.name);
}); });
it('SearchSidebarExpandAction should be dispatched to the store', () => { it('SidebarExpandAction should be dispatched to the store', () => {
expect(store.dispatch).toHaveBeenCalledWith(new SearchFilterExpandAction(mockFilterConfig.name)); expect(store.dispatch).toHaveBeenCalledWith(new SearchFilterExpandAction(mockFilterConfig.name));
}); });
}); });

View File

@@ -71,7 +71,7 @@ export class SearchFiltersComponent implements OnInit {
/** /**
* @returns {string} The base path to the search page, or the current page when inPlaceSearch is true * @returns {string} The base path to the search page, or the current page when inPlaceSearch is true
*/ */
private getSearchLink(): string { getSearchLink(): string {
if (this.inPlaceSearch) { if (this.inPlaceSearch) {
return './'; return './';
} }

View File

@@ -3,14 +3,14 @@ import { URLCombiner } from '../core/url-combiner/url-combiner';
import 'core-js/library/fn/object/entries'; import 'core-js/library/fn/object/entries';
import { SearchFilter } from './search-filter.model'; import { SearchFilter } from './search-filter.model';
import { DSpaceObjectType } from '../core/shared/dspace-object-type.model'; import { DSpaceObjectType } from '../core/shared/dspace-object-type.model';
import { SetViewMode } from '../shared/view-mode'; import { ViewMode } from '../core/shared/view-mode.model';
/** /**
* This model class represents all parameters needed to request information about a certain search request * This model class represents all parameters needed to request information about a certain search request
*/ */
export class SearchOptions { export class SearchOptions {
configuration?: string; configuration?: string;
view?: SetViewMode = SetViewMode.List; view?: ViewMode = ViewMode.ListElement;
scope?: string; scope?: string;
query?: string; query?: string;
dsoType?: DSpaceObjectType; dsoType?: DSpaceObjectType;

View File

@@ -1,43 +1,50 @@
<div class="container"> <div class="container" *ngIf="(isXsOrSm$ | async)">
<div class="search-page row"> <div class="row">
<ds-search-sidebar *ngIf="!(isXsOrSm$ | async)" class="col-{{sideBarWidth}} sidebar-md-sticky" <div class="col-12">
id="search-sidebar" <ng-template *ngTemplateOutlet="searchForm"></ng-template>
[resultCount]="(resultsRD$ | async)?.payload?.totalElements" [inPlaceSearch]="inPlaceSearch"></ds-search-sidebar>
<div class="col-12 col-md-{{12 - sideBarWidth}}">
<ds-search-form *ngIf="searchEnabled" id="search-form"
[query]="(searchOptions$ | async)?.query"
[scope]="(searchOptions$ | async)?.scope"
[currentUrl]="searchLink"
[scopes]="(scopeListRD$ | async)"
[inPlaceSearch]="inPlaceSearch">
</ds-search-form>
<ds-search-labels *ngIf="searchEnabled" [inPlaceSearch]="inPlaceSearch"></ds-search-labels>
<div class="row">
<div id="search-body"
class="row-offcanvas row-offcanvas-left"
[@pushInOut]="(isSidebarCollapsed$ | async) ? 'collapsed' : 'expanded'">
<ds-search-sidebar *ngIf="(isXsOrSm$ | async)" class="col-12"
id="search-sidebar-sm"
[resultCount]="(resultsRD$ | async)?.payload.totalElements"
(toggleSidebar)="closeSidebar()"
[ngClass]="{'active': !(isSidebarCollapsed$ | async)}">
</ds-search-sidebar>
<div id="search-content" class="col-12">
<div class="d-block d-md-none search-controls clearfix">
<ds-view-mode-switch [inPlaceSearch]="inPlaceSearch"></ds-view-mode-switch>
<button (click)="openSidebar()" aria-controls="#search-body"
class="btn btn-outline-primary float-right open-sidebar"><i
class="fas fa-sliders"></i> {{"search.sidebar.open"
| translate}}
</button>
</div>
<ds-search-results [searchResults]="resultsRD$ | async"
[searchConfig]="searchOptions$ | async"
[configuration]="configuration$ | async"
[disableHeader]="!searchEnabled"></ds-search-results>
</div>
</div>
</div>
</div>
</div> </div>
</div>
</div> </div>
<ds-page-with-sidebar [id]="'search-page'" [sidebarContent]="sidebarContent">
<div class="row">
<div class="col-12" *ngIf="!(isXsOrSm$ | async)">
<ng-template *ngTemplateOutlet="searchForm"></ng-template>
</div>
<div id="search-content" class="col-12">
<div class="d-block d-md-none search-controls clearfix">
<ds-view-mode-switch [inPlaceSearch]="inPlaceSearch"></ds-view-mode-switch>
<button (click)="openSidebar()" aria-controls="#search-body"
class="btn btn-outline-primary float-right open-sidebar"><i
class="fas fa-sliders"></i> {{"search.sidebar.open"
| translate}}
</button>
</div>
<ds-search-results [searchResults]="resultsRD$ | async"
[searchConfig]="searchOptions$ | async"
[configuration]="configuration$ | async"
[disableHeader]="!searchEnabled"></ds-search-results>
</div>
</div>
</ds-page-with-sidebar>
<ng-template #sidebarContent>
<ds-search-sidebar id="search-sidebar" *ngIf="!(isXsOrSm$ | async)"
[resultCount]="(resultsRD$ | async)?.payload?.totalElements"
[inPlaceSearch]="inPlaceSearch"></ds-search-sidebar>
<ds-search-sidebar id="search-sidebar-sm" *ngIf="(isXsOrSm$ | async)"
[resultCount]="(resultsRD$ | async)?.payload.totalElements"
(toggleSidebar)="closeSidebar()"
>
</ds-search-sidebar>
</ng-template>
<ng-template #searchForm>
<ds-search-form *ngIf="searchEnabled" id="search-form"
[query]="(searchOptions$ | async)?.query"
[scope]="(searchOptions$ | async)?.scope"
[currentUrl]="searchLink"
[scopes]="(scopeListRD$ | async)"
[inPlaceSearch]="inPlaceSearch">
</ds-search-form>
<ds-search-labels *ngIf="searchEnabled" [inPlaceSearch]="inPlaceSearch"></ds-search-labels>
</ng-template>

View File

@@ -1,52 +1,10 @@
@include media-breakpoint-down(md) { @include media-breakpoint-down(md) {
.container { .container {
width: 100%; width: 100%;
max-width: none; max-width: none;
} }
} }
/deep/ .search-controls { /deep/ .search-controls {
margin-bottom: $spacer; margin-bottom: $spacer;
} }
#search-body {
&.row-offcanvas {
width: 100%;
}
@include media-breakpoint-down(sm) {
position: relative;
&.row-offcanvas {
position: relative;
}
&.row-offcanvas-right #search-sidebar-sm {
right: -100%;
}
&.row-offcanvas-left #search-sidebar-sm {
left: -100%;
}
#search-sidebar-sm {
position: absolute;
top: 0;
width: 100%;
}
}
}
@include media-breakpoint-up(md) {
.sidebar-md-sticky {
position: sticky;
position: -webkit-sticky;
top: 0;
z-index: $zindex-sticky;
padding-top: $content-spacing;
margin-top: -$content-spacing;
align-self: flex-start;
display: block;
}
}

View File

@@ -16,7 +16,7 @@ import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap'; import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap';
import { SearchSidebarService } from './search-sidebar/search-sidebar.service'; import { SidebarService } from '../shared/sidebar/sidebar.service';
import { SearchFilterService } from './search-filters/search-filter/search-filter.service'; import { SearchFilterService } from './search-filters/search-filter/search-filter.service';
import { SearchConfigurationService } from './search-service/search-configuration.service'; import { SearchConfigurationService } from './search-service/search-configuration.service';
import { RemoteData } from '../core/data/remote-data'; import { RemoteData } from '../core/data/remote-data';
@@ -115,7 +115,7 @@ export function configureSearchComponentTestingModule(compType) {
}) })
}, },
{ {
provide: SearchSidebarService, provide: SidebarService,
useValue: sidebarService useValue: sidebarService
}, },
{ {
@@ -191,34 +191,4 @@ describe('SearchPageComponent', () => {
}); });
}); });
describe('when sidebarCollapsed is true in mobile view', () => {
let menu: HTMLElement;
beforeEach(() => {
menu = fixture.debugElement.query(By.css('#search-sidebar-sm')).nativeElement;
(comp as any).isSidebarCollapsed$ = observableOf(true);
fixture.detectChanges();
});
it('should close the sidebar', () => {
expect(menu.classList).not.toContain('active');
});
});
describe('when sidebarCollapsed is false in mobile view', () => {
let menu: HTMLElement;
beforeEach(() => {
menu = fixture.debugElement.query(By.css('#search-sidebar-sm')).nativeElement;
(comp as any).isSidebarCollapsed$ = observableOf(false);
fixture.detectChanges();
});
it('should open the menu', () => {
expect(menu.classList).toContain('active');
});
});
}); });

View File

@@ -9,7 +9,7 @@ import { HostWindowService } from '../shared/host-window.service';
import { PaginatedSearchOptions } from './paginated-search-options.model'; import { PaginatedSearchOptions } from './paginated-search-options.model';
import { SearchResult } from './search-result.model'; import { SearchResult } from './search-result.model';
import { SearchService } from './search-service/search.service'; import { SearchService } from './search-service/search.service';
import { SearchSidebarService } from './search-sidebar/search-sidebar.service'; import { SidebarService } from '../shared/sidebar/sidebar.service';
import { hasValue, isNotEmpty } from '../shared/empty.util'; import { hasValue, isNotEmpty } from '../shared/empty.util';
import { SearchConfigurationService } from './search-service/search-configuration.service'; import { SearchConfigurationService } from './search-service/search-configuration.service';
import { getSucceededRemoteData } from '../core/shared/operators'; import { getSucceededRemoteData } from '../core/shared/operators';
@@ -102,7 +102,7 @@ export class SearchPageComponent implements OnInit {
isSidebarCollapsed$: Observable<boolean>; isSidebarCollapsed$: Observable<boolean>;
constructor(protected service: SearchService, constructor(protected service: SearchService,
protected sidebarService: SearchSidebarService, protected sidebarService: SidebarService,
protected windowService: HostWindowService, protected windowService: HostWindowService,
@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService, @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService,
protected routeService: RouteService) { protected routeService: RouteService) {

View File

@@ -5,12 +5,11 @@ import { SharedModule } from '../shared/shared.module';
import { SearchPageRoutingModule } from './search-page-routing.module'; import { SearchPageRoutingModule } from './search-page-routing.module';
import { SearchPageComponent } from './search-page.component'; import { SearchPageComponent } from './search-page.component';
import { SearchResultsComponent } from './search-results/search-results.component'; import { SearchResultsComponent } from './search-results/search-results.component';
import { ItemSearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/item-search-result/item-search-result-grid-element.component';
import { CommunitySearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component' import { CommunitySearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component'
import { CollectionSearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component'; import { CollectionSearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component';
import { SearchSidebarComponent } from './search-sidebar/search-sidebar.component'; import { SearchSidebarComponent } from './search-sidebar/search-sidebar.component';
import { SearchSidebarService } from './search-sidebar/search-sidebar.service'; import { SidebarService } from '../shared/sidebar/sidebar.service';
import { SearchSidebarEffects } from './search-sidebar/search-sidebar.effects'; import { SidebarEffects } from '../shared/sidebar/sidebar-effects.service';
import { SearchSettingsComponent } from './search-settings/search-settings.component'; import { SearchSettingsComponent } from './search-settings/search-settings.component';
import { EffectsModule } from '@ngrx/effects'; import { EffectsModule } from '@ngrx/effects';
import { SearchFiltersComponent } from './search-filters/search-filters.component'; import { SearchFiltersComponent } from './search-filters/search-filters.component';
@@ -34,9 +33,10 @@ import { SearchLabelComponent } from './search-labels/search-label/search-label.
import { ConfigurationSearchPageComponent } from './configuration-search-page.component'; import { ConfigurationSearchPageComponent } from './configuration-search-page.component';
import { ConfigurationSearchPageGuard } from './configuration-search-page.guard'; import { ConfigurationSearchPageGuard } from './configuration-search-page.guard';
import { FilteredSearchPageComponent } from './filtered-search-page.component'; import { FilteredSearchPageComponent } from './filtered-search-page.component';
import { SidebarFilterService } from '../shared/sidebar/filter/sidebar-filter.service';
const effects = [ const effects = [
SearchSidebarEffects SidebarEffects
]; ];
const components = [ const components = [
@@ -44,9 +44,6 @@ const components = [
SearchResultsComponent, SearchResultsComponent,
SearchSidebarComponent, SearchSidebarComponent,
SearchSettingsComponent, SearchSettingsComponent,
ItemSearchResultGridElementComponent,
CollectionSearchResultGridElementComponent,
CommunitySearchResultGridElementComponent,
SearchFiltersComponent, SearchFiltersComponent,
SearchFilterComponent, SearchFilterComponent,
SearchFacetFilterComponent, SearchFacetFilterComponent,
@@ -73,20 +70,18 @@ const components = [
CommonModule, CommonModule,
SharedModule, SharedModule,
EffectsModule.forFeature(effects), EffectsModule.forFeature(effects),
CoreModule.forRoot() CoreModule.forRoot(),
], ],
declarations: components, declarations: components,
providers: [ providers: [
SearchSidebarService, SidebarService,
SidebarFilterService,
SearchFilterService, SearchFilterService,
SearchFixedFilterService, SearchFixedFilterService,
ConfigurationSearchPageGuard, ConfigurationSearchPageGuard,
SearchConfigurationService SearchConfigurationService
], ],
entryComponents: [ entryComponents: [
ItemSearchResultGridElementComponent,
CollectionSearchResultGridElementComponent,
CommunitySearchResultGridElementComponent,
SearchFacetFilterComponent, SearchFacetFilterComponent,
SearchRangeFilterComponent, SearchRangeFilterComponent,
SearchTextFilterComponent, SearchTextFilterComponent,

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