Merge remote-tracking branch 'dspace/dspace-8_x' into accessibility-settings-8_x

# Conflicts:
#	src/app/profile-page/profile-page.component.html
#	src/app/profile-page/profile-page.component.ts
#	src/app/shared/notifications/notifications-board/notifications-board.component.spec.ts
#	src/app/shared/notifications/notifications-board/notifications-board.component.ts
#	src/themes/custom/app/profile-page/profile-page.component.ts
This commit is contained in:
Andreas Awouters
2025-01-22 16:11:24 +01:00
214 changed files with 16459 additions and 6592 deletions

View File

@@ -8,6 +8,7 @@ on: [push, pull_request]
permissions:
contents: read # to fetch code (actions/checkout)
packages: read # to fetch private images from GitHub Container Registry (GHCR)
jobs:
tests:
@@ -35,6 +36,9 @@ jobs:
NODE_OPTIONS: '--max-old-space-size=4096'
# Project name to use when running "docker compose" prior to e2e tests
COMPOSE_PROJECT_NAME: 'ci'
# Docker Registry to use for Docker compose scripts below.
# We use GitHub's Container Registry to avoid aggressive rate limits at DockerHub.
DOCKER_REGISTRY: ghcr.io
strategy:
# Create a matrix of Node versions to test against (in parallel)
matrix:
@@ -114,6 +118,14 @@ jobs:
path: 'coverage/dspace-angular/lcov.info'
retention-days: 14
# Login to our Docker registry, so that we can access private Docker images using "docker compose" below.
- name: Login to ${{ env.DOCKER_REGISTRY }}
uses: docker/login-action@v3
with:
registry: ${{ env.DOCKER_REGISTRY }}
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
# Using "docker compose" start backend using CI configuration
# and load assetstore from a cached copy
- name: Start DSpace REST Backend via Docker (for e2e tests)

View File

@@ -17,6 +17,7 @@ on:
permissions:
contents: read # to fetch code (actions/checkout)
packages: write # to write images to GitHub Container Registry (GHCR)
jobs:
#############################################################

View File

@@ -1,7 +1,7 @@
# This image will be published as dspace/dspace-angular
# See https://github.com/DSpace/dspace-angular/tree/main/docker for usage details
FROM node:18-alpine
FROM docker.io/node:18-alpine
# Ensure Python and other build tools are available
# These are needed to install some node modules, especially on linux/arm64
@@ -24,5 +24,5 @@ ENV NODE_OPTIONS="--max_old_space_size=4096"
# Listen / accept connections from all IP addresses.
# NOTE: At this time it is only possible to run Docker container in Production mode
# if you have a public URL. See https://github.com/DSpace/dspace-angular/issues/1485
ENV NODE_ENV development
ENV NODE_ENV=development
CMD yarn serve --host 0.0.0.0

View File

@@ -2,9 +2,9 @@
# See https://github.com/DSpace/dspace-angular/tree/main/docker for usage details
# Test build:
# docker build -f Dockerfile.dist -t dspace/dspace-angular:latest-dist .
# docker build -f Dockerfile.dist -t dspace/dspace-angular:dspace-8_x-dist .
FROM node:18-alpine AS build
FROM docker.io/node:18-alpine AS build
# Ensure Python and other build tools are available
# These are needed to install some node modules, especially on linux/arm64
@@ -26,6 +26,6 @@ COPY --chown=node:node docker/dspace-ui.json /app/dspace-ui.json
WORKDIR /app
USER node
ENV NODE_ENV production
ENV NODE_ENV=production
EXPOSE 4000
CMD pm2-runtime start dspace-ui.json --json

View File

@@ -35,7 +35,7 @@ https://wiki.lyrasis.org/display/DSDOC7x/Installing+DSpace
Quick start
-----------
**Ensure you're running [Node](https://nodejs.org) `v16.x` or `v18.x`, [npm](https://www.npmjs.com/) >= `v5.x` and [yarn](https://yarnpkg.com) == `v1.x`**
**Ensure you're running [Node](https://nodejs.org) `v18.x` or `v20.x`, [npm](https://www.npmjs.com/) >= `v10.x` and [yarn](https://yarnpkg.com) == `v1.x`**
```bash
# clone the repo
@@ -90,7 +90,7 @@ Requirements
------------
- [Node.js](https://nodejs.org) and [yarn](https://yarnpkg.com)
- Ensure you're running node `v16.x` or `v18.x` and yarn == `v1.x`
- Ensure you're running node `v18.x` or `v20.x` and yarn == `v1.x`
If you have [`nvm`](https://github.com/creationix/nvm#install-script) or [`nvm-windows`](https://github.com/coreybutler/nvm-windows) installed, which is highly recommended, you can run `nvm install --lts && nvm use` to install and start using the latest Node LTS.

View File

@@ -1,7 +1,7 @@
# NOTE: will log all redux actions and transfers in console
debug: false
# Angular Universal server settings
# Angular User Inteface settings
# NOTE: these settings define where Node.js will start your UI application. Therefore, these
# "ui" settings usually specify a localhost port/URL which is later proxied to a public URL (using Apache or similar)
ui:
@@ -17,12 +17,12 @@ ui:
# Trust X-FORWARDED-* headers from proxies (default = true)
useProxies: true
universal:
# Whether to inline "critical" styles into the server-side rendered HTML.
# Determining which styles are critical is a relatively expensive operation;
# this option can be disabled to boost server performance at the expense of
# loading smoothness.
inlineCriticalCss: true
# Angular Server Side Rendering (SSR) settings
ssr:
# Whether to tell Angular to inline "critical" styles into the server-side rendered HTML.
# Determining which styles are critical is a relatively expensive operation; this option is
# disabled (false) by default to boost server performance at the expense of loading smoothness.
inlineCriticalCss: false
# The REST API server settings
# NOTE: these settings define which (publicly available) REST API to use. They are usually

View File

@@ -9,9 +9,11 @@ describe('Admin Add New Modals', () => {
it('Add new Community modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-new-title').should('be.visible');
cy.get('#admin-menu-section-new-title').click();
cy.get('a[data-test="menu.section.new_community"]').click();
@@ -22,9 +24,11 @@ describe('Admin Add New Modals', () => {
it('Add new Collection modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-new-title').should('be.visible');
cy.get('#admin-menu-section-new-title').click();
cy.get('a[data-test="menu.section.new_collection"]').click();
@@ -35,9 +39,11 @@ describe('Admin Add New Modals', () => {
it('Add new Item modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-new-title').should('be.visible');
cy.get('#admin-menu-section-new-title').click();
cy.get('a[data-test="menu.section.new_item"]').click();

View File

@@ -9,9 +9,11 @@ describe('Admin Edit Modals', () => {
it('Edit Community modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-edit-title').should('be.visible');
cy.get('#admin-menu-section-edit-title').click();
cy.get('a[data-test="menu.section.edit_community"]').click();
@@ -22,9 +24,11 @@ describe('Admin Edit Modals', () => {
it('Edit Collection modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-edit-title').should('be.visible');
cy.get('#admin-menu-section-edit-title').click();
cy.get('a[data-test="menu.section.edit_collection"]').click();
@@ -35,9 +39,11 @@ describe('Admin Edit Modals', () => {
it('Edit Item modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-edit-title').should('be.visible');
cy.get('#admin-menu-section-edit-title').click();
cy.get('a[data-test="menu.section.edit_item"]').click();

View File

@@ -9,9 +9,11 @@ describe('Admin Export Modals', () => {
it('Export metadata modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-export-title').should('be.visible');
cy.get('#admin-menu-section-export-title').click();
cy.get('a[data-test="menu.section.export_metadata"]').click();
@@ -22,9 +24,11 @@ describe('Admin Export Modals', () => {
it('Export batch modal should pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').trigger('mouseover');
cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu
cy.get('#admin-menu-section-export-title').should('be.visible');
cy.get('#admin-menu-section-export-title').click();
cy.get('a[data-test="menu.section.export_batch"]').click();

View File

@@ -9,18 +9,15 @@ beforeEach(() => {
// This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
// We need to wait for the correction types allowed for the item to be loaded to be sure that each tab is fully loaded.
// This because the edit item page causes often tests to fails due to timeout.
cy.intercept('GET', 'server/api/config/correctiontypes/search/findByItem*').as('correctionTypes');
cy.wait('@correctionTypes');
});
describe('Edit Item > Edit Metadata tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="metadata"]').should('be.visible');
cy.get('a[data-test="metadata"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="metadata"]').should('be.visible');
cy.get('a[data-test="metadata"]').should('have.class', 'active');
// <ds-edit-item-page> tag must be loaded
@@ -39,9 +36,11 @@ describe('Edit Item > Edit Metadata tab', () => {
describe('Edit Item > Status tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="status"]').should('be.visible');
cy.get('a[data-test="status"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="status"]').should('be.visible');
cy.get('a[data-test="status"]').should('have.class', 'active');
// <ds-item-status> tag must be loaded
@@ -55,9 +54,11 @@ describe('Edit Item > Status tab', () => {
describe('Edit Item > Bitstreams tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="bitstreams"]').should('be.visible');
cy.get('a[data-test="bitstreams"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="bitstreams"]').should('be.visible');
cy.get('a[data-test="bitstreams"]').should('have.class', 'active');
// <ds-item-bitstreams> tag must be loaded
@@ -82,9 +83,11 @@ describe('Edit Item > Bitstreams tab', () => {
describe('Edit Item > Curate tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="curate"]').should('be.visible');
cy.get('a[data-test="curate"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="curate"]').should('be.visible');
cy.get('a[data-test="curate"]').should('have.class', 'active');
// <ds-item-curate> tag must be loaded
@@ -98,9 +101,11 @@ describe('Edit Item > Curate tab', () => {
describe('Edit Item > Relationships tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="relationships"]').should('be.visible');
cy.get('a[data-test="relationships"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="relationships"]').should('be.visible');
cy.get('a[data-test="relationships"]').should('have.class', 'active');
// <ds-item-relationships> tag must be loaded
@@ -114,9 +119,11 @@ describe('Edit Item > Relationships tab', () => {
describe('Edit Item > Version History tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="versionhistory"]').should('be.visible');
cy.get('a[data-test="versionhistory"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="versionhistory"]').should('be.visible');
cy.get('a[data-test="versionhistory"]').should('have.class', 'active');
// <ds-item-version-history> tag must be loaded
@@ -130,9 +137,11 @@ describe('Edit Item > Version History tab', () => {
describe('Edit Item > Access Control tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="access-control"]').should('be.visible');
cy.get('a[data-test="access-control"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="access-control"]').should('be.visible');
cy.get('a[data-test="access-control"]').should('have.class', 'active');
// <ds-item-access-control> tag must be loaded
@@ -146,9 +155,11 @@ describe('Edit Item > Access Control tab', () => {
describe('Edit Item > Collection Mapper tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="mapper"]').should('be.visible');
cy.get('a[data-test="mapper"]').click();
// Our selected tab should be active
// Our selected tab should be both visible & active
cy.get('a[data-test="mapper"]').should('be.visible');
cy.get('a[data-test="mapper"]').should('have.class', 'active');
// <ds-item-collection-mapper> tag must be loaded

View File

@@ -23,14 +23,14 @@ the Docker compose scripts in this 'docker' folder.
This Dockerfile is used to build a *development* DSpace Angular UI image, published as 'dspace/dspace-angular'
```
docker build -t dspace/dspace-angular:latest .
docker build -t dspace/dspace-angular:dspace-8_x .
```
This image is built *automatically* after each commit is made to the `main` branch.
Admins to our DockerHub repo can manually publish with the following command.
```
docker push dspace/dspace-angular:latest
docker push dspace/dspace-angular:dspace-8_x
```
### Dockerfile.dist
@@ -39,7 +39,7 @@ The `Dockerfile.dist` is used to generate a *production* build and runtime envir
```bash
# build the latest image
docker build -f Dockerfile.dist -t dspace/dspace-angular:latest-dist .
docker build -f Dockerfile.dist -t dspace/dspace-angular:dspace-8_x-dist .
```
A default/demo version of this image is built *automatically*.

View File

@@ -14,14 +14,14 @@
# Therefore, it should be kept in sync with that file
networks:
# Default to using network named 'dspacenet' from docker-compose-rest.yml.
# Its full name will be prepended with the project name (e.g. "-p d7" means it will be named "d7_dspacenet")
# Its full name will be prepended with the project name (e.g. "-p d8" means it will be named "d8_dspacenet")
# If COMPOSITE_PROJECT_NAME is missing, default value will be "docker" (name of folder this file is in)
default:
name: ${COMPOSE_PROJECT_NAME:-docker}_dspacenet
external: true
services:
dspace-cli:
image: "${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-latest}"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-dspace-8_x}"
container_name: dspace-cli
environment:
# Below syntax may look odd, but it is how to override dspace.cfg settings via env variables.

View File

@@ -14,10 +14,11 @@
# # Therefore, it should be kept in sync with that file
services:
dspacedb:
image: "${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-latest}-loadsql"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-8_x}-loadsql"
environment:
# This LOADSQL should be kept in sync with the URL in DSpace/DSpace
# This SQL is available from https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data
# NOTE: currently there is no dspace8 version
- LOADSQL=https://github.com/DSpace-Labs/AIP-Files/releases/download/demo-entities-data/dspace7-entities-data.sql
dspace:
### OVERRIDE default 'entrypoint' in 'docker-compose-rest.yml' ####

View File

@@ -33,7 +33,7 @@ services:
# This allows us to generate statistics in e2e tests so that statistics pages can be tested thoroughly.
solr__D__statistics__P__autoCommit: 'false'
LOGGING_CONFIG: /dspace/config/log4j2-container.xml
image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-latest-test}"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-8_x-test}"
depends_on:
- dspacedb
networks:
@@ -60,11 +60,12 @@ services:
# NOTE: This is customized to use our loadsql image, so that we are using a database with existing test data
dspacedb:
container_name: dspacedb
image: "${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-latest}-loadsql"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-8_x}-loadsql"
environment:
# This LOADSQL should be kept in sync with the LOADSQL in
# https://github.com/DSpace/DSpace/blob/main/dspace/src/main/docker-compose/db.entities.yml
# This SQL is available from https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data
# NOTE: currently there is no dspace8 version
LOADSQL: https://github.com/DSpace-Labs/AIP-Files/releases/download/demo-entities-data/dspace7-entities-data.sql
PGDATA: /pgdata
POSTGRES_PASSWORD: dspace
@@ -81,7 +82,7 @@ services:
# DSpace Solr container
dspacesolr:
container_name: dspacesolr
image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-latest}"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-dspace-8_x}"
networks:
- dspacenet
ports:

View File

@@ -26,7 +26,7 @@ services:
DSPACE_REST_HOST: sandbox.dspace.org
DSPACE_REST_PORT: 443
DSPACE_REST_NAMESPACE: /server
image: dspace/dspace-angular:${DSPACE_VER:-latest}-dist
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-angular:${DSPACE_VER:-dspace-8_x}-dist"
build:
context: ..
dockerfile: Dockerfile.dist

View File

@@ -40,7 +40,7 @@ services:
# from the host machine. This IP range MUST correspond to the 'dspacenet' subnet defined above.
proxies__P__trusted__P__ipranges: '172.23.0'
LOGGING_CONFIG: /dspace/config/log4j2-container.xml
image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-latest-test}"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-8_x-test}"
depends_on:
- dspacedb
networks:
@@ -68,7 +68,7 @@ services:
dspacedb:
container_name: dspacedb
# Uses a custom Postgres image with pgcrypto installed
image: "${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-latest}"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-8_x}"
environment:
PGDATA: /pgdata
POSTGRES_PASSWORD: dspace
@@ -85,7 +85,7 @@ services:
# DSpace Solr container
dspacesolr:
container_name: dspacesolr
image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-latest}"
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-dspace-8_x}"
networks:
- dspacenet
ports:

View File

@@ -23,7 +23,7 @@ services:
DSPACE_REST_HOST: localhost
DSPACE_REST_PORT: 8080
DSPACE_REST_NAMESPACE: /server
image: dspace/dspace-angular:${DSPACE_VER:-latest}
image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-angular:${DSPACE_VER:-dspace-8_x}"
build:
context: ..
dockerfile: Dockerfile

View File

@@ -78,19 +78,19 @@
"@ngx-translate/core": "^14.0.0",
"@nicky-lenaers/ngx-scroll-to": "^14.0.0",
"angulartics2": "^12.2.0",
"axios": "^1.7.4",
"axios": "^1.7.9",
"bootstrap": "^4.6.1",
"cerialize": "0.1.18",
"cli-progress": "^3.12.0",
"colors": "^1.4.0",
"compression": "^1.7.4",
"compression": "^1.7.5",
"cookie-parser": "1.4.7",
"core-js": "^3.30.1",
"core-js": "^3.39.0",
"date-fns": "^2.29.3",
"date-fns-tz": "^1.3.7",
"deepmerge": "^4.3.1",
"ejs": "^3.1.10",
"express": "^4.21.1",
"express": "^4.21.2",
"express-rate-limit": "^5.1.3",
"fast-json-patch": "^3.1.1",
"filesize": "^6.1.0",
@@ -100,13 +100,13 @@
"js-cookie": "2.2.1",
"js-yaml": "^4.1.0",
"json5": "^2.2.3",
"jsonschema": "1.4.1",
"jsonschema": "1.5.0",
"jwt-decode": "^3.1.2",
"klaro": "^0.7.18",
"lodash": "^4.17.21",
"lru-cache": "^7.14.1",
"markdown-it": "^13.0.1",
"mirador": "^3.3.0",
"mirador": "^3.4.2",
"mirador-dl-plugin": "^0.13.0",
"mirador-share-plugin": "^0.16.0",
"morgan": "^1.10.0",
@@ -135,7 +135,7 @@
"@angular/compiler-cli": "^17.3.11",
"@angular/language-service": "^17.3.11",
"@cypress/schematic": "^1.5.0",
"@fortawesome/fontawesome-free": "^6.4.0",
"@fortawesome/fontawesome-free": "^6.7.2",
"@material-ui/core": "^4.12.4",
"@material-ui/icons": "^4.11.3",
"@ngrx/store-devtools": "^17.1.1",
@@ -146,7 +146,7 @@
"@types/grecaptcha": "^3.0.9",
"@types/jasmine": "~3.6.0",
"@types/js-cookie": "2.2.6",
"@types/lodash": "^4.17.13",
"@types/lodash": "^4.17.14",
"@types/node": "^14.14.9",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
@@ -157,7 +157,7 @@
"copy-webpack-plugin": "^6.4.1",
"cross-env": "^7.0.3",
"csstype": "^3.1.3",
"cypress": "^13.15.1",
"cypress": "^13.17.0",
"cypress-axe": "^1.5.0",
"deep-freeze": "0.0.1",
"eslint": "^8.39.0",
@@ -167,12 +167,12 @@
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-import-newlines": "^1.3.1",
"eslint-plugin-jsdoc": "^45.0.0",
"eslint-plugin-jsonc": "^2.6.0",
"eslint-plugin-jsonc": "^2.18.2",
"eslint-plugin-lodash": "^7.4.0",
"eslint-plugin-rxjs": "^5.0.3",
"eslint-plugin-simple-import-sort": "^10.0.0",
"eslint-plugin-unused-imports": "^3.2.0",
"express-static-gzip": "^2.1.8",
"express-static-gzip": "^2.2.0",
"jasmine": "^3.8.0",
"jasmine-core": "^3.8.0",
"jasmine-marbles": "0.9.2",
@@ -194,12 +194,12 @@
"react-copy-to-clipboard": "^5.1.0",
"react-dom": "^16.14.0",
"rimraf": "^3.0.2",
"sass": "~1.80.4",
"sass": "~1.83.1",
"sass-loader": "^12.6.0",
"sass-resources-loader": "^2.2.5",
"ts-node": "^8.10.2",
"typescript": "~5.4.5",
"webpack": "5.95.0",
"webpack": "5.97.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}

View File

@@ -61,7 +61,7 @@
</thead>
<tbody>
<tr *ngFor="let epersonDto of (ePeopleDto$ | async)?.page"
[ngClass]="{'table-primary' : isActive(epersonDto.eperson) | async}">
[ngClass]="{'table-primary' : (activeEPerson$ | async) === epersonDto.eperson}">
<td>{{epersonDto.eperson.id}}</td>
<td>{{ dsoNameService.getName(epersonDto.eperson) }}</td>
<td>{{epersonDto.eperson.email}}</td>

View File

@@ -100,6 +100,8 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
*/
ePeopleDto$: BehaviorSubject<PaginatedList<EpersonDtoModel>> = new BehaviorSubject<PaginatedList<EpersonDtoModel>>({} as any);
activeEPerson$: Observable<EPerson>;
/**
* An observable for the pageInfo, needed to pass to the pagination component
*/
@@ -165,6 +167,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
initialisePage() {
this.searching$.next(true);
this.search({ scope: this.currentSearchScope, query: this.currentSearchQuery });
this.activeEPerson$ = this.epersonService.getActiveEPerson();
this.subs.push(this.ePeople$.pipe(
switchMap((epeople: PaginatedList<EPerson>) => {
if (epeople.pageInfo.totalElements > 0) {
@@ -232,23 +235,6 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
);
}
/**
* Checks whether the given EPerson is active (being edited)
* @param eperson
*/
isActive(eperson: EPerson): Observable<boolean> {
return this.getActiveEPerson().pipe(
map((activeEPerson) => eperson === activeEPerson),
);
}
/**
* Gets the active eperson (being edited)
*/
getActiveEPerson(): Observable<EPerson> {
return this.epersonService.getActiveEPerson();
}
/**
* Deletes EPerson, show notification on success/failure & updates EPeople list
*/

View File

@@ -2,7 +2,7 @@
<div class="group-form row">
<div class="col-12">
<div *ngIf="epersonService.getActiveEPerson() | async; then editHeader; else createHeader"></div>
<div *ngIf="activeEPerson$ | async; then editHeader; else createHeader"></div>
<ng-template #createHeader>
<h1 class="border-bottom pb-2">{{messagePrefix + '.create' | translate}}</h1>
@@ -44,7 +44,7 @@
<ds-loading [showMessage]="false" *ngIf="!formGroup"></ds-loading>
<div *ngIf="epersonService.getActiveEPerson() | async">
<div *ngIf="activeEPerson$ | async">
<h2>{{messagePrefix + '.groupsEPersonIsMemberOf' | translate}}</h2>
<ds-loading [showMessage]="false" *ngIf="groups$ | async | dsHasNoValue"></ds-loading>
@@ -75,7 +75,9 @@
{{ dsoNameService.getName(group) }}
</a>
</td>
<td class="align-middle">{{ dsoNameService.getName(undefined) }}</td>
<td class="align-middle">
{{ dsoNameService.getName((group.object | async)?.payload) }}
</td>
</tr>
</tbody>
</table>

View File

@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
TestBed,
@@ -19,12 +19,10 @@ import {
import {
ActivatedRoute,
Router,
RouterModule,
} from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import {
TranslateLoader,
TranslateModule,
} from '@ngx-translate/core';
import { TranslateModule } from '@ngx-translate/core';
import {
Observable,
of as observableOf,
@@ -49,7 +47,6 @@ import { FormBuilderService } from '../../../shared/form/builder/form-builder.se
import { FormComponent } from '../../../shared/form/form.component';
import { ThemedLoadingComponent } from '../../../shared/loading/themed-loading.component';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
@@ -92,9 +89,6 @@ describe('EPersonFormComponent', () => {
ePersonDataServiceStub = {
activeEPerson: null,
allEpeople: mockEPeople,
getEPeople(): Observable<RemoteData<PaginatedList<EPerson>>> {
return createSuccessfulRemoteDataObject$(buildPaginatedList(null, this.allEpeople));
},
getActiveEPerson(): Observable<EPerson> {
return observableOf(this.activeEPerson);
},
@@ -228,12 +222,8 @@ describe('EPersonFormComponent', () => {
router = new RouterStub();
TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock,
},
}),
RouterModule.forRoot([]),
TranslateModule.forRoot(),
EPersonFormComponent,
HasNoValuePipe,
],
@@ -251,7 +241,7 @@ describe('EPersonFormComponent', () => {
{ provide: Router, useValue: router },
EPeopleRegistryComponent,
],
schemas: [NO_ERRORS_SCHEMA],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.overrideComponent(EPersonFormComponent, {
remove: { imports: [ ThemedLoadingComponent, PaginationComponent,FormComponent] },
@@ -274,37 +264,13 @@ describe('EPersonFormComponent', () => {
});
describe('check form validation', () => {
let firstName;
let lastName;
let email;
let canLogIn;
let requireCertificate;
let canLogIn: boolean;
let requireCertificate: boolean;
let expected;
beforeEach(() => {
firstName = 'testName';
lastName = 'testLastName';
email = 'testEmail@test.com';
canLogIn = false;
requireCertificate = false;
expected = Object.assign(new EPerson(), {
metadata: {
'eperson.firstname': [
{
value: firstName,
},
],
'eperson.lastname': [
{
value: lastName,
},
],
},
email: email,
canLogIn: canLogIn,
requireCertificate: requireCertificate,
});
spyOn(component.submitForm, 'emit');
component.canLogIn.value = canLogIn;
component.requireCertificate.value = requireCertificate;
@@ -378,15 +344,13 @@ describe('EPersonFormComponent', () => {
expect(component.formGroup.controls.email.errors.emailTaken).toBeTruthy();
});
});
});
describe('when submitting the form', () => {
let firstName;
let lastName;
let email;
let canLogIn;
let canLogIn: boolean;
let requireCertificate;
let expected;
@@ -415,6 +379,7 @@ describe('EPersonFormComponent', () => {
requireCertificate: requireCertificate,
});
spyOn(component.submitForm, 'emit');
component.ngOnInit();
component.firstName.value = firstName;
component.lastName.value = lastName;
component.email.value = email;
@@ -454,9 +419,17 @@ describe('EPersonFormComponent', () => {
email: email,
canLogIn: canLogIn,
requireCertificate: requireCertificate,
_links: undefined,
_links: {
groups: {
href: '',
},
self: {
href: '',
},
},
});
spyOn(ePersonDataServiceStub, 'getActiveEPerson').and.returnValue(observableOf(expectedWithId));
component.ngOnInit();
component.onSubmit();
fixture.detectChanges();
});
@@ -504,22 +477,19 @@ describe('EPersonFormComponent', () => {
});
describe('delete', () => {
let ePersonId;
let eperson: EPerson;
let modalService;
beforeEach(() => {
spyOn(authService, 'impersonate').and.callThrough();
ePersonId = 'testEPersonId';
eperson = EPersonMock;
component.epersonInitial = eperson;
component.canDelete$ = observableOf(true);
spyOn(component.epersonService, 'getActiveEPerson').and.returnValue(observableOf(eperson));
modalService = (component as any).modalService;
spyOn(modalService, 'open').and.returnValue(Object.assign({ componentInstance: Object.assign({ response: observableOf(true) }) }));
component.ngOnInit();
fixture.detectChanges();
});
it('the delete button should be visible if the ePerson can be deleted', () => {

View File

@@ -189,6 +189,11 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
*/
canImpersonate$: Observable<boolean>;
/**
* The current {@link EPerson}
*/
activeEPerson$: Observable<EPerson>;
/**
* List of subscriptions
*/
@@ -254,7 +259,11 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
protected route: ActivatedRoute,
protected router: Router,
) {
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
}
ngOnInit() {
this.activeEPerson$ = this.epersonService.getActiveEPerson();
this.subs.push(this.activeEPerson$.subscribe((eperson: EPerson) => {
this.epersonInitial = eperson;
if (hasValue(eperson)) {
this.isImpersonated = this.authService.isImpersonatingUser(eperson.id);
@@ -262,9 +271,6 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
this.submitLabel = 'form.submit';
}
}));
}
ngOnInit() {
this.initialisePage();
}
@@ -272,20 +278,14 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* This method will initialise the page
*/
initialisePage() {
if (this.route.snapshot.params.id) {
this.subs.push(this.epersonService.findById(this.route.snapshot.params.id).subscribe((ePersonRD: RemoteData<EPerson>) => {
this.epersonService.editEPerson(ePersonRD.payload);
}));
observableCombineLatest([
this.translateService.get(`${this.messagePrefix}.firstName`),
this.translateService.get(`${this.messagePrefix}.lastName`),
this.translateService.get(`${this.messagePrefix}.email`),
this.translateService.get(`${this.messagePrefix}.canLogIn`),
this.translateService.get(`${this.messagePrefix}.requireCertificate`),
this.translateService.get(`${this.messagePrefix}.emailHint`),
]).subscribe(([firstName, lastName, email, canLogIn, requireCertificate, emailHint]) => {
}
this.firstName = new DynamicInputModel({
id: 'firstName',
label: firstName,
label: this.translateService.instant(`${this.messagePrefix}.firstName`),
name: 'firstName',
validators: {
required: null,
@@ -294,7 +294,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
});
this.lastName = new DynamicInputModel({
id: 'lastName',
label: lastName,
label: this.translateService.instant(`${this.messagePrefix}.lastName`),
name: 'lastName',
validators: {
required: null,
@@ -303,7 +303,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
});
this.email = new DynamicInputModel({
id: 'email',
label: email,
label: this.translateService.instant(`${this.messagePrefix}.email`),
name: 'email',
validators: {
required: null,
@@ -314,19 +314,19 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
emailTaken: 'error.validation.emailTaken',
pattern: 'error.validation.NotValidEmail',
},
hint: emailHint,
hint: this.translateService.instant(`${this.messagePrefix}.emailHint`),
});
this.canLogIn = new DynamicCheckboxModel(
{
id: 'canLogIn',
label: canLogIn,
label: this.translateService.instant(`${this.messagePrefix}.canLogIn`),
name: 'canLogIn',
value: (this.epersonInitial != null ? this.epersonInitial.canLogIn : true),
});
this.requireCertificate = new DynamicCheckboxModel(
{
id: 'requireCertificate',
label: requireCertificate,
label: this.translateService.instant(`${this.messagePrefix}.requireCertificate`),
name: 'requireCertificate',
value: (this.epersonInitial != null ? this.epersonInitial.requireCertificate : false),
});
@@ -338,12 +338,12 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
this.requireCertificate,
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
this.subs.push(this.activeEPerson$.subscribe((eperson: EPerson) => {
if (eperson != null) {
this.groups$ = this.groupsDataService.findListByHref(eperson._links.groups.href, {
currentPage: 1,
elementsPerPage: this.config.pageSize,
});
}, undefined, undefined, followLink('object'));
}
this.formGroup.patchValue({
firstName: eperson != null ? eperson.firstMetadataValue('eperson.firstname') : '',
@@ -361,9 +361,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
}
}));
const activeEPerson$ = this.epersonService.getActiveEPerson();
this.groups$ = activeEPerson$.pipe(
this.groups$ = this.activeEPerson$.pipe(
switchMap((eperson) => {
return observableCombineLatest([observableOf(eperson), this.paginationService.getFindListOptions(this.config.id, {
currentPage: 1,
@@ -382,7 +380,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
map(groupsRD => groupsRD.payload.pageInfo),
);
this.canImpersonate$ = activeEPerson$.pipe(
this.canImpersonate$ = this.activeEPerson$.pipe(
switchMap((eperson) => {
if (hasValue(eperson)) {
return this.authorizationService.isAuthorized(FeatureID.LoginOnBehalfOf, eperson.self);
@@ -391,11 +389,10 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
}
}),
);
this.canDelete$ = activeEPerson$.pipe(
this.canDelete$ = this.activeEPerson$.pipe(
switchMap((eperson) => this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined)),
);
this.canReset$ = observableOf(true);
});
}
/**
@@ -414,7 +411,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* Emit the updated/created eperson using the EventEmitter submitForm
*/
onSubmit() {
this.epersonService.getActiveEPerson().pipe(take(1)).subscribe(
this.activeEPerson$.pipe(take(1)).subscribe(
(ePerson: EPerson) => {
const values = {
metadata: {
@@ -533,7 +530,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* It'll either show a success or error message depending on whether the delete was successful or not.
*/
delete(): void {
this.epersonService.getActiveEPerson().pipe(
this.activeEPerson$.pipe(
take(1),
switchMap((eperson: EPerson) => {
const modalRef = this.modalService.open(ConfirmationModalComponent);
@@ -637,7 +634,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* Update the list of groups by fetching it from the rest api or cache
*/
private updateGroups(options) {
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
this.subs.push(this.activeEPerson$.subscribe((eperson: EPerson) => {
this.groups$ = this.groupsDataService.findListByHref(eperson._links.groups.href, options);
}));
}

View File

@@ -2,7 +2,7 @@
<div class="group-form row">
<div class="col-12">
<div *ngIf="groupDataService.getActiveGroup() | async; then editHeader; else createHeader"></div>
<div *ngIf="activeGroup$ | async; then editHeader; else createHeader"></div>
<ng-template #createHeader>
<h1 class="border-bottom pb-2">{{messagePrefix + '.head.create' | translate}}</h1>
@@ -23,11 +23,15 @@
</h1>
</ng-template>
<ds-alert *ngIf="groupBeingEdited?.permanent" [type]="AlertTypeEnum.Warning"
<ng-container *ngIf="(activeGroup$ | async) as groupBeingEdited">
<ds-alert *ngIf="groupBeingEdited?.permanent" [type]="AlertType.Warning"
[content]="messagePrefix + '.alert.permanent'"></ds-alert>
<ds-alert *ngIf="(canEdit$ | async) !== true && (groupDataService.getActiveGroup() | async)" [type]="AlertTypeEnum.Warning"
[content]="(messagePrefix + '.alert.workflowGroup' | translate:{ name: dsoNameService.getName((getLinkedDSO(groupBeingEdited) | async)?.payload), comcol: (getLinkedDSO(groupBeingEdited) | async)?.payload?.type, comcolEditRolesRoute: (getLinkedEditRolesRoute(groupBeingEdited) | async) })">
<ng-container *ngIf="(activeGroupLinkedDSO$ | async) as activeGroupLinkedDSO">
<ds-alert *ngIf="(canEdit$ | async) !== true" [type]="AlertType.Warning"
[content]="(messagePrefix + '.alert.workflowGroup' | translate:{ name: dsoNameService.getName(activeGroupLinkedDSO), comcol: activeGroupLinkedDSO.type, comcolEditRolesRoute: (linkedEditRolesRoute$ | async) })">
</ds-alert>
</ng-container>
</ng-container>
<ds-form [formId]="formId"
[formModel]="formModel"
@@ -39,22 +43,21 @@
<button (click)="onCancel()" type="button"
class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> {{messagePrefix + '.return' | translate}}</button>
</div>
<div after *ngIf="(canEdit$ | async) && !groupBeingEdited?.permanent" class="btn-group">
<div after *ngIf="(canEdit$ | async) && !(activeGroup$ | async)?.permanent" class="btn-group">
<button (click)="delete()" class="btn btn-danger delete-button" type="button">
<i class="fa fa-trash"></i> {{ messagePrefix + '.actions.delete' | translate}}
</button>
</div>
</ds-form>
<ng-container *ngIf="(activeGroup$ | async) as groupBeingEdited">
<div class="mb-5">
<ds-members-list *ngIf="groupBeingEdited !== undefined"
[messagePrefix]="messagePrefix + '.members-list'"></ds-members-list>
</div>
<ds-subgroups-list *ngIf="groupBeingEdited !== undefined"
[messagePrefix]="messagePrefix + '.subgroups-list'"></ds-subgroups-list>
</ng-container>
</div>
</div>
</div>

View File

@@ -1,6 +1,6 @@
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
TestBed,
@@ -23,11 +23,7 @@ import {
} from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Store } from '@ngrx/store';
import {
TranslateLoader,
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { TranslateModule } from '@ngx-translate/core';
import { Operation } from 'fast-json-patch';
import {
Observable,
@@ -61,15 +57,14 @@ import { FormComponent } from '../../../shared/form/form.component';
import { DSONameServiceMock } from '../../../shared/mocks/dso-name.service.mock';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { RouterMock } from '../../../shared/mocks/router.mock';
import { getMockTranslateService } from '../../../shared/mocks/translate.service.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
import {
GroupMock,
GroupMock2,
} from '../../../shared/testing/group-mock';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { TranslateLoaderMock } from '../../../shared/testing/translate-loader.mock';
import { GroupFormComponent } from './group-form.component';
import { MembersListComponent } from './members-list/members-list.component';
import { SubgroupsListComponent } from './subgroup-list/subgroups-list.component';
@@ -78,19 +73,19 @@ import { ValidateGroupExists } from './validators/group-exists.validator';
describe('GroupFormComponent', () => {
let component: GroupFormComponent;
let fixture: ComponentFixture<GroupFormComponent>;
let translateService: TranslateService;
let builderService: FormBuilderService;
let ePersonDataServiceStub: any;
let groupsDataServiceStub: any;
let dsoDataServiceStub: any;
let authorizationService: AuthorizationDataService;
let notificationService: NotificationsServiceStub;
let router;
let router: RouterMock;
let route: ActivatedRouteStub;
let groups;
let groupName;
let groupDescription;
let expected;
let groups: Group[];
let groupName: string;
let groupDescription: string;
let expected: Group;
beforeEach(waitForAsync(() => {
groups = [GroupMock, GroupMock2];
@@ -105,6 +100,15 @@ describe('GroupFormComponent', () => {
},
],
},
object: createSuccessfulRemoteDataObject$(undefined),
_links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
},
},
});
ePersonDataServiceStub = {};
groupsDataServiceStub = {
@@ -141,7 +145,14 @@ describe('GroupFormComponent', () => {
create(group: Group): Observable<RemoteData<Group>> {
this.allGroups = [...this.allGroups, group];
this.createdGroup = Object.assign({}, group, {
_links: { self: { href: 'group-selflink' } },
_links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
},
},
});
return createSuccessfulRemoteDataObject$(this.createdGroup);
},
@@ -223,17 +234,15 @@ describe('GroupFormComponent', () => {
return typeof value === 'object' && value !== null;
},
});
translateService = getMockTranslateService();
router = new RouterMock();
route = new ActivatedRouteStub();
notificationService = new NotificationsServiceStub();
return TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock,
},
}), GroupFormComponent],
TranslateModule.forRoot(),
GroupFormComponent,
],
providers: [
{ provide: DSONameService, useValue: new DSONameServiceMock() },
{ provide: EPersonDataService, useValue: ePersonDataServiceStub },
@@ -249,14 +258,11 @@ describe('GroupFormComponent', () => {
{ provide: Store, useValue: {} },
{ provide: RemoteDataBuildService, useValue: {} },
{ provide: HALEndpointService, useValue: {} },
{
provide: ActivatedRoute,
useValue: { data: observableOf({ dso: { payload: {} } }), params: observableOf({}) },
},
{ provide: ActivatedRoute, useValue: route },
{ provide: Router, useValue: router },
{ provide: AuthorizationDataService, useValue: authorizationService },
],
schemas: [NO_ERRORS_SCHEMA],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.overrideComponent(GroupFormComponent, {
remove: { imports: [
@@ -279,8 +285,8 @@ describe('GroupFormComponent', () => {
describe('when submitting the form', () => {
beforeEach(() => {
spyOn(component.submitForm, 'emit');
component.groupName.value = groupName;
component.groupDescription.value = groupDescription;
component.groupName.setValue(groupName);
component.groupDescription.setValue(groupDescription);
});
describe('without active Group', () => {
beforeEach(() => {
@@ -288,14 +294,22 @@ describe('GroupFormComponent', () => {
fixture.detectChanges();
});
it('should emit a new group using the correct values', (async () => {
await fixture.whenStable().then(() => {
expect(component.submitForm.emit).toHaveBeenCalledWith(expected);
});
it('should emit a new group using the correct values', (() => {
expect(component.submitForm.emit).toHaveBeenCalledWith(jasmine.objectContaining({
name: groupName,
metadata: {
'dc.description': [
{
value: groupDescription,
},
],
},
}));
}));
});
describe('with active Group', () => {
let expected2;
let expected2: Group;
beforeEach(() => {
expected2 = Object.assign(new Group(), {
name: 'newGroupName',
@@ -306,15 +320,24 @@ describe('GroupFormComponent', () => {
},
],
},
object: createSuccessfulRemoteDataObject$(undefined),
_links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
},
},
});
spyOn(groupsDataServiceStub, 'getActiveGroup').and.returnValue(observableOf(expected));
spyOn(groupsDataServiceStub, 'patch').and.returnValue(createSuccessfulRemoteDataObject$(expected2));
component.groupName.value = 'newGroupName';
component.onSubmit();
fixture.detectChanges();
component.ngOnInit();
});
it('should edit with name and description operations', () => {
component.groupName.setValue('newGroupName');
component.onSubmit();
const operations = [{
op: 'add',
path: '/metadata/dc.description',
@@ -328,9 +351,8 @@ describe('GroupFormComponent', () => {
});
it('should edit with description operations', () => {
component.groupName.value = null;
component.groupName.setValue(null);
component.onSubmit();
fixture.detectChanges();
const operations = [{
op: 'add',
path: '/metadata/dc.description',
@@ -340,9 +362,9 @@ describe('GroupFormComponent', () => {
});
it('should edit with name operations', () => {
component.groupDescription.value = null;
component.groupName.setValue('newGroupName');
component.groupDescription.setValue(null);
component.onSubmit();
fixture.detectChanges();
const operations = [{
op: 'replace',
path: '/name',
@@ -351,12 +373,13 @@ describe('GroupFormComponent', () => {
expect(groupsDataServiceStub.patch).toHaveBeenCalledWith(expected, operations);
});
it('should emit the existing group using the correct new values', (async () => {
await fixture.whenStable().then(() => {
it('should emit the existing group using the correct new values', () => {
component.onSubmit();
expect(component.submitForm.emit).toHaveBeenCalledWith(expected2);
});
}));
it('should emit success notification', () => {
component.onSubmit();
expect(notificationService.success).toHaveBeenCalled();
});
});
@@ -371,11 +394,8 @@ describe('GroupFormComponent', () => {
describe('check form validation', () => {
let groupCommunity;
beforeEach(() => {
groupName = 'testName';
groupCommunity = 'testgroupCommunity';
groupDescription = 'testgroupDescription';
expected = Object.assign(new Group(), {
@@ -387,8 +407,17 @@ describe('GroupFormComponent', () => {
},
],
},
_links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
},
},
});
spyOn(component.submitForm, 'emit');
spyOn(dsoDataServiceStub, 'findByHref').and.returnValue(observableOf(expected));
fixture.detectChanges();
component.initialisePage();
@@ -438,21 +467,20 @@ describe('GroupFormComponent', () => {
});
describe('delete', () => {
let deleteButton;
let deleteButton: HTMLButtonElement;
beforeEach(() => {
component.initialisePage();
component.canEdit$ = observableOf(true);
component.groupBeingEdited = {
beforeEach(async () => {
spyOn(groupsDataServiceStub, 'delete').and.callThrough();
component.activeGroup$ = observableOf({
id: 'active-group',
permanent: false,
} as Group;
} as Group);
component.canEdit$ = observableOf(true);
component.initialisePage();
fixture.detectChanges();
deleteButton = fixture.debugElement.query(By.css('.delete-button')).nativeElement;
spyOn(groupsDataServiceStub, 'delete').and.callThrough();
spyOn(groupsDataServiceStub, 'getActiveGroup').and.returnValue(observableOf({ id: 'active-group' }));
});
describe('if confirmed via modal', () => {

View File

@@ -11,7 +11,10 @@ import {
OnInit,
Output,
} from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import {
AbstractControl,
UntypedFormGroup,
} from '@angular/forms';
import {
ActivatedRoute,
Router,
@@ -31,13 +34,10 @@ import { Operation } from 'fast-json-patch';
import {
combineLatest as observableCombineLatest,
Observable,
of as observableOf,
Subscription,
} from 'rxjs';
import {
catchError,
debounceTime,
filter,
map,
switchMap,
take,
@@ -53,7 +53,6 @@ import { FeatureID } from '../../../core/data/feature-authorization/feature-id';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { EPersonDataService } from '../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../core/eperson/group-data.service';
import { Group } from '../../../core/eperson/models/group.model';
import { Collection } from '../../../core/shared/collection.model';
@@ -61,9 +60,9 @@ import { Community } from '../../../core/shared/community.model';
import { DSpaceObject } from '../../../core/shared/dspace-object.model';
import { NoContent } from '../../../core/shared/NoContent.model';
import {
getAllCompletedRemoteData,
getFirstCompletedRemoteData,
getFirstSucceededRemoteData,
getFirstSucceededRemoteDataPayload,
getRemoteDataPayload,
} from '../../../core/shared/operators';
import { AlertComponent } from '../../../shared/alert/alert.component';
@@ -117,9 +116,9 @@ export class GroupFormComponent implements OnInit, OnDestroy {
/**
* Dynamic models for the inputs of form
*/
groupName: DynamicInputModel;
groupCommunity: DynamicInputModel;
groupDescription: DynamicTextAreaModel;
groupName: AbstractControl;
groupCommunity: AbstractControl;
groupDescription: AbstractControl;
/**
* A list of all dynamic input models
@@ -162,21 +161,30 @@ export class GroupFormComponent implements OnInit, OnDestroy {
*/
subs: Subscription[] = [];
/**
* Group currently being edited
*/
groupBeingEdited: Group;
/**
* Observable whether or not the logged in user is allowed to delete the Group & doesn't have a linked object (community / collection linked to workspace group
*/
canEdit$: Observable<boolean>;
/**
* The AlertType enumeration
* @type {AlertType}
* The current {@link Group}
*/
public AlertTypeEnum = AlertType;
activeGroup$: Observable<Group>;
/**
* The current {@link Group}'s linked {@link Community}/{@link Collection}
*/
activeGroupLinkedDSO$: Observable<DSpaceObject>;
/**
* Link to the current {@link Group}'s {@link Community}/{@link Collection} edit role tab
*/
linkedEditRolesRoute$: Observable<string>;
/**
* The AlertType enumeration
*/
public readonly AlertType = AlertType;
/**
* Subscription to email field value change
@@ -186,78 +194,76 @@ export class GroupFormComponent implements OnInit, OnDestroy {
constructor(
public groupDataService: GroupDataService,
private ePersonDataService: EPersonDataService,
private dSpaceObjectDataService: DSpaceObjectDataService,
private formBuilderService: FormBuilderService,
private translateService: TranslateService,
private notificationsService: NotificationsService,
private route: ActivatedRoute,
protected dSpaceObjectDataService: DSpaceObjectDataService,
protected formBuilderService: FormBuilderService,
protected translateService: TranslateService,
protected notificationsService: NotificationsService,
protected route: ActivatedRoute,
protected router: Router,
private authorizationService: AuthorizationDataService,
private modalService: NgbModal,
protected authorizationService: AuthorizationDataService,
protected modalService: NgbModal,
public requestService: RequestService,
protected changeDetectorRef: ChangeDetectorRef,
public dsoNameService: DSONameService,
) {
}
ngOnInit() {
ngOnInit(): void {
if (this.route.snapshot.params.groupId !== 'newGroup') {
this.setActiveGroup(this.route.snapshot.params.groupId);
}
this.activeGroup$ = this.groupDataService.getActiveGroup();
this.activeGroupLinkedDSO$ = this.getActiveGroupLinkedDSO();
this.linkedEditRolesRoute$ = this.getLinkedEditRolesRoute();
this.canEdit$ = this.activeGroupLinkedDSO$.pipe(
switchMap((dso: DSpaceObject) => {
if (hasValue(dso)) {
return [false];
} else {
return this.activeGroup$.pipe(
hasValueOperator(),
switchMap((group: Group) => this.authorizationService.isAuthorized(FeatureID.CanDelete, group.self)),
);
}
}),
);
this.initialisePage();
}
initialisePage() {
this.subs.push(this.route.params.subscribe((params) => {
if (params.groupId !== 'newGroup') {
this.setActiveGroup(params.groupId);
}
}));
this.canEdit$ = this.groupDataService.getActiveGroup().pipe(
hasValueOperator(),
switchMap((group: Group) => {
return observableCombineLatest([
this.authorizationService.isAuthorized(FeatureID.CanDelete, isNotEmpty(group) ? group.self : undefined),
this.hasLinkedDSO(group),
]).pipe(
map(([isAuthorized, hasLinkedDSO]: [boolean, boolean]) => isAuthorized && !hasLinkedDSO),
);
}),
);
observableCombineLatest([
this.translateService.get(`${this.messagePrefix}.groupName`),
this.translateService.get(`${this.messagePrefix}.groupCommunity`),
this.translateService.get(`${this.messagePrefix}.groupDescription`),
]).subscribe(([groupName, groupCommunity, groupDescription]) => {
this.groupName = new DynamicInputModel({
const groupNameModel = new DynamicInputModel({
id: 'groupName',
label: groupName,
label: this.translateService.instant(`${this.messagePrefix}.groupName`),
name: 'groupName',
validators: {
required: null,
},
required: true,
});
this.groupCommunity = new DynamicInputModel({
const groupCommunityModel = new DynamicInputModel({
id: 'groupCommunity',
label: groupCommunity,
label: this.translateService.instant(`${this.messagePrefix}.groupCommunity`),
name: 'groupCommunity',
required: false,
readOnly: true,
});
this.groupDescription = new DynamicTextAreaModel({
const groupDescriptionModel = new DynamicTextAreaModel({
id: 'groupDescription',
label: groupDescription,
label: this.translateService.instant(`${this.messagePrefix}.groupDescription`),
name: 'groupDescription',
required: false,
spellCheck: environment.form.spellCheck,
});
this.formModel = [
this.groupName,
this.groupDescription,
groupNameModel,
groupDescriptionModel,
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.groupName = this.formGroup.get('groupName');
this.groupDescription = this.formGroup.get('groupDescription');
if (this.formGroup.controls.groupName) {
this.formGroup.controls.groupName.setAsyncValidators(ValidateGroupExists.createValidator(this.groupDataService));
if (hasValue(this.groupName)) {
this.groupName.setAsyncValidators(ValidateGroupExists.createValidator(this.groupDataService));
this.groupNameValueChangeSubscribe = this.groupName.valueChanges.pipe(debounceTime(300)).subscribe(() => {
this.changeDetectorRef.detectChanges();
});
@@ -265,10 +271,9 @@ export class GroupFormComponent implements OnInit, OnDestroy {
this.subs.push(
observableCombineLatest([
this.groupDataService.getActiveGroup(),
this.activeGroup$,
this.canEdit$,
this.groupDataService.getActiveGroup()
.pipe(filter((activeGroup) => hasValue(activeGroup)),switchMap((activeGroup) => this.getLinkedDSO(activeGroup).pipe(getFirstSucceededRemoteDataPayload()))),
this.activeGroupLinkedDSO$,
]).subscribe(([activeGroup, canEdit, linkedObject]) => {
if (activeGroup != null) {
@@ -276,36 +281,34 @@ export class GroupFormComponent implements OnInit, OnDestroy {
// Disable group name exists validator
this.formGroup.controls.groupName.clearAsyncValidators();
this.groupBeingEdited = activeGroup;
if (linkedObject?.name) {
if (isNotEmpty(linkedObject?.name)) {
if (!this.formGroup.controls.groupCommunity) {
this.formBuilderService.insertFormGroupControl(1, this.formGroup, this.formModel, this.groupCommunity);
this.formBuilderService.insertFormGroupControl(1, this.formGroup, this.formModel, groupCommunityModel);
this.groupDescription = this.formGroup.get('groupCommunity');
}
this.formGroup.patchValue({
groupName: activeGroup.name,
groupCommunity: linkedObject?.name ?? '',
groupDescription: activeGroup.firstMetadataValue('dc.description'),
});
}
} else {
this.formModel = [
this.groupName,
this.groupDescription,
groupNameModel,
groupDescriptionModel,
];
this.formGroup.patchValue({
groupName: activeGroup.name,
groupDescription: activeGroup.firstMetadataValue('dc.description'),
});
}
setTimeout(() => {
if (!canEdit || activeGroup.permanent) {
this.formGroup.disable();
} else {
this.formGroup.enable();
}
}, 200);
}
}),
);
});
}
/**
@@ -324,9 +327,9 @@ export class GroupFormComponent implements OnInit, OnDestroy {
* Emit the updated/created eperson using the EventEmitter submitForm
*/
onSubmit() {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe(
(group: Group) => {
const values = {
this.activeGroup$.pipe(take(1)).subscribe((group: Group) => {
if (group === null) {
this.createNewGroup({
name: this.groupName.value,
metadata: {
'dc.description': [
@@ -335,14 +338,11 @@ export class GroupFormComponent implements OnInit, OnDestroy {
},
],
},
};
if (group === null) {
this.createNewGroup(values);
});
} else {
this.editGroup(group);
}
},
);
});
}
/**
@@ -448,7 +448,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
* @param groupSelfLink SelfLink of group to set as active
*/
setActiveGroupWithLink(groupSelfLink: string) {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => {
this.activeGroup$.pipe(take(1)).subscribe((activeGroup: Group) => {
if (activeGroup === null) {
this.groupDataService.cancelEditGroup();
this.groupDataService.findByHref(groupSelfLink, false, false, followLink('subgroups'), followLink('epersons'), followLink('object'))
@@ -467,7 +467,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
* It'll either show a success or error message depending on whether the delete was successful or not.
*/
delete() {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((group: Group) => {
this.activeGroup$.pipe(take(1)).subscribe((group: Group) => {
const modalRef = this.modalService.open(ConfirmationModalComponent);
modalRef.componentInstance.name = this.dsoNameService.getName(group);
modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-group.modal.header';
@@ -504,59 +504,45 @@ export class GroupFormComponent implements OnInit, OnDestroy {
this.groupDataService.cancelEditGroup();
this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe());
if ( hasValue(this.groupNameValueChangeSubscribe) ) {
if (hasValue(this.groupNameValueChangeSubscribe)) {
this.groupNameValueChangeSubscribe.unsubscribe();
}
}
/**
* Check if group has a linked object (community or collection linked to a workflow group)
* @param group
* Get the active {@link Group}'s linked object if it has one ({@link Community} or {@link Collection} linked to a
* workflow group)
*/
hasLinkedDSO(group: Group): Observable<boolean> {
if (hasValue(group) && hasValue(group._links.object.href)) {
return this.getLinkedDSO(group).pipe(
map((rd: RemoteData<DSpaceObject>) => {
return hasValue(rd) && hasValue(rd.payload);
}),
catchError(() => observableOf(false)),
);
}
}
/**
* Get group's linked object if it has one (community or collection linked to a workflow group)
* @param group
*/
getLinkedDSO(group: Group): Observable<RemoteData<DSpaceObject>> {
if (hasValue(group) && hasValue(group._links.object.href)) {
getActiveGroupLinkedDSO(): Observable<DSpaceObject> {
return this.activeGroup$.pipe(
hasValueOperator(),
switchMap((group: Group) => {
if (group.object === undefined) {
return this.dSpaceObjectDataService.findByHref(group._links.object.href);
}
return group.object;
}
}),
getAllCompletedRemoteData(),
getRemoteDataPayload(),
);
}
/**
* Get the route to the edit roles tab of the group's linked object (community or collection linked to a workflow group) if it has one
* @param group
* Get the route to the edit roles tab of the active {@link Group}'s linked object (community or collection linked
* to a workflow group) if it has one
*/
getLinkedEditRolesRoute(group: Group): Observable<string> {
if (hasValue(group) && hasValue(group._links.object.href)) {
return this.getLinkedDSO(group).pipe(
map((rd: RemoteData<DSpaceObject>) => {
if (hasValue(rd) && hasValue(rd.payload)) {
const dso = rd.payload;
getLinkedEditRolesRoute(): Observable<string> {
return this.activeGroupLinkedDSO$.pipe(
hasValueOperator(),
map((dso: DSpaceObject) => {
switch ((dso as any).type) {
case Community.type.value:
return getCommunityEditRolesRoute(rd.payload.id);
return getCommunityEditRolesRoute(dso.id);
case Collection.type.value:
return getCollectionEditRolesRoute(rd.payload.id);
}
return getCollectionEditRolesRoute(dso.id);
}
}),
);
}
}
}

View File

@@ -18,7 +18,9 @@ import {
ACCESSIBILITY_COOKIE,
ACCESSIBILITY_SETTINGS_METADATA_KEY,
AccessibilitySettings,
AccessibilitySettingsService, AccessibilitySettingsFormValues, FullAccessibilitySettings,
AccessibilitySettingsFormValues,
AccessibilitySettingsService,
FullAccessibilitySettings,
} from './accessibility-settings.service';

View File

@@ -9,9 +9,9 @@
<ds-pagination
*ngIf="(bitstreamFormats | async)?.payload?.totalElements > 0"
*ngIf="(bitstreamFormats$ | async)?.payload?.totalElements > 0"
[paginationOptions]="pageConfig"
[collectionSize]="(bitstreamFormats | async)?.payload?.totalElements"
[collectionSize]="(bitstreamFormats$ | async)?.payload?.totalElements"
[hideGear]="false"
[hidePagerWhenSinglePage]="true">
<div class="table-responsive">
@@ -26,12 +26,12 @@
</tr>
</thead>
<tbody>
<tr *ngFor="let bitstreamFormat of (bitstreamFormats | async)?.payload?.page">
<tr *ngFor="let bitstreamFormat of (bitstreamFormats$ | async)?.payload?.page">
<td>
<label class="mb-0">
<input type="checkbox"
[attr.aria-label]="'admin.registries.bitstream-formats.select' | translate"
[checked]="isSelected(bitstreamFormat) | async"
[checked]="(selectedBitstreamFormatIDs$ | async)?.includes(bitstreamFormat.id)"
(change)="selectBitStreamFormat(bitstreamFormat, $event)"
>
<span class="sr-only">{{'admin.registries.bitstream-formats.select' | translate}}&#125;</span>
@@ -46,13 +46,13 @@
</table>
</div>
</ds-pagination>
<div *ngIf="(bitstreamFormats | async)?.payload?.totalElements === 0" class="alert alert-info" role="alert">
<div *ngIf="(bitstreamFormats$ | async)?.payload?.totalElements === 0" class="alert alert-info" role="alert">
{{'admin.registries.bitstream-formats.no-items' | translate}}
</div>
<div>
<button *ngIf="(bitstreamFormats | async)?.payload?.page?.length > 0" class="btn btn-primary deselect" (click)="deselectAll()">{{'admin.registries.bitstream-formats.table.deselect-all' | translate}}</button>
<button *ngIf="(bitstreamFormats | async)?.payload?.page?.length > 0" type="submit" class="btn btn-danger float-right" (click)="deleteFormats()">{{'admin.registries.bitstream-formats.table.delete' | translate}}</button>
<button *ngIf="(bitstreamFormats$ | async)?.payload?.page?.length > 0" class="btn btn-primary deselect" (click)="deselectAll()">{{'admin.registries.bitstream-formats.table.deselect-all' | translate}}</button>
<button *ngIf="(bitstreamFormats$ | async)?.payload?.page?.length > 0" type="submit" class="btn btn-danger float-right" (click)="deleteFormats()">{{'admin.registries.bitstream-formats.table.delete' | translate}}</button>
</div>
</div>
</div>

View File

@@ -8,10 +8,7 @@ import { By } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { provideMockStore } from '@ngrx/store/testing';
import { TranslateModule } from '@ngx-translate/core';
import {
cold,
hot,
} from 'jasmine-marbles';
import { hot } from 'jasmine-marbles';
import { of as observableOf } from 'rxjs';
import { BitstreamFormatDataService } from '../../../core/data/bitstream-format-data.service';
@@ -191,17 +188,17 @@ describe('BitstreamFormatsComponent', () => {
beforeEach(waitForAsync(initAsync));
beforeEach(initBeforeEach);
it('should return an observable of true if the provided bistream is in the list returned by the service', () => {
const result = comp.isSelected(bitstreamFormat1);
expect(result).toBeObservable(cold('b', { b: true }));
comp.selectedBitstreamFormatIDs().subscribe((selectedBitstreamFormatIDs: string[]) => {
expect(selectedBitstreamFormatIDs).toContain(bitstreamFormat1.id);
});
});
it('should return an observable of false if the provided bistream is not in the list returned by the service', () => {
const format = new BitstreamFormat();
format.uuid = 'new';
const result = comp.isSelected(format);
expect(result).toBeObservable(cold('b', { b: false }));
comp.selectedBitstreamFormatIDs().subscribe((selectedBitstreamFormatIDs: string[]) => {
expect(selectedBitstreamFormatIDs).not.toContain(format.id);
});
});
});

View File

@@ -13,10 +13,7 @@ import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
combineLatest as observableCombineLatest,
Observable,
} from 'rxjs';
import { Observable } from 'rxjs';
import {
map,
mergeMap,
@@ -58,7 +55,12 @@ export class BitstreamFormatsComponent implements OnInit, OnDestroy {
/**
* A paginated list of bitstream formats to be shown on the page
*/
bitstreamFormats: Observable<RemoteData<PaginatedList<BitstreamFormat>>>;
bitstreamFormats$: Observable<RemoteData<PaginatedList<BitstreamFormat>>>;
/**
* The currently selected {@link BitstreamFormat} IDs
*/
selectedBitstreamFormatIDs$: Observable<string[]>;
/**
* The current pagination configuration for the page
@@ -125,14 +127,11 @@ export class BitstreamFormatsComponent implements OnInit, OnDestroy {
}
/**
* Checks whether a given bitstream format is selected in the list (checkbox)
* @param bitstreamFormat
* Returns the list of all the bitstream formats that are selected in the list (checkbox)
*/
isSelected(bitstreamFormat: BitstreamFormat): Observable<boolean> {
selectedBitstreamFormatIDs(): Observable<string[]> {
return this.bitstreamFormatService.getSelectedBitstreamFormats().pipe(
map((bitstreamFormats: BitstreamFormat[]) => {
return bitstreamFormats.find((selectedFormat) => selectedFormat.id === bitstreamFormat.id) != null;
}),
map((bitstreamFormats: BitstreamFormat[]) => bitstreamFormats.map((selectedFormat) => selectedFormat.id)),
);
}
@@ -156,27 +155,23 @@ export class BitstreamFormatsComponent implements OnInit, OnDestroy {
const prefix = 'admin.registries.bitstream-formats.delete';
const suffix = success ? 'success' : 'failure';
const messages = observableCombineLatest(
this.translateService.get(`${prefix}.${suffix}.head`),
this.translateService.get(`${prefix}.${suffix}.amount`, { amount: amount }),
);
messages.subscribe(([head, content]) => {
const head: string = this.translateService.instant(`${prefix}.${suffix}.head`);
const content: string = this.translateService.instant(`${prefix}.${suffix}.amount`, { amount: amount });
if (success) {
this.notificationsService.success(head, content);
} else {
this.notificationsService.error(head, content);
}
});
}
ngOnInit(): void {
this.bitstreamFormats = this.paginationService.getFindListOptions(this.pageConfig.id, this.pageConfig).pipe(
this.bitstreamFormats$ = this.paginationService.getFindListOptions(this.pageConfig.id, this.pageConfig).pipe(
switchMap((findListOptions: FindListOptions) => {
return this.bitstreamFormatService.findAll(findListOptions);
}),
);
this.selectedBitstreamFormatIDs$ = this.selectedBitstreamFormatIDs();
}

View File

@@ -27,14 +27,14 @@
</thead>
<tbody>
<tr *ngFor="let schema of (metadataSchemas | async)?.payload?.page"
[ngClass]="{'table-primary' : isActive(schema) | async}">
[ngClass]="{'table-primary' : (activeMetadataSchema$ | async)?.id === schema.id}">
<td>
<label class="mb-0">
<input type="checkbox"
[checked]="isSelected(schema) | async"
[checked]="(selectedMetadataSchemaIDs$ | async)?.includes(schema.id)"
(change)="selectMetadataSchema(schema, $event)"
>
<span class="sr-only">{{((isSelected(schema) | async) ? 'admin.registries.metadata.schemas.deselect' : 'admin.registries.metadata.schemas.select') | translate}}</span>
<span class="sr-only">{{(((selectedMetadataSchemaIDs$ | async)?.includes(schema.id)) ? 'admin.registries.metadata.schemas.deselect' : 'admin.registries.metadata.schemas.select') | translate}}</span>
</label>
</td>
<td class="selectable-row" (click)="editSchema(schema)"><a [routerLink]="[schema.prefix]">{{schema.id}}</a></td>

View File

@@ -17,9 +17,7 @@ import { TranslateModule } from '@ngx-translate/core';
import { of as observableOf } from 'rxjs';
import { FormBuilderService } from 'src/app/shared/form/builder/form-builder.service';
import { RestResponse } from '../../../core/cache/response.models';
import { ConfigurationDataService } from '../../../core/data/configuration-data.service';
import { buildPaginatedList } from '../../../core/data/paginated-list.model';
import { GroupDataService } from '../../../core/eperson/group-data.service';
import { MetadataSchema } from '../../../core/metadata/metadata-schema.model';
import { PaginationService } from '../../../core/pagination/pagination.service';
@@ -36,7 +34,9 @@ import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.u
import { HostWindowServiceStub } from '../../../shared/testing/host-window-service.stub';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
import { RegistryServiceStub } from '../../../shared/testing/registry.service.stub';
import { SearchConfigurationServiceStub } from '../../../shared/testing/search-configuration-service.stub';
import { createPaginatedList } from '../../../shared/testing/utils.test';
import { EnumKeysPipe } from '../../../shared/utils/enum-keys-pipe';
import { MetadataRegistryComponent } from './metadata-registry.component';
import { MetadataSchemaFormComponent } from './metadata-schema-form/metadata-schema-form.component';
@@ -44,9 +44,11 @@ import { MetadataSchemaFormComponent } from './metadata-schema-form/metadata-sch
describe('MetadataRegistryComponent', () => {
let comp: MetadataRegistryComponent;
let fixture: ComponentFixture<MetadataRegistryComponent>;
let registryService: RegistryService;
let paginationService;
const mockSchemasList = [
let paginationService: PaginationServiceStub;
let registryService: RegistryServiceStub;
const mockSchemasList: MetadataSchema[] = [
{
id: 1,
_links: {
@@ -67,25 +69,7 @@ describe('MetadataRegistryComponent', () => {
prefix: 'mock',
namespace: 'http://dspace.org/mockschema',
},
];
const mockSchemas = createSuccessfulRemoteDataObject$(buildPaginatedList(null, mockSchemasList));
/* eslint-disable no-empty,@typescript-eslint/no-empty-function */
const registryServiceStub = {
getMetadataSchemas: () => mockSchemas,
getActiveMetadataSchema: () => observableOf(undefined),
getSelectedMetadataSchemas: () => observableOf([]),
editMetadataSchema: (schema) => {
},
cancelEditMetadataSchema: () => {
},
deleteMetadataSchema: () => observableOf(new RestResponse(true, 200, 'OK')),
deselectAllMetadataSchema: () => {
},
clearMetadataSchemaRequests: () => observableOf(undefined),
};
/* eslint-enable no-empty, @typescript-eslint/no-empty-function */
paginationService = new PaginationServiceStub();
] as MetadataSchema[];
const configurationDataService = jasmine.createSpyObj('configurationDataService', {
findByPropertyName: createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), {
@@ -109,6 +93,10 @@ describe('MetadataRegistryComponent', () => {
);
beforeEach(waitForAsync(() => {
paginationService = new PaginationServiceStub();
registryService = new RegistryServiceStub();
spyOn(registryService, 'getMetadataSchemas').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(mockSchemasList)));
TestBed.configureTestingModule({
imports: [
CommonModule,
@@ -120,7 +108,7 @@ describe('MetadataRegistryComponent', () => {
EnumKeysPipe,
],
providers: [
{ provide: RegistryService, useValue: registryServiceStub },
{ provide: RegistryService, useValue: registryService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService },
{
@@ -190,7 +178,7 @@ describe('MetadataRegistryComponent', () => {
}));
it('should cancel editing the selected schema when clicked again', waitForAsync(() => {
spyOn(registryService, 'getActiveMetadataSchema').and.returnValue(observableOf(mockSchemasList[0] as MetadataSchema));
comp.activeMetadataSchema$ = observableOf(mockSchemasList[0] as MetadataSchema);
spyOn(registryService, 'cancelEditMetadataSchema');
row.click();
fixture.detectChanges();
@@ -205,7 +193,7 @@ describe('MetadataRegistryComponent', () => {
beforeEach(() => {
spyOn(registryService, 'deleteMetadataSchema').and.callThrough();
spyOn(registryService, 'getSelectedMetadataSchemas').and.returnValue(observableOf(selectedSchemas as MetadataSchema[]));
comp.selectedMetadataSchemaIDs$ = observableOf(selectedSchemas.map((selectedSchema: MetadataSchema) => selectedSchema.id));
comp.deleteSchemas();
fixture.detectChanges();
});

View File

@@ -7,19 +7,17 @@ import {
import {
Component,
OnDestroy,
OnInit,
} from '@angular/core';
import {
Router,
RouterLink,
} from '@angular/router';
import { RouterLink } from '@angular/router';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
BehaviorSubject,
combineLatest as observableCombineLatest,
Observable,
Subscription,
zip,
} from 'rxjs';
import {
@@ -36,7 +34,6 @@ import { PaginationService } from '../../../core/pagination/pagination.service';
import { RegistryService } from '../../../core/registry/registry.service';
import { NoContent } from '../../../core/shared/NoContent.model';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { hasValue } from '../../../shared/empty.util';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { toFindListOptions } from '../../../shared/pagination/pagination.utils';
@@ -63,13 +60,23 @@ import { MetadataSchemaFormComponent } from './metadata-schema-form/metadata-sch
* A component used for managing all existing metadata schemas within the repository.
* The admin can create, edit or delete metadata schemas here.
*/
export class MetadataRegistryComponent implements OnDestroy {
export class MetadataRegistryComponent implements OnDestroy, OnInit {
/**
* A list of all the current metadata schemas within the repository
*/
metadataSchemas: Observable<RemoteData<PaginatedList<MetadataSchema>>>;
/**
* The {@link MetadataSchema}that is being edited
*/
activeMetadataSchema$: Observable<MetadataSchema>;
/**
* The selected {@link MetadataSchema} IDs
*/
selectedMetadataSchemaIDs$: Observable<number[]>;
/**
* Pagination config used to display the list of metadata schemas
*/
@@ -79,15 +86,25 @@ export class MetadataRegistryComponent implements OnDestroy {
});
/**
* Whether or not the list of MetadataSchemas needs an update
* Whether the list of MetadataSchemas needs an update
*/
needsUpdate$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);
constructor(private registryService: RegistryService,
private notificationsService: NotificationsService,
private router: Router,
private paginationService: PaginationService,
private translateService: TranslateService) {
subscriptions: Subscription[] = [];
constructor(
protected registryService: RegistryService,
protected notificationsService: NotificationsService,
protected paginationService: PaginationService,
protected translateService: TranslateService,
) {
}
ngOnInit(): void {
this.activeMetadataSchema$ = this.registryService.getActiveMetadataSchema();
this.selectedMetadataSchemaIDs$ = this.registryService.getSelectedMetadataSchemas().pipe(
map((schemas: MetadataSchema[]) => schemas.map((schema: MetadataSchema) => schema.id)),
);
this.updateSchemas();
}
@@ -116,30 +133,13 @@ export class MetadataRegistryComponent implements OnDestroy {
* @param schema
*/
editSchema(schema: MetadataSchema) {
this.getActiveSchema().pipe(take(1)).subscribe((activeSchema) => {
this.subscriptions.push(this.activeMetadataSchema$.pipe(take(1)).subscribe((activeSchema: MetadataSchema) => {
if (schema === activeSchema) {
this.registryService.cancelEditMetadataSchema();
} else {
this.registryService.editMetadataSchema(schema);
}
});
}
/**
* Checks whether the given metadata schema is active (being edited)
* @param schema
*/
isActive(schema: MetadataSchema): Observable<boolean> {
return this.getActiveSchema().pipe(
map((activeSchema) => schema === activeSchema),
);
}
/**
* Gets the active metadata schema (being edited)
*/
getActiveSchema(): Observable<MetadataSchema> {
return this.registryService.getActiveMetadataSchema();
}));
}
/**
@@ -153,31 +153,16 @@ export class MetadataRegistryComponent implements OnDestroy {
this.registryService.deselectMetadataSchema(schema);
}
/**
* Checks whether a given metadata schema is selected in the list (checkbox)
* @param schema
*/
isSelected(schema: MetadataSchema): Observable<boolean> {
return this.registryService.getSelectedMetadataSchemas().pipe(
map((schemas) => schemas.find((selectedSchema) => selectedSchema === schema) != null),
);
}
/**
* Delete all the selected metadata schemas
*/
deleteSchemas() {
this.registryService.getSelectedMetadataSchemas().pipe(take(1)).subscribe(
(schemas) => {
const tasks$ = [];
for (const schema of schemas) {
if (hasValue(schema.id)) {
tasks$.push(this.registryService.deleteMetadataSchema(schema.id).pipe(getFirstCompletedRemoteData()));
}
}
zip(...tasks$).subscribe((responses: RemoteData<NoContent>[]) => {
const successResponses = responses.filter((response: RemoteData<NoContent>) => response.hasSucceeded);
const failedResponses = responses.filter((response: RemoteData<NoContent>) => response.hasFailed);
this.subscriptions.push(this.selectedMetadataSchemaIDs$.pipe(
take(1),
switchMap((schemaIDs: number[]) => zip(schemaIDs.map((schemaID: number) => this.registryService.deleteMetadataSchema(schemaID).pipe(getFirstCompletedRemoteData())))),
).subscribe((responses: RemoteData<NoContent>[]) => {
const successResponses: RemoteData<NoContent>[] = responses.filter((response: RemoteData<NoContent>) => response.hasSucceeded);
const failedResponses: RemoteData<NoContent>[] = responses.filter((response: RemoteData<NoContent>) => response.hasFailed);
if (successResponses.length > 0) {
this.showNotification(true, successResponses.length);
}
@@ -186,9 +171,7 @@ export class MetadataRegistryComponent implements OnDestroy {
}
this.registryService.deselectAllMetadataSchema();
this.registryService.cancelEditMetadataSchema();
});
},
);
}));
}
/**
@@ -199,20 +182,20 @@ export class MetadataRegistryComponent implements OnDestroy {
showNotification(success: boolean, amount: number) {
const prefix = 'admin.registries.schema.notification';
const suffix = success ? 'success' : 'failure';
const messages = observableCombineLatest(
this.translateService.get(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`),
this.translateService.get(`${prefix}.deleted.${suffix}`, { amount: amount }),
);
messages.subscribe(([head, content]) => {
const head: string = this.translateService.instant(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`);
const content: string = this.translateService.instant(`${prefix}.deleted.${suffix}`, { amount: amount });
if (success) {
this.notificationsService.success(head, content);
} else {
this.notificationsService.error(head, content);
}
});
}
ngOnDestroy(): void {
this.paginationService.clearPagination(this.config.id);
this.subscriptions.map((subscription: Subscription) => subscription.unsubscribe());
}
}

View File

@@ -1,4 +1,4 @@
<div *ngIf="registryService.getActiveMetadataSchema() | async; then editheader; else createHeader"></div>
<div *ngIf="activeMetadataSchema$ | async; then editheader; else createHeader"></div>
<ng-template #createHeader>
<h2>{{messagePrefix + '.create' | translate}}</h2>

View File

@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
inject,
@@ -16,42 +16,26 @@ import { RegistryService } from '../../../../core/registry/registry.service';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { FormComponent } from '../../../../shared/form/form.component';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
import { RegistryServiceStub } from '../../../../shared/testing/registry.service.stub';
import { EnumKeysPipe } from '../../../../shared/utils/enum-keys-pipe';
import { MetadataSchemaFormComponent } from './metadata-schema-form.component';
describe('MetadataSchemaFormComponent', () => {
let component: MetadataSchemaFormComponent;
let fixture: ComponentFixture<MetadataSchemaFormComponent>;
let registryService: RegistryService;
/* eslint-disable no-empty,@typescript-eslint/no-empty-function */
const registryServiceStub = {
getActiveMetadataSchema: () => observableOf(undefined),
createOrUpdateMetadataSchema: (schema: MetadataSchema) => observableOf(schema),
cancelEditMetadataSchema: () => {
},
clearMetadataSchemaRequests: () => observableOf(undefined),
};
const formBuilderServiceStub = {
createFormGroup: () => {
return {
patchValue: () => {
},
reset(_value?: any, _options?: { onlySelf?: boolean; emitEvent?: boolean; }): void {
},
};
},
};
/* eslint-enable no-empty, @typescript-eslint/no-empty-function */
let registryService: RegistryServiceStub;
beforeEach(waitForAsync(() => {
registryService = new RegistryServiceStub();
return TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule, MetadataSchemaFormComponent, EnumKeysPipe],
providers: [
{ provide: RegistryService, useValue: registryServiceStub },
{ provide: RegistryService, useValue: registryService },
{ provide: FormBuilderService, useValue: getMockFormBuilderService() },
],
schemas: [NO_ERRORS_SCHEMA],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.overrideComponent(MetadataSchemaFormComponent, {
remove: {
@@ -88,7 +72,7 @@ describe('MetadataSchemaFormComponent', () => {
describe('without an active schema', () => {
beforeEach(() => {
spyOn(registryService, 'getActiveMetadataSchema').and.returnValue(observableOf(undefined));
component.activeMetadataSchema$ = observableOf(undefined);
component.onSubmit();
fixture.detectChanges();
});
@@ -107,7 +91,7 @@ describe('MetadataSchemaFormComponent', () => {
} as MetadataSchema);
beforeEach(() => {
spyOn(registryService, 'getActiveMetadataSchema').and.returnValue(observableOf(expectedWithId));
component.activeMetadataSchema$ = observableOf(expectedWithId);
component.onSubmit();
fixture.detectChanges();
});

View File

@@ -21,13 +21,13 @@ import {
TranslateService,
} from '@ngx-translate/core';
import {
combineLatest,
Observable,
Subscription,
} from 'rxjs';
import {
map,
switchMap,
take,
tap,
} from 'rxjs/operators';
import { MetadataSchema } from '../../../../core/metadata/metadata-schema.model';
@@ -102,17 +102,24 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
*/
@Output() submitForm: EventEmitter<any> = new EventEmitter();
constructor(public registryService: RegistryService, private formBuilderService: FormBuilderService, private translateService: TranslateService) {
/**
* The {@link MetadataSchema} that is currently being edited
*/
activeMetadataSchema$: Observable<MetadataSchema>;
subscriptions: Subscription[] = [];
constructor(
protected registryService: RegistryService,
protected formBuilderService: FormBuilderService,
protected translateService: TranslateService,
) {
}
ngOnInit() {
combineLatest([
this.translateService.get(`${this.messagePrefix}.name`),
this.translateService.get(`${this.messagePrefix}.namespace`),
]).subscribe(([name, namespace]) => {
this.name = new DynamicInputModel({
id: 'name',
label: name,
label: this.translateService.instant(`${this.messagePrefix}.name`),
name: 'name',
validators: {
required: null,
@@ -127,7 +134,7 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
});
this.namespace = new DynamicInputModel({
id: 'namespace',
label: namespace,
label: this.translateService.instant(`${this.messagePrefix}.namespace`),
name: 'namespace',
validators: {
required: null,
@@ -146,7 +153,8 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
}),
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.registryService.getActiveMetadataSchema().subscribe((schema: MetadataSchema) => {
this.activeMetadataSchema$ = this.registryService.getActiveMetadataSchema();
this.subscriptions.push(this.activeMetadataSchema$.subscribe((schema: MetadataSchema) => {
if (schema == null) {
this.clearFields();
} else {
@@ -158,8 +166,7 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
});
this.name.disabled = true;
}
});
});
}));
}
/**
@@ -176,44 +183,25 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
* Emit the updated/created schema using the EventEmitter submitForm
*/
onSubmit(): void {
this.registryService
.getActiveMetadataSchema()
.pipe(
this.activeMetadataSchema$.pipe(
take(1),
switchMap((schema: MetadataSchema) => {
const metadataValues = {
prefix: this.name.value,
namespace: this.namespace.value,
};
let createOrUpdate$: Observable<MetadataSchema>;
if (schema == null) {
createOrUpdate$ =
this.registryService.createOrUpdateMetadataSchema(
Object.assign(new MetadataSchema(), metadataValues),
);
return this.registryService.createOrUpdateMetadataSchema(Object.assign(new MetadataSchema(), metadataValues));
} else {
const updatedSchema = Object.assign(
new MetadataSchema(),
schema,
{
return this.registryService.createOrUpdateMetadataSchema(Object.assign(new MetadataSchema(), schema, {
namespace: metadataValues.namespace,
},
);
createOrUpdate$ =
this.registryService.createOrUpdateMetadataSchema(
updatedSchema,
);
}));
}
return createOrUpdate$;
}),
tap(() => {
this.registryService.clearMetadataSchemaRequests().subscribe();
}),
)
.subscribe((updatedOrCreatedSchema: MetadataSchema) => {
switchMap((updatedOrCreatedSchema: MetadataSchema) => this.registryService.clearMetadataSchemaRequests().pipe(
map(() => updatedOrCreatedSchema),
)),
).subscribe((updatedOrCreatedSchema: MetadataSchema) => {
this.submitForm.emit(updatedOrCreatedSchema);
this.clearFields();
this.registryService.cancelEditMetadataSchema();
@@ -233,5 +221,6 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
*/
ngOnDestroy(): void {
this.onCancel();
this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe());
}
}

View File

@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
inject,
@@ -17,13 +17,15 @@ import { RegistryService } from '../../../../core/registry/registry.service';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { FormComponent } from '../../../../shared/form/form.component';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
import { RegistryServiceStub } from '../../../../shared/testing/registry.service.stub';
import { EnumKeysPipe } from '../../../../shared/utils/enum-keys-pipe';
import { MetadataFieldFormComponent } from './metadata-field-form.component';
describe('MetadataFieldFormComponent', () => {
let component: MetadataFieldFormComponent;
let fixture: ComponentFixture<MetadataFieldFormComponent>;
let registryService: RegistryService;
let registryService: RegistryServiceStub;
const metadataSchema = Object.assign(new MetadataSchema(), {
id: 1,
@@ -31,37 +33,16 @@ describe('MetadataFieldFormComponent', () => {
prefix: 'fake',
});
/* eslint-disable no-empty,@typescript-eslint/no-empty-function */
const registryServiceStub = {
getActiveMetadataField: () => observableOf(undefined),
createMetadataField: (field: MetadataField) => observableOf(field),
updateMetadataField: (field: MetadataField) => observableOf(field),
cancelEditMetadataField: () => {
},
cancelEditMetadataSchema: () => {
},
clearMetadataFieldRequests: () => observableOf(undefined),
};
const formBuilderServiceStub = {
createFormGroup: () => {
return {
patchValue: () => {
},
reset(_value?: any, _options?: { onlySelf?: boolean; emitEvent?: boolean; }): void {
},
};
},
};
/* eslint-enable no-empty, @typescript-eslint/no-empty-function */
beforeEach(waitForAsync(() => {
registryService = new RegistryServiceStub();
return TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule, MetadataFieldFormComponent, EnumKeysPipe],
providers: [
{ provide: RegistryService, useValue: registryServiceStub },
{ provide: RegistryService, useValue: registryService },
{ provide: FormBuilderService, useValue: getMockFormBuilderService() },
],
schemas: [NO_ERRORS_SCHEMA],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.overrideComponent(MetadataFieldFormComponent, {
remove: { imports: [FormComponent] },

View File

@@ -31,8 +31,8 @@
</thead>
<tbody>
<tr *ngFor="let field of fields?.page"
[ngClass]="{'table-primary' : isActive(field) | async}">
<td *ngVar="(isSelected(field) | async) as selected">
[ngClass]="{'table-primary' : (activeField$ | async)?.id === field.id}">
<td *ngVar="(selectedMetadataFieldIDs$ | async)?.includes(field.id) as selected">
<input type="checkbox"
[attr.aria-label]="(selected ? 'admin.registries.schema.fields.deselect' : 'admin.registries.schema.fields.select') | translate"
[checked]="selected"

View File

@@ -1,5 +1,5 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
inject,
@@ -7,16 +7,12 @@ import {
waitForAsync,
} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { of as observableOf } from 'rxjs';
import { RestResponse } from '../../../core/cache/response.models';
import { ConfigurationDataService } from '../../../core/data/configuration-data.service';
import { buildPaginatedList } from '../../../core/data/paginated-list.model';
import { GroupDataService } from '../../../core/eperson/group-data.service';
@@ -34,7 +30,7 @@ import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
import { HostWindowServiceStub } from '../../../shared/testing/host-window-service.stub';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
import { RouterStub } from '../../../shared/testing/router.stub';
import { RegistryServiceStub } from '../../../shared/testing/registry.service.stub';
import { SearchConfigurationServiceStub } from '../../../shared/testing/search-configuration-service.stub';
import { createPaginatedList } from '../../../shared/testing/utils.test';
import { EnumKeysPipe } from '../../../shared/utils/enum-keys-pipe';
@@ -45,8 +41,12 @@ import { MetadataSchemaComponent } from './metadata-schema.component';
describe('MetadataSchemaComponent', () => {
let comp: MetadataSchemaComponent;
let fixture: ComponentFixture<MetadataSchemaComponent>;
let registryService: RegistryService;
const mockSchemasList = [
let registryService: RegistryServiceStub;
let activatedRoute: ActivatedRouteStub;
let paginationService: PaginationServiceStub;
const mockSchemasList: MetadataSchema[] = [
{
id: 1,
_links: {
@@ -67,8 +67,8 @@ describe('MetadataSchemaComponent', () => {
prefix: 'mock',
namespace: 'http://dspace.org/mockschema',
},
];
const mockFieldsList = [
] as MetadataSchema[];
const mockFieldsList: MetadataField[] = [
{
id: 1,
_links: {
@@ -117,33 +117,8 @@ describe('MetadataSchemaComponent', () => {
scopeNote: null,
schema: createSuccessfulRemoteDataObject$(mockSchemasList[1]),
},
];
const mockSchemas = createSuccessfulRemoteDataObject$(buildPaginatedList(null, mockSchemasList));
/* eslint-disable no-empty,@typescript-eslint/no-empty-function */
const registryServiceStub = {
getMetadataSchemas: () => mockSchemas,
getMetadataFieldsBySchema: (schema: MetadataSchema) => createSuccessfulRemoteDataObject$(buildPaginatedList(null, mockFieldsList.filter((value) => value.id === 3 || value.id === 4))),
getMetadataSchemaByPrefix: (schemaName: string) => createSuccessfulRemoteDataObject$(mockSchemasList.filter((value) => value.prefix === schemaName)[0]),
getActiveMetadataField: () => observableOf(undefined),
getSelectedMetadataFields: () => observableOf([]),
editMetadataField: (schema) => {
},
cancelEditMetadataField: () => {
},
deleteMetadataField: () => observableOf(new RestResponse(true, 200, 'OK')),
deselectAllMetadataField: () => {
},
clearMetadataFieldRequests: () => observableOf(undefined),
};
/* eslint-enable no-empty, @typescript-eslint/no-empty-function */
] as MetadataField[];
const schemaNameParam = 'mock';
const activatedRouteStub = Object.assign(new ActivatedRouteStub(), {
params: observableOf({
schemaName: schemaNameParam,
}),
});
const paginationService = new PaginationServiceStub();
const configurationDataService = jasmine.createSpyObj('configurationDataService', {
findByPropertyName: createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), {
@@ -162,6 +137,14 @@ describe('MetadataSchemaComponent', () => {
beforeEach(waitForAsync(() => {
activatedRoute = new ActivatedRouteStub({
schemaName: schemaNameParam,
});
paginationService = new PaginationServiceStub();
registryService = new RegistryServiceStub();
spyOn(registryService, 'getMetadataFieldsBySchema').and.returnValue(createSuccessfulRemoteDataObject$(buildPaginatedList(null, mockFieldsList.filter((value) => value.id === 3 || value.id === 4))));
spyOn(registryService, 'getMetadataSchemaByPrefix').and.callFake((schemaName) => createSuccessfulRemoteDataObject$(mockSchemasList.filter((value) => value.prefix === schemaName)[0]));
TestBed.configureTestingModule({
imports: [
CommonModule,
@@ -174,10 +157,9 @@ describe('MetadataSchemaComponent', () => {
VarDirective,
],
providers: [
{ provide: RegistryService, useValue: registryServiceStub },
{ provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: RegistryService, useValue: registryService },
{ provide: ActivatedRoute, useValue: activatedRoute },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: Router, useValue: new RouterStub() },
{ provide: PaginationService, useValue: paginationService },
{
provide: NotificationsService,
@@ -187,7 +169,7 @@ describe('MetadataSchemaComponent', () => {
{ provide: ConfigurationDataService, useValue: configurationDataService },
{ provide: SearchConfigurationService, useValue: new SearchConfigurationServiceStub() },
],
schemas: [NO_ERRORS_SCHEMA],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.overrideComponent(MetadataSchemaComponent, {
remove: {
@@ -242,7 +224,7 @@ describe('MetadataSchemaComponent', () => {
}));
it('should cancel editing the selected field when clicked again', waitForAsync(() => {
spyOn(registryService, 'getActiveMetadataField').and.returnValue(observableOf(mockFieldsList[2] as MetadataField));
comp.activeField$ = observableOf(mockFieldsList[2] as MetadataField);
spyOn(registryService, 'cancelEditMetadataField');
row.click();
fixture.detectChanges();
@@ -257,7 +239,7 @@ describe('MetadataSchemaComponent', () => {
beforeEach(() => {
spyOn(registryService, 'deleteMetadataField').and.callThrough();
spyOn(registryService, 'getSelectedMetadataFields').and.returnValue(observableOf(selectedFields as MetadataField[]));
comp.selectedMetadataFieldIDs$ = observableOf(selectedFields.map((metadataField: MetadataField) => metadataField.id));
comp.deleteFields();
fixture.detectChanges();
});

View File

@@ -20,9 +20,9 @@ import {
import {
BehaviorSubject,
combineLatest,
combineLatest as observableCombineLatest,
Observable,
of as observableOf,
Subscription,
zip,
} from 'rxjs';
import {
@@ -42,7 +42,6 @@ import {
getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload,
} from '../../../core/shared/operators';
import { hasValue } from '../../../shared/empty.util';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { toFindListOptions } from '../../../shared/pagination/pagination.utils';
@@ -71,7 +70,7 @@ import { MetadataFieldFormComponent } from './metadata-field-form/metadata-field
* A component used for managing all existing metadata fields within the current metadata schema.
* The admin can create, edit or delete metadata fields here.
*/
export class MetadataSchemaComponent implements OnInit, OnDestroy {
export class MetadataSchemaComponent implements OnDestroy, OnInit {
/**
* The metadata schema
*/
@@ -96,26 +95,33 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
*/
needsUpdate$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);
constructor(private registryService: RegistryService,
private route: ActivatedRoute,
private notificationsService: NotificationsService,
private paginationService: PaginationService,
private translateService: TranslateService) {
/**
* The current {@link MetadataField} that is being edited
*/
activeField$: Observable<MetadataField>;
/**
* The selected {@link MetadataField} IDs
*/
selectedMetadataFieldIDs$: Observable<number[]>;
subscriptions: Subscription[] = [];
constructor(
protected registryService: RegistryService,
protected route: ActivatedRoute,
protected notificationsService: NotificationsService,
protected paginationService: PaginationService,
protected translateService: TranslateService,
) {
}
ngOnInit(): void {
this.route.params.subscribe((params) => {
this.initialize(params);
});
}
/**
* Initialize the component using the params within the url (schemaName)
* @param params
*/
initialize(params) {
this.metadataSchema$ = this.registryService.getMetadataSchemaByPrefix(params.schemaName).pipe(getFirstSucceededRemoteDataPayload());
this.metadataSchema$ = this.registryService.getMetadataSchemaByPrefix(this.route.snapshot.params.schemaName).pipe(getFirstSucceededRemoteDataPayload());
this.activeField$ = this.registryService.getActiveMetadataField();
this.selectedMetadataFieldIDs$ = this.registryService.getSelectedMetadataFields().pipe(
map((metadataFields: MetadataField[]) => metadataFields.map((metadataField: MetadataField) => metadataField.id)),
);
this.updateFields();
}
@@ -148,30 +154,13 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
* @param field
*/
editField(field: MetadataField) {
this.getActiveField().pipe(take(1)).subscribe((activeField) => {
this.subscriptions.push(this.activeField$.pipe(take(1)).subscribe((activeField) => {
if (field === activeField) {
this.registryService.cancelEditMetadataField();
} else {
this.registryService.editMetadataField(field);
}
});
}
/**
* Checks whether the given metadata field is active (being edited)
* @param field
*/
isActive(field: MetadataField): Observable<boolean> {
return this.getActiveField().pipe(
map((activeField) => field === activeField),
);
}
/**
* Gets the active metadata field (being edited)
*/
getActiveField(): Observable<MetadataField> {
return this.registryService.getActiveMetadataField();
}));
}
/**
@@ -185,29 +174,14 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
this.registryService.deselectMetadataField(field);
}
/**
* Checks whether a given metadata field is selected in the list (checkbox)
* @param field
*/
isSelected(field: MetadataField): Observable<boolean> {
return this.registryService.getSelectedMetadataFields().pipe(
map((fields) => fields.find((selectedField) => selectedField === field) != null),
);
}
/**
* Delete all the selected metadata fields
*/
deleteFields() {
this.registryService.getSelectedMetadataFields().pipe(take(1)).subscribe(
(fields) => {
const tasks$ = [];
for (const field of fields) {
if (hasValue(field.id)) {
tasks$.push(this.registryService.deleteMetadataField(field.id).pipe(getFirstCompletedRemoteData()));
}
}
zip(...tasks$).subscribe((responses: RemoteData<NoContent>[]) => {
this.subscriptions.push(this.selectedMetadataFieldIDs$.pipe(
take(1),
switchMap((fieldIDs) => zip(fieldIDs.map((fieldID) => this.registryService.deleteMetadataField(fieldID).pipe(getFirstCompletedRemoteData())))),
).subscribe((responses: RemoteData<NoContent>[]) => {
const successResponses = responses.filter((response: RemoteData<NoContent>) => response.hasSucceeded);
const failedResponses = responses.filter((response: RemoteData<NoContent>) => response.hasFailed);
if (successResponses.length > 0) {
@@ -218,9 +192,7 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
}
this.registryService.deselectAllMetadataField();
this.registryService.cancelEditMetadataField();
});
},
);
}));
}
/**
@@ -231,21 +203,19 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
showNotification(success: boolean, amount: number) {
const prefix = 'admin.registries.schema.notification';
const suffix = success ? 'success' : 'failure';
const messages = observableCombineLatest([
this.translateService.get(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`),
this.translateService.get(`${prefix}.field.deleted.${suffix}`, { amount: amount }),
]);
messages.subscribe(([head, content]) => {
const head = this.translateService.instant(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`);
const content = this.translateService.instant(`${prefix}.field.deleted.${suffix}`, { amount: amount });
if (success) {
this.notificationsService.success(head, content);
} else {
this.notificationsService.error(head, content);
}
});
}
ngOnDestroy(): void {
this.paginationService.clearPagination(this.config.id);
this.registryService.deselectAllMetadataField();
this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe());
}
}

View File

@@ -19,7 +19,7 @@ import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { ResourcePoliciesComponent } from '../../shared/resource-policies/resource-policies.component';
@Component({
selector: 'ds-collection-authorizations',
selector: 'ds-bitstream-authorizations',
templateUrl: './bitstream-authorizations.component.html',
imports: [
ResourcePoliciesComponent,
@@ -30,7 +30,7 @@ import { ResourcePoliciesComponent } from '../../shared/resource-policies/resour
standalone: true,
})
/**
* Component that handles the Collection Authorizations
* Component that handles the Bitstream Authorizations
*/
export class BitstreamAuthorizationsComponent<TDomain extends DSpaceObject> implements OnInit {

View File

@@ -18,7 +18,10 @@ import {
combineLatest as observableCombineLatest,
Observable,
} from 'rxjs';
import { map } from 'rxjs/operators';
import {
map,
take,
} from 'rxjs/operators';
import { ThemedBrowseByComponent } from 'src/app/shared/browse-by/themed-browse-by.component';
import {
@@ -53,7 +56,6 @@ import { VarDirective } from '../../shared/utils/var.directive';
import {
BrowseByMetadataComponent,
browseParamsToOptions,
getBrowseSearchOptions,
} from '../browse-by-metadata/browse-by-metadata.component';
@Component({
@@ -104,15 +106,18 @@ export class BrowseByDateComponent extends BrowseByMetadataComponent implements
ngOnInit(): void {
const sortConfig = new SortOptions('default', SortDirection.ASC);
this.startsWithType = StartsWithType.date;
// include the thumbnail configuration in browse search options
this.updatePage(getBrowseSearchOptions(this.defaultBrowseId, this.paginationConfig, sortConfig, this.fetchThumbnails));
this.currentPagination$ = this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig);
this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig);
this.subs.push(
observableCombineLatest([this.route.params, this.route.queryParams, this.scope$, this.route.data,
this.currentPagination$, this.currentSort$]).pipe(
map(([routeParams, queryParams, scope, data, currentPage, currentSort]) => {
return [Object.assign({}, routeParams, queryParams, data), scope, currentPage, currentSort];
observableCombineLatest(
[ this.route.params.pipe(take(1)),
this.route.queryParams,
this.scope$,
this.currentPagination$,
this.currentSort$,
]).pipe(
map(([routeParams, queryParams, scope, currentPage, currentSort]) => {
return [Object.assign({}, routeParams, queryParams), scope, currentPage, currentSort];
}),
).subscribe(([params, scope, currentPage, currentSort]: [Params, string, PaginationComponentOptions, SortOptions]) => {
const metadataKeys = params.browseDefinition ? params.browseDefinition.metadataKeys : this.defaultMetadataKeys;

View File

@@ -23,7 +23,10 @@ import {
of as observableOf,
Subscription,
} from 'rxjs';
import { map } from 'rxjs/operators';
import {
map,
take,
} from 'rxjs/operators';
import { ThemedBrowseByComponent } from 'src/app/shared/browse-by/themed-browse-by.component';
import {
@@ -216,7 +219,13 @@ export class BrowseByMetadataComponent implements OnInit, OnChanges, OnDestroy {
this.currentPagination$ = this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig);
this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig);
this.subs.push(
observableCombineLatest([this.route.params, this.route.queryParams, this.scope$, this.currentPagination$, this.currentSort$]).pipe(
observableCombineLatest(
[ this.route.params.pipe(take(1)),
this.route.queryParams,
this.scope$,
this.currentPagination$,
this.currentSort$,
]).pipe(
map(([routeParams, queryParams, scope, currentPage, currentSort]) => {
return [Object.assign({}, routeParams, queryParams), scope, currentPage, currentSort];
}),

View File

@@ -1,6 +1,5 @@
import { Route } from '@angular/router';
import { dsoEditMenuResolver } from '../shared/dso-page/dso-edit-menu.resolver';
import { browseByDSOBreadcrumbResolver } from './browse-by-dso-breadcrumb.resolver';
import { browseByGuard } from './browse-by-guard';
import { browseByI18nBreadcrumbResolver } from './browse-by-i18n-breadcrumb.resolver';
@@ -11,7 +10,6 @@ export const ROUTES: Route[] = [
path: '',
resolve: {
breadcrumb: browseByDSOBreadcrumbResolver,
menu: dsoEditMenuResolver,
},
children: [
{

View File

@@ -23,7 +23,7 @@ import { BrowseBySwitcherComponent } from '../browse-by-switcher/browse-by-switc
})
export class BrowseByPageComponent implements OnInit {
browseByType$: Observable<BrowseByDataType>;
browseByType$: Observable<{type: BrowseByDataType }>;
constructor(
protected route: ActivatedRoute,
@@ -35,7 +35,7 @@ export class BrowseByPageComponent implements OnInit {
*/
ngOnInit(): void {
this.browseByType$ = this.route.data.pipe(
map((data: { browseDefinition: BrowseDefinition }) => data.browseDefinition.getRenderType()),
map((data: { browseDefinition: BrowseDefinition }) => ({ type: data.browseDefinition.getRenderType() })),
);
}

View File

@@ -85,7 +85,7 @@ describe('BrowseBySwitcherComponent', () => {
types.forEach((type: NonHierarchicalBrowseDefinition) => {
describe(`when switching to a browse-by page for "${type.id}"`, () => {
beforeEach(async () => {
comp.browseByType = type.dataType;
comp.browseByType = type as any;
comp.ngOnChanges({
browseByType: new SimpleChange(undefined, type.dataType, true),
});

View File

@@ -24,7 +24,7 @@ export class BrowseBySwitcherComponent extends AbstractComponentLoaderComponent<
@Input() context: Context;
@Input() browseByType: BrowseByDataType;
@Input() browseByType: { type: BrowseByDataType };
@Input() displayTitle: boolean;
@@ -43,7 +43,7 @@ export class BrowseBySwitcherComponent extends AbstractComponentLoaderComponent<
];
public getComponent(): GenericConstructor<Component> {
return getComponentByBrowseByType(this.browseByType, this.context, this.themeService.getThemeName());
return getComponentByBrowseByType(this.browseByType.type, this.context, this.themeService.getThemeName());
}
}

View File

@@ -9,7 +9,10 @@ import {
import { Params } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { combineLatest as observableCombineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import {
map,
take,
} from 'rxjs/operators';
import {
SortDirection,
@@ -28,7 +31,6 @@ import { VarDirective } from '../../shared/utils/var.directive';
import {
BrowseByMetadataComponent,
browseParamsToOptions,
getBrowseSearchOptions,
} from '../browse-by-metadata/browse-by-metadata.component';
@Component({
@@ -58,12 +60,16 @@ export class BrowseByTitleComponent extends BrowseByMetadataComponent implements
ngOnInit(): void {
const sortConfig = new SortOptions('dc.title', SortDirection.ASC);
// include the thumbnail configuration in browse search options
this.updatePage(getBrowseSearchOptions(this.defaultBrowseId, this.paginationConfig, sortConfig, this.fetchThumbnails));
this.currentPagination$ = this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig);
this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig);
this.subs.push(
observableCombineLatest([this.route.params, this.route.queryParams, this.scope$, this.currentPagination$, this.currentSort$]).pipe(
observableCombineLatest(
[ this.route.params.pipe(take(1)),
this.route.queryParams,
this.scope$,
this.currentPagination$,
this.currentSort$,
]).pipe(
map(([routeParams, queryParams, scope, currentPage, currentSort]) => {
return [Object.assign({}, routeParams, queryParams), scope, currentPage, currentSort];
}),

View File

@@ -54,7 +54,6 @@ export const ROUTES: Route[] = [
resolve: {
dso: collectionPageResolver,
breadcrumb: collectionBreadcrumbResolver,
menu: dsoEditMenuResolver,
},
runGuardsAndResolvers: 'always',
children: [
@@ -83,6 +82,9 @@ export const ROUTES: Route[] = [
{
path: '',
component: ThemedCollectionPageComponent,
resolve: {
menu: dsoEditMenuResolver,
},
children: [
{
path: '',

View File

@@ -1,8 +1,8 @@
<div class="container" *ngIf="(isLoading$ | async) === false">
<div class="row">
<div class="col-12 pb-4">
<h2 id="sub-header"
class="border-bottom pb-2">{{ 'collection.create.sub-head' | translate:{ parent: dsoNameService.getName((parentRD$| async)?.payload) } }}</h2>
<h1 id="sub-header"
class="border-bottom pb-2">{{ 'collection.create.sub-head' | translate:{ parent: dsoNameService.getName((parentRD$| async)?.payload) } }}</h1>
</div>
</div>
<ds-collection-form (submitForm)="onSubmit($event)"

View File

@@ -51,7 +51,6 @@ export const ROUTES: Route[] = [
resolve: {
dso: communityPageResolver,
breadcrumb: communityBreadcrumbResolver,
menu: dsoEditMenuResolver,
},
runGuardsAndResolvers: 'always',
children: [
@@ -70,6 +69,9 @@ export const ROUTES: Route[] = [
{
path: '',
component: ThemedCommunityPageComponent,
resolve: {
menu: dsoEditMenuResolver,
},
children: [
{
path: '',

View File

@@ -2,9 +2,9 @@
<div class="row">
<div class="col-12 pb-4">
<ng-container *ngVar="(parentRD$ | async)?.payload as parent">
<h2 *ngIf="!parent" id="header" class="border-bottom p-2">{{ 'community.create.head' | translate }}</h2>
<h2 *ngIf="parent" id="sub-header"
class="border-bottom pb-2">{{ 'community.create.sub-head' | translate:{ parent: dsoNameService.getName(parent) } }}</h2>
<h1 *ngIf="!parent" id="header" class="border-bottom p-2">{{ 'community.create.head' | translate }}</h1>
<h1 *ngIf="parent" id="sub-header"
class="border-bottom pb-2">{{ 'community.create.sub-head' | translate:{ parent: dsoNameService.getName(parent) } }}</h1>
</ng-container>
</div>
</div>

View File

@@ -7,7 +7,7 @@ import {
import { Observable } from 'rxjs';
import { BreadcrumbConfig } from '../../breadcrumbs/breadcrumb/breadcrumb-config.model';
import { ITEM_PAGE_LINKS_TO_FOLLOW } from '../../item-page/item.resolver';
import { getItemPageLinksToFollow } from '../../item-page/item.resolver';
import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { ItemDataService } from '../data/item-data.service';
import { DSpaceObject } from '../shared/dspace-object.model';
@@ -24,7 +24,7 @@ export const itemBreadcrumbResolver: ResolveFn<BreadcrumbConfig<Item>> = (
breadcrumbService: DSOBreadcrumbsService = inject(DSOBreadcrumbsService),
dataService: ItemDataService = inject(ItemDataService),
): Observable<BreadcrumbConfig<Item>> => {
const linksToFollow: FollowLinkConfig<DSpaceObject>[] = ITEM_PAGE_LINKS_TO_FOLLOW as FollowLinkConfig<DSpaceObject>[];
const linksToFollow: FollowLinkConfig<DSpaceObject>[] = getItemPageLinksToFollow() as FollowLinkConfig<DSpaceObject>[];
return DSOBreadcrumbResolver(
route,
state,

View File

@@ -7,7 +7,6 @@ import { of as observableOf } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
import { getMockHrefOnlyDataService } from '../../shared/mocks/href-only-data.service.mock';
import { getMockRemoteDataBuildService } from '../../shared/mocks/remote-data-build.service.mock';
import { getMockRequestService } from '../../shared/mocks/request.service.mock';
import {
createSuccessfulRemoteDataObject,
@@ -18,7 +17,6 @@ import {
createPaginatedList,
getFirstUsedArgumentOfSpyMethod,
} from '../../shared/testing/utils.test';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
import { RequestService } from '../data/request.service';
import { RequestEntry } from '../data/request-entry.model';
import { FlatBrowseDefinition } from '../shared/flat-browse-definition.model';
@@ -31,7 +29,6 @@ describe('BrowseService', () => {
let scheduler: TestScheduler;
let service: BrowseService;
let requestService: RequestService;
let rdbService: RemoteDataBuildService;
const browsesEndpointURL = 'https://rest.api/browses';
const halService: any = new HALEndpointServiceStub(browsesEndpointURL);
@@ -129,7 +126,6 @@ describe('BrowseService', () => {
halService,
browseDefinitionDataService,
hrefOnlyDataService,
rdbService,
);
}
@@ -141,11 +137,9 @@ describe('BrowseService', () => {
beforeEach(() => {
requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService();
spyOn(halService, 'getEndpoint').and
.returnValue(hot('--a-', { a: browsesEndpointURL }));
spyOn(rdbService, 'buildList').and.callThrough();
});
it('should call BrowseDefinitionDataService to create the RemoteData Observable', () => {
@@ -162,9 +156,7 @@ describe('BrowseService', () => {
beforeEach(() => {
requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService();
spyOn(rdbService, 'buildList').and.callThrough();
});
describe('when getBrowseEntriesFor is called with a valid browse definition id', () => {
@@ -215,7 +207,6 @@ describe('BrowseService', () => {
describe('if getBrowseDefinitions fires', () => {
beforeEach(() => {
requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService();
spyOn(service, 'getBrowseDefinitions').and
.returnValue(hot('--a-', {
@@ -270,7 +261,6 @@ describe('BrowseService', () => {
describe('if getBrowseDefinitions doesn\'t fire', () => {
it('should return undefined', () => {
requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService();
spyOn(service, 'getBrowseDefinitions').and
.returnValue(hot('----'));
@@ -288,9 +278,7 @@ describe('BrowseService', () => {
describe('getFirstItemFor', () => {
beforeEach(() => {
requestService = getMockRequestService();
rdbService = getMockRemoteDataBuildService();
service = initTestService();
spyOn(rdbService, 'buildList').and.callThrough();
});
describe('when getFirstItemFor is called with a valid browse definition id', () => {

View File

@@ -6,6 +6,7 @@ import {
startWith,
} from 'rxjs/operators';
import { environment } from '../../../environments/environment';
import {
hasValue,
hasValueOperator,
@@ -16,7 +17,6 @@ import {
followLink,
FollowLinkConfig,
} from '../../shared/utils/follow-link-config.model';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
import { SortDirection } from '../cache/models/sort-options.model';
import { HrefOnlyDataService } from '../data/href-only-data.service';
import { PaginatedList } from '../data/paginated-list.model';
@@ -38,9 +38,15 @@ import { URLCombiner } from '../url-combiner/url-combiner';
import { BrowseDefinitionDataService } from './browse-definition-data.service';
import { BrowseEntrySearchOptions } from './browse-entry-search-options.model';
export const BROWSE_LINKS_TO_FOLLOW: FollowLinkConfig<BrowseEntry | Item>[] = [
export function getBrowseLinksToFollow(): FollowLinkConfig<BrowseEntry | Item>[] {
const followLinks = [
followLink('thumbnail'),
];
];
if (environment.item.showAccessStatuses) {
followLinks.push(followLink('accessStatus'));
}
return followLinks;
}
/**
* The service handling all browse requests
@@ -67,7 +73,6 @@ export class BrowseService {
protected halService: HALEndpointService,
private browseDefinitionDataService: BrowseDefinitionDataService,
private hrefOnlyDataService: HrefOnlyDataService,
private rdb: RemoteDataBuildService,
) {
}
@@ -117,7 +122,7 @@ export class BrowseService {
}),
);
if (options.fetchThumbnail ) {
return this.hrefOnlyDataService.findListByHref<BrowseEntry>(href$, {}, undefined, undefined, ...BROWSE_LINKS_TO_FOLLOW);
return this.hrefOnlyDataService.findListByHref<BrowseEntry>(href$, {}, undefined, undefined, ...getBrowseLinksToFollow());
}
return this.hrefOnlyDataService.findListByHref<BrowseEntry>(href$);
}
@@ -165,7 +170,7 @@ export class BrowseService {
}),
);
if (options.fetchThumbnail) {
return this.hrefOnlyDataService.findListByHref<Item>(href$, {}, undefined, undefined, ...BROWSE_LINKS_TO_FOLLOW);
return this.hrefOnlyDataService.findListByHref<Item>(href$, {}, undefined, undefined, ...getBrowseLinksToFollow());
}
return this.hrefOnlyDataService.findListByHref<Item>(href$);
}

View File

@@ -174,10 +174,12 @@ export function objectCacheReducer(state = initialState, action: ObjectCacheActi
* the new state, with the object added, or overwritten.
*/
function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheAction): ObjectCacheState {
const existing = state[action.payload.objectToCache._links.self.href] || {} as any;
const cacheLink = hasValue(action.payload.objectToCache?._links?.self) ? action.payload.objectToCache._links.self.href : action.payload.alternativeLink;
const existing = state[cacheLink] || {} as any;
const newAltLinks = hasValue(action.payload.alternativeLink) ? [action.payload.alternativeLink] : [];
if (hasValue(cacheLink)) {
return Object.assign({}, state, {
[action.payload.objectToCache._links.self.href]: {
[cacheLink]: {
data: action.payload.objectToCache,
timeCompleted: action.payload.timeCompleted,
msToLive: action.payload.msToLive,
@@ -188,6 +190,9 @@ function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheActio
alternativeLinks: [...(existing.alternativeLinks || []), ...newAltLinks],
} as ObjectCacheEntry,
});
} else {
return state;
}
}
/**

View File

@@ -99,7 +99,9 @@ export class ObjectCacheService {
* An optional alternative link to this object
*/
add(object: CacheableObject, msToLive: number, requestUUID: string, alternativeLink?: string): void {
if (hasValue(object)) {
object = this.linkService.removeResolvedLinks(object); // Ensure the object we're storing has no resolved links
}
this.store.dispatch(new AddToObjectCacheAction(object, new Date().getTime(), msToLive, requestUUID, alternativeLink));
}
@@ -175,11 +177,15 @@ export class ObjectCacheService {
},
),
map((entry: ObjectCacheEntry) => {
if (hasValue(entry.data)) {
const type: GenericConstructor<T> = getClassForType((entry.data as any).type);
if (typeof type !== 'function') {
throw new Error(`${type} is not a valid constructor for ${JSON.stringify(entry.data)}`);
}
return Object.assign(new type(), entry.data) as T;
} else {
return null;
}
}),
);
}

View File

@@ -4,20 +4,16 @@ import {
inheritSerialization,
} from 'cerialize';
import {
SectionScope,
SectionVisibility,
} from '../../../submission/objects/section-visibility.model';
import { SectionsType } from '../../../submission/sections/sections-type';
import { typedObject } from '../../cache/builders/build-decorators';
import { HALLink } from '../../shared/hal-link.model';
import { ConfigObject } from './config.model';
import { SUBMISSION_SECTION_TYPE } from './config-type';
/**
* An interface that define section visibility and its properties.
*/
export interface SubmissionSectionVisibility {
main: any;
other: any;
}
@typedObject
@inheritSerialization(ConfigObject)
export class SubmissionSectionModel extends ConfigObject {
@@ -35,6 +31,12 @@ export class SubmissionSectionModel extends ConfigObject {
@autoserialize
mandatory: boolean;
/**
* The submission scope for this section
*/
@autoserialize
scope: SectionScope;
/**
* A string representing the kind of section object
*/
@@ -42,10 +44,10 @@ export class SubmissionSectionModel extends ConfigObject {
sectionType: SectionsType;
/**
* The [SubmissionSectionVisibility] object for this section
* The [SectionVisibility] object for this section
*/
@autoserialize
visibility: SubmissionSectionVisibility;
visibility: SectionVisibility;
/**
* The {@link HALLink}s for this SubmissionSectionModel

View File

@@ -65,6 +65,7 @@ describe('BaseDataService', () => {
let selfLink;
let linksToFollow;
let testScheduler;
let remoteDataTimestamp: number;
let remoteDataMocks: { [responseType: string]: RemoteData<any> };
let remoteDataPageMocks: { [responseType: string]: RemoteData<any> };
@@ -85,7 +86,9 @@ describe('BaseDataService', () => {
expect(actual).toEqual(expected);
});
const timeStamp = new Date().getTime();
// The response's lastUpdated equals the time of 60 seconds after the test started, ensuring they are not perceived
// as cached values.
remoteDataTimestamp = new Date().getTime() + 60 * 1000;
const msToLive = 15 * 60 * 1000;
const payload = {
foo: 'bar',
@@ -112,22 +115,22 @@ describe('BaseDataService', () => {
const statusCodeError = 404;
const errorMessage = 'not found';
remoteDataMocks = {
RequestPending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.RequestPending, undefined, undefined, undefined),
ResponsePending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.ResponsePending, undefined, undefined, undefined),
ResponsePendingStale: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.ResponsePendingStale, undefined, undefined, undefined),
Success: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Success, undefined, payload, statusCodeSuccess),
SuccessStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.SuccessStale, undefined, payload, statusCodeSuccess),
Error: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Error, errorMessage, undefined, statusCodeError),
ErrorStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.ErrorStale, errorMessage, undefined, statusCodeError),
RequestPending: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.RequestPending, undefined, undefined, undefined),
ResponsePending: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.ResponsePending, undefined, undefined, undefined),
ResponsePendingStale: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.ResponsePendingStale, undefined, undefined, undefined),
Success: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.Success, undefined, payload, statusCodeSuccess),
SuccessStale: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.SuccessStale, undefined, payload, statusCodeSuccess),
Error: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.Error, errorMessage, undefined, statusCodeError),
ErrorStale: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.ErrorStale, errorMessage, undefined, statusCodeError),
};
remoteDataPageMocks = {
RequestPending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.RequestPending, undefined, undefined, undefined),
ResponsePending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.ResponsePending, undefined, undefined, undefined),
ResponsePendingStale: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.ResponsePendingStale, undefined, undefined, undefined),
Success: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Success, undefined, createPaginatedList([payload]), statusCodeSuccess),
SuccessStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.SuccessStale, undefined, createPaginatedList([payload]), statusCodeSuccess),
Error: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Error, errorMessage, undefined, statusCodeError),
ErrorStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.ErrorStale, errorMessage, undefined, statusCodeError),
RequestPending: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.RequestPending, undefined, undefined, undefined),
ResponsePending: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.ResponsePending, undefined, undefined, undefined),
ResponsePendingStale: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.ResponsePendingStale, undefined, undefined, undefined),
Success: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.Success, undefined, createPaginatedList([payload]), statusCodeSuccess),
SuccessStale: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.SuccessStale, undefined, createPaginatedList([payload]), statusCodeSuccess),
Error: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.Error, errorMessage, undefined, statusCodeError),
ErrorStale: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.ErrorStale, errorMessage, undefined, statusCodeError),
};
return new TestService(
@@ -361,11 +364,15 @@ describe('BaseDataService', () => {
spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source);
});
it(`should not emit a cached completed RemoteData, but only start emitting after the state first changes to RequestPending`, () => {
it('should not emit a cached completed RemoteData', () => {
// Old cached value from 1 minute before the test started
const oldCachedSucceededData: RemoteData<any> = Object.assign({}, remoteDataPageMocks.Success, {
timeCompleted: remoteDataTimestamp - 2 * 60 * 1000,
lastUpdated: remoteDataTimestamp - 2 * 60 * 1000,
} as RemoteData<any>);
testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e', {
a: remoteDataMocks.Success,
a: oldCachedSucceededData,
b: remoteDataMocks.RequestPending,
c: remoteDataMocks.ResponsePending,
d: remoteDataMocks.Success,
@@ -383,6 +390,22 @@ describe('BaseDataService', () => {
});
});
it('should emit the first completed RemoteData since the request was made', () => {
testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b', {
a: remoteDataMocks.Success,
b: remoteDataMocks.SuccessStale,
}));
const expected = 'a-b';
const values = {
a: remoteDataMocks.Success,
b: remoteDataMocks.SuccessStale,
};
expectObservable(service.findByHref(selfLink, false, true, ...linksToFollow)).toBe(expected, values);
});
});
it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => {
testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e-f-g', {
@@ -411,17 +434,12 @@ describe('BaseDataService', () => {
it('should link all the followLinks of a cached object by calling addDependency', () => {
spyOn(objectCache, 'addDependency').and.callThrough();
testScheduler.run(({ cold, expectObservable, flush }) => {
spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d', {
spyOn(rdbService, 'buildSingle').and.returnValue(cold('a', {
a: remoteDataMocks.Success,
b: remoteDataMocks.RequestPending,
c: remoteDataMocks.ResponsePending,
d: remoteDataMocks.Success,
}));
const expected = '--b-c-d';
const expected = 'a';
const values = {
b: remoteDataMocks.RequestPending,
c: remoteDataMocks.ResponsePending,
d: remoteDataMocks.Success,
a: remoteDataMocks.Success,
};
expectObservable(service.findByHref(selfLink, false, false, ...linksToFollow)).toBe(expected, values);
@@ -570,11 +588,15 @@ describe('BaseDataService', () => {
spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source);
});
it(`should not emit a cached completed RemoteData, but only start emitting after the state first changes to RequestPending`, () => {
it('should not emit a cached completed RemoteData', () => {
testScheduler.run(({ cold, expectObservable }) => {
// Old cached value from 1 minute before the test started
const oldCachedSucceededData: RemoteData<any> = Object.assign({}, remoteDataPageMocks.Success, {
timeCompleted: remoteDataTimestamp - 2 * 60 * 1000,
lastUpdated: remoteDataTimestamp - 2 * 60 * 1000,
} as RemoteData<any>);
spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e', {
a: remoteDataPageMocks.Success,
a: oldCachedSucceededData,
b: remoteDataPageMocks.RequestPending,
c: remoteDataPageMocks.ResponsePending,
d: remoteDataPageMocks.Success,
@@ -592,6 +614,22 @@ describe('BaseDataService', () => {
});
});
it('should emit the first completed RemoteData since the request was made', () => {
testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildList').and.returnValue(cold('a-b', {
a: remoteDataPageMocks.Success,
b: remoteDataPageMocks.SuccessStale,
}));
const expected = 'a-b';
const values = {
a: remoteDataPageMocks.Success,
b: remoteDataPageMocks.SuccessStale,
};
expectObservable(service.findListByHref(selfLink, findListOptions, false, true, ...linksToFollow)).toBe(expected, values);
});
});
it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => {
testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e-f-g', {

View File

@@ -285,6 +285,7 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
map((href: string) => this.buildHrefFromFindOptions(href, {}, [], ...linksToFollow)),
);
const startTime: number = new Date().getTime();
this.createAndSendGetRequest(requestHref$, useCachedVersionIfAvailable);
const response$: Observable<RemoteData<T>> = this.rdbService.buildSingle<T>(requestHref$, ...linksToFollow).pipe(
@@ -292,7 +293,7 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
// call it isn't immediately returned, but we wait until the remote data for the new request
// is created. If useCachedVersionIfAvailable is false it also ensures you don't get a
// cached completed object
skipWhile((rd: RemoteData<T>) => rd.isStale || (!useCachedVersionIfAvailable && rd.hasCompleted)),
skipWhile((rd: RemoteData<T>) => rd.isStale || (!useCachedVersionIfAvailable && rd.lastUpdated < startTime)),
this.reRequestStaleRemoteData(reRequestOnStale, () =>
this.findByHref(href$, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)),
);
@@ -338,6 +339,7 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
map((href: string) => this.buildHrefFromFindOptions(href, options, [], ...linksToFollow)),
);
const startTime: number = new Date().getTime();
this.createAndSendGetRequest(requestHref$, useCachedVersionIfAvailable);
const response$: Observable<RemoteData<PaginatedList<T>>> = this.rdbService.buildList<T>(requestHref$, ...linksToFollow).pipe(
@@ -345,7 +347,7 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
// call it isn't immediately returned, but we wait until the remote data for the new request
// is created. If useCachedVersionIfAvailable is false it also ensures you don't get a
// cached completed object
skipWhile((rd: RemoteData<PaginatedList<T>>) => rd.isStale || (!useCachedVersionIfAvailable && rd.hasCompleted)),
skipWhile((rd: RemoteData<PaginatedList<T>>) => rd.isStale || (!useCachedVersionIfAvailable && rd.lastUpdated < startTime)),
this.reRequestStaleRemoteData(reRequestOnStale, () =>
this.findListByHref(href$, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)),
);

View File

@@ -120,6 +120,13 @@ export class DspaceRestResponseParsingService implements ResponseParsingService
if (hasValue(match)) {
embedAltUrl = new URLCombiner(embedAltUrl, `?size=${match.size}`).toString();
}
if (data._embedded[property] == null) {
// Embedded object is null, meaning it exists (not undefined), but had an empty response (204) -> cache it as null
this.addToObjectCache(null, request, data, embedAltUrl);
} else if (!isCacheableObject(data._embedded[property])) {
// Embedded object exists, but doesn't contain a self link -> cache it using the alternative link instead
this.objectCache.add(data._embedded[property], hasValue(request.responseMsToLive) ? request.responseMsToLive : environment.cache.msToLive.default, request.uuid, embedAltUrl);
}
this.process<ObjectDomain>(data._embedded[property], request, embedAltUrl);
});
}
@@ -237,7 +244,7 @@ export class DspaceRestResponseParsingService implements ResponseParsingService
* @param alternativeURL an alternative url that can be used to retrieve the object
*/
addToObjectCache(co: CacheableObject, request: RestRequest, data: any, alternativeURL?: string): void {
if (!isCacheableObject(co)) {
if (hasValue(co) && !isCacheableObject(co)) {
const type = hasValue(data) && hasValue(data.type) ? data.type : 'object';
let dataJSON: string;
if (hasValue(data._embedded)) {
@@ -251,7 +258,7 @@ export class DspaceRestResponseParsingService implements ResponseParsingService
return;
}
if (alternativeURL === co._links.self.href) {
if (hasValue(co) && alternativeURL === co._links.self.href) {
alternativeURL = undefined;
}

View File

@@ -0,0 +1,28 @@
export class ObjectUpdatesServiceStub {
initialize = jasmine.createSpy('initialize');
saveFieldUpdate = jasmine.createSpy('saveFieldUpdate');
getObjectEntry = jasmine.createSpy('getObjectEntry');
getFieldState = jasmine.createSpy('getFieldState');
getFieldUpdates = jasmine.createSpy('getFieldUpdates');
getFieldUpdatesExclusive = jasmine.createSpy('getFieldUpdatesExclusive');
isValid = jasmine.createSpy('isValid');
isValidPage = jasmine.createSpy('isValidPage');
saveAddFieldUpdate = jasmine.createSpy('saveAddFieldUpdate');
saveRemoveFieldUpdate = jasmine.createSpy('saveRemoveFieldUpdate');
saveChangeFieldUpdate = jasmine.createSpy('saveChangeFieldUpdate');
isSelectedVirtualMetadata = jasmine.createSpy('isSelectedVirtualMetadata');
setSelectedVirtualMetadata = jasmine.createSpy('setSelectedVirtualMetadata');
setEditableFieldUpdate = jasmine.createSpy('setEditableFieldUpdate');
setValidFieldUpdate = jasmine.createSpy('setValidFieldUpdate');
discardFieldUpdates = jasmine.createSpy('discardFieldUpdates');
discardAllFieldUpdates = jasmine.createSpy('discardAllFieldUpdates');
reinstateFieldUpdates = jasmine.createSpy('reinstateFieldUpdates');
removeSingleFieldUpdate = jasmine.createSpy('removeSingleFieldUpdate');
getUpdateFields = jasmine.createSpy('getUpdateFields');
hasUpdates = jasmine.createSpy('hasUpdates');
isReinstatable = jasmine.createSpy('isReinstatable');
getLastModified = jasmine.createSpy('getLastModified');
createPatch = jasmine.createSpy('getPatch');
}

View File

@@ -3,6 +3,8 @@ import { Store } from '@ngrx/store';
import { provideMockStore } from '@ngrx/store/testing';
import { of as observableOf } from 'rxjs';
import { APP_CONFIG } from '../../../config/app-config.interface';
import { environment } from '../../../environments/environment.test';
import { PAGINATED_RELATIONS_TO_ITEMS_OPERATOR } from '../../item-page/simple/item-types/shared/item-relationships-utils';
import { getMockRemoteDataBuildServiceHrefMap } from '../../shared/mocks/remote-data-build.service.mock';
import { getMockRequestService } from '../../shared/mocks/request.service.mock';
@@ -150,6 +152,7 @@ describe('RelationshipDataService', () => {
{ provide: RequestService, useValue: requestService },
{ provide: PAGINATED_RELATIONS_TO_ITEMS_OPERATOR, useValue: jasmine.createSpy('paginatedRelationsToItems').and.returnValue((v) => v) },
{ provide: Store, useValue: provideMockStore() },
{ provide: APP_CONFIG, useValue: environment },
RelationshipDataService,
],
});
@@ -157,7 +160,7 @@ describe('RelationshipDataService', () => {
});
describe('composition', () => {
const initService = () => new RelationshipDataService(null, null, null, null, null, null, null, null);
const initService = () => new RelationshipDataService(null, null, null, null, null, null, null, null, environment);
testSearchDataImplementation(initService);
});

View File

@@ -24,6 +24,10 @@ import {
tap,
} from 'rxjs/operators';
import {
APP_CONFIG,
AppConfig,
} from '../../../config/app-config.interface';
import {
AppState,
keySelector,
@@ -133,6 +137,7 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
protected itemService: ItemDataService,
protected appStore: Store<AppState>,
@Inject(PAGINATED_RELATIONS_TO_ITEMS_OPERATOR) private paginatedRelationsToItems: (thisId: string) => (source: Observable<RemoteData<PaginatedList<Relationship>>>) => Observable<RemoteData<PaginatedList<Item>>>,
@Inject(APP_CONFIG) private appConfig: AppConfig,
) {
super('relationships', requestService, rdbService, objectCache, halService, 15 * 60 * 1000);
@@ -319,7 +324,7 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
* @param options
*/
getRelatedItemsByLabel(item: Item, label: string, options?: FindListOptions): Observable<RemoteData<PaginatedList<Item>>> {
const linksToFollow: FollowLinkConfig<Relationship>[] = itemLinksToFollow(options.fetchThumbnail);
const linksToFollow: FollowLinkConfig<Relationship>[] = itemLinksToFollow(options.fetchThumbnail, this.appConfig.item.showAccessStatuses);
linksToFollow.push(followLink('relationshipType'));
return this.getItemRelationshipsByLabel(item, label, options, true, true, ...linksToFollow).pipe(this.paginatedRelationsToItems(item.uuid));

View File

@@ -190,7 +190,7 @@ export class VersionHistoryDataService extends IdentifiableDataService<VersionHi
return this.versionDataService.findByHref(versionHref, false, true, followLink('versionhistory')).pipe(
getFirstCompletedRemoteData(),
switchMap((versionRD: RemoteData<Version>) => {
if (versionRD.hasSucceeded && !versionRD.hasNoContent) {
if (versionRD.hasSucceeded && !versionRD.hasNoContent && hasValue(versionRD.payload)) {
return versionRD.payload.versionhistory.pipe(
getFirstCompletedRemoteData(),
map((versionHistoryRD: RemoteData<VersionHistory>) => {

View File

@@ -45,7 +45,7 @@ export class UUIDIndexEffects {
addObject$ = createEffect(() => this.actions$
.pipe(
ofType(ObjectCacheActionTypes.ADD),
filter((action: AddToObjectCacheAction) => hasValue(action.payload.objectToCache.uuid)),
filter((action: AddToObjectCacheAction) => hasValue(action.payload.objectToCache) && hasValue(action.payload.objectToCache.uuid)),
map((action: AddToObjectCacheAction) => {
return new AddToIndexAction(
IndexName.OBJECT,
@@ -64,7 +64,7 @@ export class UUIDIndexEffects {
ofType(ObjectCacheActionTypes.ADD),
map((action: AddToObjectCacheAction) => {
const alternativeLink = action.payload.alternativeLink;
const selfLink = action.payload.objectToCache._links.self.href;
const selfLink = hasValue(action.payload.objectToCache?._links?.self) ? action.payload.objectToCache._links.self.href : alternativeLink;
if (hasValue(alternativeLink) && alternativeLink !== selfLink) {
return new AddToIndexAction(
IndexName.ALTERNATIVE_OBJECT_LINK,

View File

@@ -16,6 +16,7 @@ import { AccessStatusObject } from '../shared/object-collection/shared/badges/ac
import { IdentifierData } from '../shared/object-list/identifier-data/identifier-data.model';
import { Subscription } from '../shared/subscriptions/models/subscription.model';
import { SubmissionCoarNotifyConfig } from '../submission/sections/section-coar-notify/submission-coar-notify.config';
import { SystemWideAlert } from '../system-wide-alert/system-wide-alert.model';
import { AuthStatus } from './auth/models/auth-status.model';
import { ShortLivedToken } from './auth/models/short-lived-token.model';
import { BulkAccessConditionOptions } from './config/models/bulk-access-condition-options.model';
@@ -186,4 +187,5 @@ export const models =
Itemfilter,
SubmissionCoarNotifyConfig,
NotifyRequestsStatus,
SystemWideAlert,
];

View File

@@ -1,4 +1,7 @@
import { autoserialize } from 'cerialize';
import {
autoserialize,
autoserializeAs,
} from 'cerialize';
import { BrowseByDataType } from '../../browse-by/browse-by-switcher/browse-by-data-type';
import { CacheableObject } from '../cache/cacheable-object.model';
@@ -11,6 +14,9 @@ export abstract class BrowseDefinition extends CacheableObject {
@autoserialize
id: string;
@autoserializeAs('metadata')
metadataKeys: string[];
/**
* Get the render type of the BrowseDefinition model
*/

View File

@@ -1,6 +1,5 @@
import {
autoserialize,
autoserializeAs,
deserialize,
inheritSerialization,
} from 'cerialize';
@@ -33,9 +32,6 @@ export class HierarchicalBrowseDefinition extends BrowseDefinition {
@autoserialize
vocabulary: string;
@autoserializeAs('metadata')
metadataKeys: string[];
get self(): string {
return this._links.self.href;
}

View File

@@ -21,9 +21,6 @@ export abstract class NonHierarchicalBrowseDefinition extends BrowseDefinition {
@autoserializeAs('order')
defaultSortOrder: string;
@autoserializeAs('metadata')
metadataKeys: string[];
@autoserialize
dataType: BrowseByDataType;
}

View File

@@ -3,20 +3,26 @@
[ngClass]="{ 'ds-warning': mdValue.reordered || mdValue.change === DsoEditMetadataChangeTypeEnum.UPDATE, 'ds-danger': mdValue.change === DsoEditMetadataChangeTypeEnum.REMOVE, 'ds-success': mdValue.change === DsoEditMetadataChangeTypeEnum.ADD, 'h-100': isOnlyValue }">
<div class="flex-grow-1 ds-flex-cell ds-value-cell d-flex flex-column" *ngVar="(mdRepresentation$ | async) as mdRepresentation" role="cell">
<div class="dont-break-out preserve-line-breaks" *ngIf="!mdValue.editing && !mdRepresentation">{{ mdValue.newValue.value }}</div>
<textarea class="form-control" rows="5" *ngIf="mdValue.editing && !mdRepresentation && (isAuthorityControlled() | async) !== true" [(ngModel)]="mdValue.newValue.value"
<textarea class="form-control" rows="5" *ngIf="mdValue.editing && !mdRepresentation && ((isAuthorityControlled() | async) !== true || (enabledFreeTextEditing && (isSuggesterVocabulary() | async) !== true))" [(ngModel)]="mdValue.newValue.value"
[attr.aria-label]="(dsoType + '.edit.metadata.edit.value') | translate"
[dsDebounce]="300" (onDebounce)="confirm.emit(false)"></textarea>
<ds-dynamic-scrollable-dropdown *ngIf="mdValue.editing && (isScrollableVocabulary() | async)"
<ds-dynamic-scrollable-dropdown *ngIf="mdValue.editing && (isScrollableVocabulary() | async) && !enabledFreeTextEditing"
[bindId]="mdField"
[group]="group"
[model]="getModel()"
(change)="onChangeAuthorityField($event)">
</ds-dynamic-scrollable-dropdown>
<ds-dynamic-onebox *ngIf="mdValue.editing && ((isHierarchicalVocabulary() | async) || (isSuggesterVocabulary() | async))"
<ds-dynamic-onebox *ngIf="mdValue.editing && (((isHierarchicalVocabulary() | async) && !enabledFreeTextEditing) || (isSuggesterVocabulary() | async))"
[group]="group"
[model]="getModel()"
(change)="onChangeAuthorityField($event)">
</ds-dynamic-onebox>
<button class="btn btn-secondary mt-2" *ngIf="mdValue.editing && ((isScrollableVocabulary() | async) || (isHierarchicalVocabulary() | async))"
[title]="enabledFreeTextEditing ? dsoType + '.edit.metadata.edit.buttons.disable-free-text-editing' : dsoType + '.edit.metadata.edit.buttons.enable-free-text-editing' | translate"
(click)="toggleFreeTextEdition()">
<i class="fas fa-fw" [ngClass]="enabledFreeTextEditing ? 'fa-lock' : 'fa-unlock'"></i>
{{ (enabledFreeTextEditing ? dsoType + '.edit.metadata.edit.buttons.disable-free-text-editing' : dsoType + '.edit.metadata.edit.buttons.enable-free-text-editing') | translate }}
</button>
<div *ngIf="!isVirtual && !mdValue.editing && mdValue.newValue.authority && mdValue.newValue.confidence !== ConfidenceTypeEnum.CF_UNSET && mdValue.newValue.confidence !== ConfidenceTypeEnum.CF_NOVALUE">
<span class="badge badge-light border" >
<i dsAuthorityConfidenceState

View File

@@ -191,6 +191,12 @@ export class DsoEditMetadataValueComponent implements OnInit, OnChanges {
*/
public editingAuthority = false;
/**
* Whether or not the free-text editing is enabled when scrollable dropdown or hierarchical vocabulary is used
*/
public enabledFreeTextEditing = false;
/**
* Field group used by authority field
* @type {UntypedFormGroup}
@@ -438,6 +444,7 @@ export class DsoEditMetadataValueComponent implements OnInit, OnChanges {
* Process the change of authority field value updating the authority key and confidence as necessary
*/
onChangeAuthorityField(event): void {
if (event) {
this.mdValue.newValue.value = event.value;
if (event.authority) {
this.mdValue.newValue.authority = event.authority;
@@ -447,6 +454,13 @@ export class DsoEditMetadataValueComponent implements OnInit, OnChanges {
this.mdValue.newValue.confidence = ConfidenceType.CF_UNSET;
}
this.confirm.emit(false);
} else {
// The event is undefined when the user clears the selection in scrollable dropdown
this.mdValue.newValue.value = '';
this.mdValue.newValue.authority = null;
this.mdValue.newValue.confidence = ConfidenceType.CF_UNSET;
this.confirm.emit(false);
}
}
/**
@@ -480,4 +494,17 @@ export class DsoEditMetadataValueComponent implements OnInit, OnChanges {
}
}
/**
* Toggles the free-text ediitng mode
*/
toggleFreeTextEdition() {
if (this.enabledFreeTextEditing) {
if (this.getModel().value !== this.mdValue.newValue.value) {
// Reload the model to adapt it to the new possible value modified during free text editing
this.initAuthorityProperties();
}
}
this.enabledFreeTextEditing = !this.enabledFreeTextEditing;
}
}

View File

@@ -6,13 +6,30 @@
[formControl]="input"
(focusin)="query$.next(mdField)"
(dsClickOutside)="query$.next(null)"
(click)="$event.stopPropagation();" />
(click)="$event.stopPropagation();"
(keyup)="this.selectedValueLoading = false"
/>
<div class="invalid-feedback show-feedback" *ngIf="showInvalid">{{ dsoType + '.edit.metadata.metadatafield.invalid' | translate }}</div>
<div class="autocomplete dropdown-menu" [ngClass]="{'show': (mdFieldOptions$ | async)?.length > 0}">
<div id="scrollable-metadata-field-selector" class="dropdown-menu scrollable-menu" [ngClass]="{'show': (mdFieldOptions$ | async)?.length > 0}">
<div class="dropdown-list">
<div *ngFor="let mdFieldOption of (mdFieldOptions$ | async)">
<button class="d-block dropdown-item" (click)="select(mdFieldOption)">
<span [innerHTML]="mdFieldOption"></span>
<div
infiniteScroll
[infiniteScrollDistance]="1"
[infiniteScrollThrottle]="0"
[infiniteScrollContainer]="'#scrollable-metadata-field-selector'"
[fromRoot]="true"
(scrolled)="onScrollDown()">
<ng-container *ngIf="mdFieldOptions$ | async">
<button *ngFor="let listEntry of (mdFieldOptions$ | async)"
class="d-block dropdown-item"
dsHoverClass="ds-hover"
(click)="select(listEntry)" #listEntryElement>
<span [innerHTML]="listEntry"></span>
</button>
</ng-container>
<button *ngIf="loading"
class="list-group-item list-group-item-action border-0 list-entry">
<ds-loading [showMessage]="false"></ds-loading>
</button>
</div>
</div>

View File

@@ -0,0 +1,5 @@
.scrollable-menu {
height: auto;
max-height: var(--ds-dso-selector-list-max-height);
overflow: scroll;
}

View File

@@ -39,7 +39,8 @@ describe('MetadataFieldSelectorComponent', () => {
metadataSchema = Object.assign(new MetadataSchema(), {
id: 0,
prefix: 'dc',
namespace: 'http://dublincore.org/documents/dcmi-terms/',
namespace: 'https://schema.org/CreativeWork',
field: '.',
});
metadataFields = [
Object.assign(new MetadataField(), {
@@ -78,10 +79,10 @@ describe('MetadataFieldSelectorComponent', () => {
});
describe('when a query is entered', () => {
const query = 'test query';
const query = 'dc.d';
beforeEach(() => {
component.showInvalid = true;
component.showInvalid = false;
component.query$.next(query);
});
@@ -90,7 +91,7 @@ describe('MetadataFieldSelectorComponent', () => {
});
it('should query the registry service for metadata fields and include the schema', () => {
expect(registryService.queryMetadataFields).toHaveBeenCalledWith(query, { elementsPerPage: 10, sort: new SortOptions('fieldName', SortDirection.ASC) }, true, false, followLink('schema'));
expect(registryService.queryMetadataFields).toHaveBeenCalledWith(query, { elementsPerPage: 20, sort: new SortOptions('fieldName', SortDirection.ASC), currentPage: 1 }, true, false, followLink('schema'));
});
});

View File

@@ -24,16 +24,18 @@ import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';
import {
BehaviorSubject,
combineLatest as observableCombineLatest,
Observable,
of,
Subscription,
} from 'rxjs';
import {
debounceTime,
distinctUntilChanged,
map,
startWith,
switchMap,
take,
tap,
@@ -50,6 +52,7 @@ import {
metadataFieldsToString,
} from '../../../core/shared/operators';
import { hasValue } from '../../../shared/empty.util';
import { ThemedLoadingComponent } from '../../../shared/loading/themed-loading.component';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { ClickOutsideDirective } from '../../../shared/utils/click-outside.directive';
import { followLink } from '../../../shared/utils/follow-link-config.model';
@@ -59,7 +62,7 @@ import { followLink } from '../../../shared/utils/follow-link-config.model';
styleUrls: ['./metadata-field-selector.component.scss'],
templateUrl: './metadata-field-selector.component.html',
standalone: true,
imports: [FormsModule, NgClass, ReactiveFormsModule, ClickOutsideDirective, NgIf, NgFor, AsyncPipe, TranslateModule],
imports: [FormsModule, NgClass, ReactiveFormsModule, ClickOutsideDirective, NgIf, NgFor, AsyncPipe, TranslateModule, ThemedLoadingComponent, InfiniteScrollModule],
})
/**
* Component displaying a searchable input for metadata-fields
@@ -96,7 +99,7 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV
* List of available metadata field options to choose from, dependent on the current query the user entered
* Shows up in a dropdown below the input
*/
mdFieldOptions$: Observable<string[]>;
mdFieldOptions$: BehaviorSubject<string[]> = new BehaviorSubject<string[]>([]);
/**
* FormControl for the input
@@ -131,6 +134,30 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV
*/
subs: Subscription[] = [];
/**
* The current page to load
* Dynamically goes up as the user scrolls down until it reaches the last page possible
*/
currentPage$ = new BehaviorSubject(1);
/**
* Whether or not the list contains a next page to load
* This allows us to avoid next pages from trying to load when there are none
*/
hasNextPage = false;
/**
* Whether or not new results are currently loading
*/
loading = false;
/**
* Default page option for this feature
*/
pageOptions = { elementsPerPage: 20, sort: new SortOptions('fieldName', SortDirection.ASC) };
constructor(protected registryService: RegistryService,
protected notificationsService: NotificationsService,
protected translate: TranslateService) {
@@ -141,32 +168,33 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV
* Update the mdFieldOptions$ depending on the query$ fired by querying the server
*/
ngOnInit(): void {
this.subs.push(
this.input.valueChanges.pipe(
this.subs.push(this.input.valueChanges.pipe(
debounceTime(this.debounceTime),
startWith(''),
).subscribe((valueChange) => {
this.currentPage$.next(1);
if (!this.selectedValueLoading) {
this.query$.next(valueChange);
}
this.selectedValueLoading = false;
this.mdField = valueChange;
this.mdFieldChange.emit(this.mdField);
}),
);
this.mdFieldOptions$ = this.query$.pipe(
distinctUntilChanged(),
switchMap((query: string) => {
this.showInvalid = false;
if (query !== null) {
return this.registryService.queryMetadataFields(query, { elementsPerPage: 10, sort: new SortOptions('fieldName', SortDirection.ASC) }, true, false, followLink('schema')).pipe(
getAllSucceededRemoteData(),
metadataFieldsToString(),
);
} else {
return [[]];
}));
this.subs.push(
observableCombineLatest(
this.query$,
this.currentPage$,
)
.pipe(
switchMap(([query, page]: [string, number]) => {
this.loading = true;
if (page === 1) {
this.mdFieldOptions$.next([]);
}
return this.search(query as string, page as number);
}),
);
).subscribe((rd ) => {
if (!this.selectedValueLoading) {this.updateList(rd);}
}));
}
/**
@@ -210,6 +238,41 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV
this.input.setValue(mdFieldOption);
}
/**
* When the user reaches the bottom of the page (or almost) and there's a next page available, increase the current page
*/
onScrollDown() {
if (this.hasNextPage && !this.loading) {
this.currentPage$.next(this.currentPage$.value + 1);
}
}
/**
* @Description It update the mdFieldOptions$ according the query result page
* */
updateList(list: string[]) {
this.loading = false;
this.hasNextPage = list.length > 0;
const currentEntries = this.mdFieldOptions$.getValue();
this.mdFieldOptions$.next([...currentEntries, ...list]);
this.selectedValueLoading = false;
}
/**
* Perform a search for the current query and page
* @param query Query to search objects for
* @param page Page to retrieve
* @param useCache Whether or not to use the cache
*/
search(query: string, page: number, useCache: boolean = true) {
return this.registryService.queryMetadataFields(query,{
elementsPerPage: this.pageOptions.elementsPerPage, sort: this.pageOptions.sort,
currentPage: page }, useCache, false, followLink('schema'))
.pipe(
getAllSucceededRemoteData(),
metadataFieldsToString(),
);
}
/**
* Unsubscribe from any open subscriptions
*/

View File

@@ -26,12 +26,12 @@
<span *ngIf="dso.allMetadata(['publicationvolume.volumeNumber']).length > 0"
class="item-list-journal-issues">
<span *ngFor="let value of allMetadataValues(['publicationvolume.volumeNumber']); let last=last;">
<span [innerHTML]="value"><span [innerHTML]="value"></span></span>
<span [innerHTML]="value"></span><span *ngIf="!last">; </span>
</span>
<span *ngIf="dso.allMetadata(['publicationissue.issueNumber']).length > 0"
class="item-list-journal-issue-numbers">
<span *ngFor="let value of allMetadataValues(['publicationissue.issueNumber']); let last=last;">
<span> - </span><span [innerHTML]="value"><span [innerHTML]="value"></span></span>
<span *ngFor="let value of allMetadataValues(['publicationissue.issueNumber']); let first=first; let last=last;">
<span *ngIf="first"> - </span><span [innerHTML]="value"></span><span *ngIf="!last">; </span>
</span>
</span>
</span>

View File

@@ -26,13 +26,13 @@
<span *ngIf="dso.allMetadata(['journal.title']).length > 0"
class="item-list-journal-volumes">
<span *ngFor="let value of allMetadataValues(['journal.title']); let last=last;">
<span [innerHTML]="value"><span [innerHTML]="value"></span></span>
<span [innerHTML]="value"></span><span *ngIf="!last">; </span>
</span>
</span>
<span *ngIf="dso.allMetadata(['publicationvolume.volumeNumber']).length > 0"
class="item-list-journal-volume-identifiers">
<span *ngFor="let value of allMetadataValues(['publicationvolume.volumeNumber']); let last=last;">
<span> (</span><span [innerHTML]="value"><span [innerHTML]="value"></span></span><span>)</span>
<span> (</span><span [innerHTML]="value"></span><span>)</span><span *ngIf="!last">;</span>
</span>
</span>
</ds-truncatable-part>

View File

@@ -24,7 +24,7 @@
<span *ngIf="dso.allMetadata(['creativeworkseries.issn']).length > 0"
class="item-list-journals">
<span *ngFor="let value of allMetadataValues(['creativeworkseries.issn']); let last=last;">
<span [innerHTML]="value"><span [innerHTML]="value"></span></span>
<span [innerHTML]="value"></span><span *ngIf="!last">; </span>
</span>
</span>
</ds-truncatable-part>

View File

@@ -32,7 +32,7 @@
<!--<span *ngIf="dso.allMetadata(['project.identifier.status']).length > 0"-->
<!--class="item-list-status">-->
<!--<span *ngFor="let value of allMetadataValues(['project.identifier.status']); let last=last;">-->
<!--<span [innerHTML]="value"><span [innerHTML]="value"></span></span>-->
<!--<span [innerHTML]="value"></span><span *ngIf="!last">; </span>-->
<!--</span>-->
<!--</span>-->
<!--</ds-truncatable-part>-->

View File

@@ -3,7 +3,7 @@
<span *ngIf="mdRepresentation.allMetadata(['person.jobTitle']).length > 0"
class="item-list-job-title">
<span *ngFor="let value of mdRepresentation.allMetadataValues(['person.jobTitle']); let last=last;">
<span [innerHTML]="value"><span [innerHTML]="value"></span></span>
<span [innerHTML]="value"></span><span *ngIf="!last">; </span>
</span>
</span>
</span>

View File

@@ -11,11 +11,11 @@
<span class="text-muted">
<span *ngIf="dso.allMetadata('organization.address.addressLocality').length > 0"
class="item-list-address-locality">
<span [innerHTML]="firstMetadataValue(['organization.address.addressLocality'])"><span [innerHTML]="firstMetadataValue(['organization.address.addressLocality'])"></span></span><span *ngIf="dso.allMetadata('organization.address.addressCountry').length > 0">, </span>
<span [innerHTML]="firstMetadataValue(['organization.address.addressLocality'])"></span><span *ngIf="dso.allMetadata('organization.address.addressCountry').length > 0">, </span>
</span>
<span *ngIf="dso.allMetadata('organization.address.addressCountry').length > 0"
class="item-list-address-country">
<span [innerHTML]="firstMetadataValue(['organization.address.addressCountry'])"><span [innerHTML]="firstMetadataValue(['organization.address.addressCountry'])"></span></span>
<span [innerHTML]="firstMetadataValue(['organization.address.addressCountry'])"></span>
</span>
</span>
</div>

View File

@@ -33,7 +33,7 @@ import { OrgUnitInputSuggestionsComponent } from './org-unit-suggestions/org-uni
@listableObjectComponent('OrgUnitSearchResult', ViewMode.ListElement, Context.EntitySearchModal)
@listableObjectComponent('OrgUnitSearchResult', ViewMode.ListElement, Context.EntitySearchModalWithNameVariants)
@Component({
selector: 'ds-person-search-result-list-submission-element',
selector: 'ds-org-unit-search-result-list-submission-element',
styleUrls: ['./org-unit-search-result-list-submission-element.component.scss'],
templateUrl: './org-unit-search-result-list-submission-element.component.html',
standalone: true,

View File

@@ -26,7 +26,7 @@
<span *ngIf="dso.allMetadata(['person.jobTitle']).length > 0"
class="item-list-job-title">
<span *ngFor="let value of allMetadataValues(['person.jobTitle']); let last=last;">
<span [innerHTML]="value"><span [innerHTML]="value"></span></span>
<span [innerHTML]="value"></span><span *ngIf="!last">; </span>
</span>
</span>
</span>

View File

@@ -98,6 +98,9 @@ export class RecentItemListComponent implements OnInit, OnDestroy {
if (this.appConfig.browseBy.showThumbnails) {
linksToFollow.push(followLink('thumbnail'));
}
if (this.appConfig.item.showAccessStatuses) {
linksToFollow.push(followLink('accessStatus'));
}
this.itemRD$ = this.searchService.search(
new PaginatedSearchOptions({

View File

@@ -8,7 +8,7 @@
<span class="align-self-center">{{'item.alerts.withdrawn' | translate}}</span>
<div class="gap-2 d-flex">
<a routerLink="/home" class="btn btn-primary btn-sm">{{"404.link.home-page" | translate}}</a>
<a *ngIf="showReinstateButton$() | async" class="btn btn-primary btn-sm" (click)="openReinstateModal()">{{ 'item.alerts.reinstate-request' | translate}}</a>
<a *ngIf="showReinstateButton$ | async" class="btn btn-primary btn-sm" (click)="openReinstateModal()">{{ 'item.alerts.reinstate-request' | translate}}</a>
</div>
</div>
</ds-alert>

View File

@@ -161,7 +161,7 @@ describe('ItemAlertsComponent', () => {
(authorizationService.isAuthorized).and.returnValue(isAdmin$);
(correctionTypeDataService.findByItem).and.returnValue(correction$);
expectObservable(component.showReinstateButton$()).toBe(expectedMarble, expectedValues);
expectObservable(component.shouldShowReinstateButton()).toBe(expectedMarble, expectedValues);
});
});

View File

@@ -5,6 +5,8 @@ import {
import {
Component,
Input,
OnChanges,
SimpleChanges,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
@@ -45,12 +47,17 @@ import {
/**
* Component displaying alerts for an item
*/
export class ItemAlertsComponent {
export class ItemAlertsComponent implements OnChanges {
/**
* The Item to display alerts for
*/
@Input() item: Item;
/**
* Whether the reinstate button should be shown
*/
showReinstateButton$: Observable<boolean>;
/**
* The AlertType enumeration
* @type {AlertType}
@@ -58,18 +65,24 @@ export class ItemAlertsComponent {
public AlertTypeEnum = AlertType;
constructor(
private authService: AuthorizationDataService,
private dsoWithdrawnReinstateModalService: DsoWithdrawnReinstateModalService,
private correctionTypeDataService: CorrectionTypeDataService,
protected authService: AuthorizationDataService,
protected dsoWithdrawnReinstateModalService: DsoWithdrawnReinstateModalService,
protected correctionTypeDataService: CorrectionTypeDataService,
) {
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.item?.currentValue.withdrawn && this.showReinstateButton$) {
this.showReinstateButton$ = this.shouldShowReinstateButton();
}
}
/**
* Determines whether to show the reinstate button.
* The button is shown if the user is not an admin and the item has a reinstate request.
* @returns An Observable that emits a boolean value indicating whether to show the reinstate button.
*/
showReinstateButton$(): Observable<boolean> {
shouldShowReinstateButton(): Observable<boolean> {
const correction$ = this.correctionTypeDataService.findByItem(this.item.uuid, true).pipe(
getFirstCompletedRemoteData(),
map((correctionTypeRD: RemoteData<PaginatedList<CorrectionType>>) => correctionTypeRD.hasSucceeded ? correctionTypeRD.payload.page : []),
@@ -78,8 +91,8 @@ export class ItemAlertsComponent {
return combineLatest([isAdmin$, correction$]).pipe(
map(([isAdmin, correction]) => {
return !isAdmin && correction.some((correctionType) => correctionType.topic === REQUEST_REINSTATE);
},
));
}),
);
}
/**

View File

@@ -16,9 +16,9 @@ import {
Subscription,
} from 'rxjs';
import {
first,
map,
switchMap,
take,
tap,
} from 'rxjs/operators';
@@ -33,7 +33,7 @@ import { getAllSucceededRemoteData } from '../../../core/shared/operators';
import { hasValue } from '../../../shared/empty.util';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { AbstractTrackableComponent } from '../../../shared/trackable/abstract-trackable.component';
import { ITEM_PAGE_LINKS_TO_FOLLOW } from '../../item.resolver';
import { getItemPageLinksToFollow } from '../../item.resolver';
import { getItemPageRoute } from '../../item-page-routing-paths';
@Component({
@@ -92,7 +92,7 @@ export class AbstractItemUpdateComponent extends AbstractTrackableComponent impl
this.item = rd.payload;
}),
switchMap((rd: RemoteData<Item>) => {
return this.itemService.findByHref(rd.payload._links.self.href, true, true, ...ITEM_PAGE_LINKS_TO_FOLLOW);
return this.itemService.findByHref(rd.payload._links.self.href, true, true, ...getItemPageLinksToFollow());
}),
getAllSucceededRemoteData(),
).subscribe((rd: RemoteData<Item>) => {
@@ -102,7 +102,7 @@ export class AbstractItemUpdateComponent extends AbstractTrackableComponent impl
super.ngOnInit();
this.discardTimeOut = environment.item.edit.undoTimeout;
this.hasChanges().pipe(first()).subscribe((hasChanges) => {
this.hasChanges().pipe(take(1)).subscribe((hasChanges) => {
if (!hasChanges) {
this.initializeOriginalFields();
} else {
@@ -187,7 +187,7 @@ export class AbstractItemUpdateComponent extends AbstractTrackableComponent impl
*/
private checkLastModified() {
const currentVersion = this.item.lastModified;
this.objectUpdatesService.getLastModified(this.url).pipe(first()).subscribe(
this.objectUpdatesService.getLastModified(this.url).pipe(take(1)).subscribe(
(updateVersion: Date) => {
if (updateVersion.getDate() !== currentVersion.getDate()) {
this.notificationsService.warning(this.getNotificationTitle('outdated'), this.getNotificationContent('outdated'));

View File

@@ -1,4 +1,8 @@
<div class="item-bitstreams" *ngVar="(bundles$ | async) as bundles">
<div class="mt-2" id="reorder-description">
<ds-alert [content]="'item.edit.bitstreams.info-alert'" [type]="AlertType.Info"></ds-alert>
</div>
<div class="button-row top d-flex mt-2 space-children-mr">
<button class="mr-auto btn btn-success"
[attr.aria-label]="'item.edit.bitstreams.upload-button' | translate"
@@ -27,21 +31,13 @@
</button>
</div>
<div *ngIf="item && bundles?.length > 0" class="container table-bordered mt-4">
<div class="row header-row font-weight-bold">
<div class="{{columnSizes.columns[0].buildClasses()}} row-element">
<ds-item-edit-bitstream-drag-handle></ds-item-edit-bitstream-drag-handle>
{{'item.edit.bitstreams.headers.name' | translate}}
</div>
<div class="{{columnSizes.columns[1].buildClasses()}} row-element">{{'item.edit.bitstreams.headers.description' | translate}}</div>
<div class="{{columnSizes.columns[2].buildClasses()}} text-center row-element">{{'item.edit.bitstreams.headers.format' | translate}}</div>
<div class="{{columnSizes.columns[3].buildClasses()}} text-center row-element">{{'item.edit.bitstreams.headers.actions' | translate}}</div>
</div>
<ds-item-edit-bitstream-bundle *ngFor="let bundle of bundles"
<div *ngIf="item && bundles?.length > 0" class="mt-4 table-border scrollable-table" [ngClass]="{'disabled-overlay': (isProcessingMoveRequest | async)}">
<ds-item-edit-bitstream-bundle *ngFor="let bundle of bundles; first as isFirst"
[bundle]="bundle"
[item]="item"
[columnSizes]="columnSizes"
(dropObject)="dropBitstream(bundle, $event)">
[isFirstTable]="isFirst"
aria-describedby="reorder-description">
</ds-item-edit-bitstream-bundle>
</div>
<div *ngIf="bundles?.length === 0"
@@ -74,3 +70,5 @@
</div>
</div>
</div>
<ds-loading *ngIf="isProcessingMoveRequest | async" class="loading-overlay"></ds-loading>

View File

@@ -1,23 +1,4 @@
.header-row {
color: var(--bs-table-dark-color);
background-color: var(--bs-table-dark-bg);
border-color: var(--bs-table-dark-border-color);
}
.bundle-row {
color: var(--bs-table-head-color);
background-color: var(--bs-table-head-bg);
border-color: var(--bs-table-border-color);
}
.row-element {
padding: 12px;
padding: 0.75em;
border-bottom: var(--bs-table-border-width) solid var(--bs-table-border-color);
}
.drag-handle {
visibility: hidden;
&:hover {
cursor: move;
}
@@ -27,10 +8,6 @@
cursor: move;
}
:host ::ng-deep .bitstream-row:hover .drag-handle, :host ::ng-deep .bitstream-row-drag-handle:focus .drag-handle {
visibility: visible !important;
}
.cdk-drag-preview {
margin-left: 0;
box-sizing: border-box;
@@ -54,3 +31,25 @@
:host ::ng-deep .larger-tooltip .tooltip-inner {
max-width: 500px;
}
.table-border {
border: 1px solid #dee2e6;
}
:host ::ng-deep .pagination {
padding-top: 0.5rem;
}
.scrollable-table {
overflow-x: auto;
}
.disabled-overlay {
opacity: 0.6;
}
.loading-overlay {
position: fixed;
top: 50%;
left: 50%;
}

View File

@@ -7,6 +7,7 @@ import {
TestBed,
waitForAsync,
} from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
ActivatedRoute,
Router,
@@ -15,7 +16,6 @@ import { TranslateModule } from '@ngx-translate/core';
import { of as observableOf } from 'rxjs';
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import { RestResponse } from '../../../core/cache/response.models';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { BundleDataService } from '../../../core/data/bundle-data.service';
import { ItemDataService } from '../../../core/data/item-data.service';
@@ -44,8 +44,12 @@ import { createPaginatedList } from '../../../shared/testing/utils.test';
import { ObjectValuesPipe } from '../../../shared/utils/object-values-pipe';
import { VarDirective } from '../../../shared/utils/var.directive';
import { ItemBitstreamsComponent } from './item-bitstreams.component';
import { ItemBitstreamsService } from './item-bitstreams.service';
import {
getItemBitstreamsServiceStub,
ItemBitstreamsServiceStub,
} from './item-bitstreams.service.stub';
import { ItemEditBitstreamBundleComponent } from './item-edit-bitstream-bundle/item-edit-bitstream-bundle.component';
import { ItemEditBitstreamDragHandleComponent } from './item-edit-bitstream-drag-handle/item-edit-bitstream-drag-handle.component';
let comp: ItemBitstreamsComponent;
let fixture: ComponentFixture<ItemBitstreamsComponent>;
@@ -97,6 +101,7 @@ let objectCache: ObjectCacheService;
let requestService: RequestService;
let searchConfig: SearchConfigurationService;
let bundleService: BundleDataService;
let itemBitstreamsService: ItemBitstreamsServiceStub;
describe('ItemBitstreamsComponent', () => {
beforeEach(waitForAsync(() => {
@@ -165,11 +170,19 @@ describe('ItemBitstreamsComponent', () => {
url: url,
});
bundleService = jasmine.createSpyObj('bundleService', {
patch: observableOf(new RestResponse(true, 200, 'OK')),
patch: createSuccessfulRemoteDataObject$({}),
});
itemBitstreamsService = getItemBitstreamsServiceStub();
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ItemBitstreamsComponent, ObjectValuesPipe, VarDirective],
imports: [
TranslateModule.forRoot(),
ItemBitstreamsComponent,
ObjectValuesPipe,
VarDirective,
BrowserAnimationsModule,
],
providers: [
{ provide: ItemDataService, useValue: itemService },
{ provide: ObjectUpdatesService, useValue: objectUpdatesService },
@@ -181,6 +194,7 @@ describe('ItemBitstreamsComponent', () => {
{ provide: RequestService, useValue: requestService },
{ provide: SearchConfigurationService, useValue: searchConfig },
{ provide: BundleDataService, useValue: bundleService },
{ provide: ItemBitstreamsService, useValue: itemBitstreamsService },
ChangeDetectorRef,
], schemas: [
NO_ERRORS_SCHEMA,
@@ -189,7 +203,6 @@ describe('ItemBitstreamsComponent', () => {
.overrideComponent(ItemBitstreamsComponent, {
remove: {
imports: [ItemEditBitstreamBundleComponent,
ItemEditBitstreamDragHandleComponent,
ThemedLoadingComponent],
},
})
@@ -209,28 +222,8 @@ describe('ItemBitstreamsComponent', () => {
comp.submit();
});
it('should call removeMultiple on the bitstreamService for the marked field', () => {
expect(bitstreamService.removeMultiple).toHaveBeenCalledWith([bitstream2]);
});
it('should not call removeMultiple on the bitstreamService for the unmarked field', () => {
expect(bitstreamService.removeMultiple).not.toHaveBeenCalledWith([bitstream1]);
});
});
describe('when dropBitstream is called', () => {
beforeEach((done) => {
comp.dropBitstream(bundle, {
fromIndex: 0,
toIndex: 50,
finish: () => {
done();
},
});
});
it('should send out a patch for the move operation', () => {
expect(bundleService.patch).toHaveBeenCalled();
it('should call removeMarkedBitstreams on the itemBitstreamsService', () => {
expect(itemBitstreamsService.removeMarkedBitstreams).toHaveBeenCalled();
});
});
@@ -247,4 +240,114 @@ describe('ItemBitstreamsComponent', () => {
expect(objectUpdatesService.reinstateFieldUpdates).toHaveBeenCalledWith(bundle.self);
});
});
describe('moveUp', () => {
it('should move the selected bitstream up', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(true);
const event = {
preventDefault: () => {/* Intentionally empty */},
} as KeyboardEvent;
comp.moveUp(event);
expect(itemBitstreamsService.moveSelectedBitstreamUp).toHaveBeenCalled();
});
it('should not do anything if no bitstream is selected', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(false);
const event = {
preventDefault: () => {/* Intentionally empty */},
} as KeyboardEvent;
comp.moveUp(event);
expect(itemBitstreamsService.moveSelectedBitstreamUp).not.toHaveBeenCalled();
});
});
describe('moveDown', () => {
it('should move the selected bitstream down', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(true);
const event = {
preventDefault: () => {/* Intentionally empty */},
} as KeyboardEvent;
comp.moveDown(event);
expect(itemBitstreamsService.moveSelectedBitstreamDown).toHaveBeenCalled();
});
it('should not do anything if no bitstream is selected', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(false);
const event = {
preventDefault: () => {/* Intentionally empty */},
} as KeyboardEvent;
comp.moveDown(event);
expect(itemBitstreamsService.moveSelectedBitstreamDown).not.toHaveBeenCalled();
});
});
describe('cancelSelection', () => {
it('should cancel the selection', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(true);
const event = {
preventDefault: () => {/* Intentionally empty */},
} as KeyboardEvent;
comp.cancelSelection(event);
expect(itemBitstreamsService.cancelSelection).toHaveBeenCalled();
});
it('should not do anything if no bitstream is selected', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(false);
const event = {
preventDefault: () => {/* Intentionally empty */},
} as KeyboardEvent;
comp.cancelSelection(event);
expect(itemBitstreamsService.cancelSelection).not.toHaveBeenCalled();
});
});
describe('clearSelection', () => {
it('should clear the selection', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(true);
const event = {
target: document.createElement('BODY'),
preventDefault: () => {/* Intentionally empty */},
} as unknown as KeyboardEvent;
comp.clearSelection(event);
expect(itemBitstreamsService.clearSelection).toHaveBeenCalled();
});
it('should not do anything if no bitstream is selected', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(false);
const event = {
target: document.createElement('BODY'),
preventDefault: () => {/* Intentionally empty */},
} as unknown as KeyboardEvent;
comp.clearSelection(event);
expect(itemBitstreamsService.clearSelection).not.toHaveBeenCalled();
});
it('should not do anything if the event target is not \'BODY\'', () => {
itemBitstreamsService.hasSelectedBitstream.and.returnValue(true);
const event = {
target: document.createElement('NOT-BODY'),
preventDefault: () => {/* Intentionally empty */},
} as unknown as KeyboardEvent;
comp.clearSelection(event);
expect(itemBitstreamsService.clearSelection).not.toHaveBeenCalled();
});
});
});

View File

@@ -1,11 +1,8 @@
import {
AsyncPipe,
NgForOf,
NgIf,
} from '@angular/common';
import { CommonModule } from '@angular/common';
import {
ChangeDetectorRef,
Component,
HostListener,
NgZone,
OnDestroy,
} from '@angular/core';
@@ -18,15 +15,12 @@ import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { Operation } from 'fast-json-patch';
import {
combineLatest,
Observable,
Subscription,
zip as observableZip,
} from 'rxjs';
import {
filter,
map,
switchMap,
take,
@@ -36,49 +30,40 @@ import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { BundleDataService } from '../../../core/data/bundle-data.service';
import { ItemDataService } from '../../../core/data/item-data.service';
import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model';
import { FieldUpdate } from '../../../core/data/object-updates/field-update.model';
import { FieldUpdates } from '../../../core/data/object-updates/field-updates.model';
import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { Bitstream } from '../../../core/shared/bitstream.model';
import { Bundle } from '../../../core/shared/bundle.model';
import { NoContent } from '../../../core/shared/NoContent.model';
import {
getFirstSucceededRemoteData,
getRemoteDataPayload,
} from '../../../core/shared/operators';
import {
hasValue,
isNotEmpty,
} from '../../../shared/empty.util';
import { AlertComponent } from '../../../shared/alert/alert.component';
import { AlertType } from '../../../shared/alert/alert-type';
import { ThemedLoadingComponent } from '../../../shared/loading/themed-loading.component';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes';
import { PaginatedSearchOptions } from '../../../shared/search/models/paginated-search-options.model';
import { ObjectValuesPipe } from '../../../shared/utils/object-values-pipe';
import { VarDirective } from '../../../shared/utils/var.directive';
import { AbstractItemUpdateComponent } from '../abstract-item-update/abstract-item-update.component';
import { ItemBitstreamsService } from './item-bitstreams.service';
import { ItemEditBitstreamBundleComponent } from './item-edit-bitstream-bundle/item-edit-bitstream-bundle.component';
import { ItemEditBitstreamDragHandleComponent } from './item-edit-bitstream-drag-handle/item-edit-bitstream-drag-handle.component';
@Component({
selector: 'ds-item-bitstreams',
styleUrls: ['./item-bitstreams.component.scss'],
templateUrl: './item-bitstreams.component.html',
imports: [
AsyncPipe,
CommonModule,
TranslateModule,
ItemEditBitstreamBundleComponent,
RouterLink,
NgIf,
VarDirective,
ItemEditBitstreamDragHandleComponent,
NgForOf,
ThemedLoadingComponent,
AlertComponent,
],
providers: [ObjectValuesPipe],
standalone: true,
@@ -88,33 +73,18 @@ import { ItemEditBitstreamDragHandleComponent } from './item-edit-bitstream-drag
*/
export class ItemBitstreamsComponent extends AbstractItemUpdateComponent implements OnDestroy {
// Declared for use in template
protected readonly AlertType = AlertType;
/**
* The currently listed bundles
*/
bundles$: Observable<Bundle[]>;
/**
* The page options to use for fetching the bundles
*/
bundlesOptions = {
id: 'bundles-pagination-options',
currentPage: 1,
pageSize: 9999,
} as any;
/**
* The bootstrap sizes used for the columns within this table
*/
columnSizes = new ResponsiveTableSizes([
// Name column
new ResponsiveColumnSizes(2, 2, 3, 4, 4),
// Description column
new ResponsiveColumnSizes(2, 3, 3, 3, 3),
// Format column
new ResponsiveColumnSizes(2, 2, 2, 2, 2),
// Actions column
new ResponsiveColumnSizes(6, 5, 4, 3, 3),
]);
columnSizes: ResponsiveTableSizes;
/**
* Are we currently submitting the changes?
@@ -128,6 +98,11 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
*/
itemUpdateSubscription: Subscription;
/**
* An observable which emits a boolean which represents whether the service is currently handling a 'move' request
*/
isProcessingMoveRequest: Observable<boolean>;
constructor(
public itemService: ItemDataService,
public objectUpdatesService: ObjectUpdatesService,
@@ -141,21 +116,82 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
public cdRef: ChangeDetectorRef,
public bundleService: BundleDataService,
public zone: NgZone,
public itemBitstreamsService: ItemBitstreamsService,
) {
super(itemService, objectUpdatesService, router, notificationsService, translateService, route);
this.columnSizes = this.itemBitstreamsService.getColumnSizes();
}
/**
* Actions to perform after the item has been initialized
*/
postItemInit(): void {
this.bundles$ = this.itemService.getBundles(this.item.id, new PaginatedSearchOptions({ pagination: this.bundlesOptions })).pipe(
const bundlesOptions = this.itemBitstreamsService.getInitialBundlesPaginationOptions();
this.isProcessingMoveRequest = this.itemBitstreamsService.getPerformingMoveRequest$();
this.bundles$ = this.itemService.getBundles(this.item.id, new PaginatedSearchOptions({ pagination: bundlesOptions })).pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
map((bundlePage: PaginatedList<Bundle>) => bundlePage.page),
);
}
/**
* Handles keyboard events that should move the currently selected bitstream up
*/
@HostListener('document:keydown.arrowUp', ['$event'])
moveUp(event: KeyboardEvent) {
if (this.itemBitstreamsService.hasSelectedBitstream()) {
event.preventDefault();
this.itemBitstreamsService.moveSelectedBitstreamUp();
}
}
/**
* Handles keyboard events that should move the currently selected bitstream down
*/
@HostListener('document:keydown.arrowDown', ['$event'])
moveDown(event: KeyboardEvent) {
if (this.itemBitstreamsService.hasSelectedBitstream()) {
event.preventDefault();
this.itemBitstreamsService.moveSelectedBitstreamDown();
}
}
/**
* Handles keyboard events that should cancel the currently selected bitstream.
* A cancel means that the selected bitstream is returned to its original position and is no longer selected.
* @param event
*/
@HostListener('document:keyup.escape', ['$event'])
cancelSelection(event: KeyboardEvent) {
if (this.itemBitstreamsService.hasSelectedBitstream()) {
event.preventDefault();
this.itemBitstreamsService.cancelSelection();
}
}
/**
* Handles keyboard events that should clear the currently selected bitstream.
* A clear means that the selected bitstream remains in its current position but is no longer selected.
*/
@HostListener('document:keydown.enter', ['$event'])
@HostListener('document:keydown.space', ['$event'])
clearSelection(event: KeyboardEvent) {
// Only when no specific element is in focus do we want to clear the currently selected bitstream
// Otherwise we might clear the selection when a different action was intended, e.g. clicking a button or selecting
// a different bitstream.
if (
this.itemBitstreamsService.hasSelectedBitstream() &&
event.target instanceof Element &&
event.target.tagName === 'BODY'
) {
event.preventDefault();
this.itemBitstreamsService.clearSelection();
}
}
/**
* Initialize the notification messages prefix
*/
@@ -171,84 +207,16 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
*/
submit() {
this.submitting = true;
const bundlesOnce$ = this.bundles$.pipe(take(1));
// Fetch all removed bitstreams from the object update service
const removedBitstreams$ = bundlesOnce$.pipe(
switchMap((bundles: Bundle[]) => observableZip(
...bundles.map((bundle: Bundle) => this.objectUpdatesService.getFieldUpdates(bundle.self, [], true)),
)),
map((fieldUpdates: FieldUpdates[]) => ([] as FieldUpdate[]).concat(
...fieldUpdates.map((updates: FieldUpdates) => Object.values(updates).filter((fieldUpdate: FieldUpdate) => fieldUpdate.changeType === FieldChangeType.REMOVE)),
)),
map((fieldUpdates: FieldUpdate[]) => fieldUpdates.map((fieldUpdate: FieldUpdate) => fieldUpdate.field)),
);
// Send out delete requests for all deleted bitstreams
const removedResponses$: Observable<RemoteData<NoContent>> = removedBitstreams$.pipe(
take(1),
switchMap((removedBitstreams: Bitstream[]) => {
return this.bitstreamService.removeMultiple(removedBitstreams);
}),
);
const removedResponses$ = this.itemBitstreamsService.removeMarkedBitstreams(this.bundles$);
// Perform the setup actions from above in order and display notifications
removedResponses$.subscribe((responses: RemoteData<NoContent>) => {
this.displayNotifications('item.edit.bitstreams.notifications.remove', [responses]);
this.itemBitstreamsService.displayNotifications('item.edit.bitstreams.notifications.remove', [responses]);
this.submitting = false;
});
}
/**
* A bitstream was dropped in a new location. Send out a Move Patch request to the REST API, display notifications,
* refresh the bundle's cache (so the lists can properly reload) and call the event's callback function (which will
* navigate the user to the correct page)
* @param bundle The bundle to send patch requests to
* @param event The event containing the index the bitstream came from and was dropped to
*/
dropBitstream(bundle: Bundle, event: any) {
this.zone.runOutsideAngular(() => {
if (hasValue(event) && hasValue(event.fromIndex) && hasValue(event.toIndex) && hasValue(event.finish)) {
const moveOperation = {
op: 'move',
from: `/_links/bitstreams/${event.fromIndex}/href`,
path: `/_links/bitstreams/${event.toIndex}/href`,
} as Operation;
this.bundleService.patch(bundle, [moveOperation]).pipe(take(1)).subscribe((response: RemoteData<Bundle>) => {
this.zone.run(() => {
this.displayNotifications('item.edit.bitstreams.notifications.move', [response]);
// Remove all cached requests from this bundle and call the event's callback when the requests are cleared
this.requestService.removeByHrefSubstring(bundle.self).pipe(
filter((isCached) => isCached),
take(1),
).subscribe(() => event.finish());
});
});
}
});
}
/**
* Display notifications
* - Error notification for each failed response with their message
* - Success notification in case there's at least one successful response
* @param key The i18n key for the notification messages
* @param responses The returned responses to display notifications for
*/
displayNotifications(key: string, responses: RemoteData<any>[]) {
if (isNotEmpty(responses)) {
const failedResponses = responses.filter((response: RemoteData<Bundle>) => hasValue(response) && response.hasFailed);
const successfulResponses = responses.filter((response: RemoteData<Bundle>) => hasValue(response) && response.hasSucceeded);
failedResponses.forEach((response: RemoteData<Bundle>) => {
this.notificationsService.error(this.translateService.instant(`${key}.failed.title`), response.errorMessage);
});
if (successfulResponses.length > 0) {
this.notificationsService.success(this.translateService.instant(`${key}.saved.title`), this.translateService.instant(`${key}.saved.content`));
}
}
}
/**
* Request the object updates service to discard all current changes to this item
* Shows a notification to remind the user that they can undo this

View File

@@ -0,0 +1,712 @@
import {
fakeAsync,
tick,
} from '@angular/core/testing';
import { TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { BundleDataService } from '../../../core/data/bundle-data.service';
import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service';
import { ObjectUpdatesServiceStub } from '../../../core/data/object-updates/object-updates.service.stub';
import { RequestService } from '../../../core/data/request.service';
import { Bitstream } from '../../../core/shared/bitstream.model';
import { BitstreamFormat } from '../../../core/shared/bitstream-format.model';
import { Bundle } from '../../../core/shared/bundle.model';
import { LiveRegionService } from '../../../shared/live-region/live-region.service';
import { getLiveRegionServiceStub } from '../../../shared/live-region/live-region.service.stub';
import { DSONameServiceMock } from '../../../shared/mocks/dso-name.service.mock';
import { getMockTranslateService } from '../../../shared/mocks/translate.service.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import {
createFailedRemoteDataObject,
createSuccessfulRemoteDataObject,
createSuccessfulRemoteDataObject$,
} from '../../../shared/remote-data.utils';
import { BitstreamDataServiceStub } from '../../../shared/testing/bitstream-data-service.stub';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import {
ItemBitstreamsService,
SelectedBitstreamTableEntry,
} from './item-bitstreams.service';
import createSpy = jasmine.createSpy;
import { MoveOperation } from 'fast-json-patch';
describe('ItemBitstreamsService', () => {
let service: ItemBitstreamsService;
let notificationsService: NotificationsService;
let translateService: TranslateService;
let objectUpdatesService: ObjectUpdatesService;
let bitstreamDataService: BitstreamDataService;
let bundleDataService: BundleDataService;
let dsoNameService: DSONameService;
let requestService: RequestService;
let liveRegionService: LiveRegionService;
beforeEach(() => {
notificationsService = new NotificationsServiceStub() as any;
translateService = getMockTranslateService();
objectUpdatesService = new ObjectUpdatesServiceStub() as any;
bitstreamDataService = new BitstreamDataServiceStub() as any;
bundleDataService = jasmine.createSpyObj('bundleDataService', {
patch: createSuccessfulRemoteDataObject$(new Bundle()),
});
dsoNameService = new DSONameServiceMock() as any;
requestService = jasmine.createSpyObj('requestService', {
setStaleByHrefSubstring: of(true),
});
liveRegionService = getLiveRegionServiceStub();
service = new ItemBitstreamsService(
notificationsService,
translateService,
objectUpdatesService,
bitstreamDataService,
bundleDataService,
dsoNameService,
requestService,
liveRegionService,
);
});
const defaultEntry: SelectedBitstreamTableEntry = {
bitstream: {
name: 'bitstream name',
} as any,
bundle: Object.assign(new Bundle(), {
_links: { self: { href: 'self_link' } },
}),
bundleSize: 10,
currentPosition: 0,
originalPosition: 0,
};
describe('selectBitstreamEntry', () => {
it('should correctly make getSelectedBitstream$ emit', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
const entry = Object.assign({}, defaultEntry);
service.selectBitstreamEntry(entry);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
}));
it('should correctly make getSelectedBitstream return the bitstream', () => {
expect(service.getSelectedBitstream()).toBeNull();
const entry = Object.assign({}, defaultEntry);
service.selectBitstreamEntry(entry);
expect(service.getSelectedBitstream()).toEqual(entry);
});
it('should correctly make hasSelectedBitstream return', () => {
expect(service.hasSelectedBitstream()).toBeFalse();
const entry = Object.assign({}, defaultEntry);
service.selectBitstreamEntry(entry);
expect(service.hasSelectedBitstream()).toBeTrue();
});
it('should do nothing if no entry was provided', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
const entry = Object.assign({}, defaultEntry);
service.selectBitstreamEntry(entry);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
service.selectBitstreamEntry(null);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
}));
it('should announce the selected bitstream', () => {
const entry = Object.assign({}, defaultEntry);
spyOn(service, 'announceSelect');
service.selectBitstreamEntry(entry);
expect(service.announceSelect).toHaveBeenCalledWith(entry.bitstream.name);
});
});
describe('clearSelection', () => {
it('should clear the selected bitstream', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
const entry = Object.assign({}, defaultEntry);
service.selectBitstreamEntry(entry);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
service.clearSelection();
tick();
expect(emittedActions.length).toBe(3);
expect(emittedActions[2]).toEqual({ action: 'Cleared', selectedEntry: entry });
}));
it('should not do anything if there is no selected bitstream', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
service.clearSelection();
tick();
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
}));
it('should announce the cleared bitstream', () => {
const entry = Object.assign({}, defaultEntry);
spyOn(service, 'announceClear');
service.selectBitstreamEntry(entry);
service.clearSelection();
expect(service.announceClear).toHaveBeenCalledWith(entry.bitstream.name);
});
it('should display a notification if the selected bitstream was moved', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: 7,
},
);
spyOn(service, 'displaySuccessNotification');
service.selectBitstreamEntry(entry);
service.clearSelection();
expect(service.displaySuccessNotification).toHaveBeenCalled();
});
it('should not display a notification if the selected bitstream is in its original position', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 7,
currentPosition: 7,
},
);
spyOn(service, 'displaySuccessNotification');
service.selectBitstreamEntry(entry);
service.clearSelection();
expect(service.displaySuccessNotification).not.toHaveBeenCalled();
});
});
describe('cancelSelection', () => {
it('should clear the selected bitstream if it has not moved', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
const entry = Object.assign({}, defaultEntry);
service.selectBitstreamEntry(entry);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
service.cancelSelection();
tick();
expect(emittedActions.length).toBe(3);
expect(emittedActions[2]).toEqual({ action: 'Cleared', selectedEntry: entry });
}));
it('should cancel the selected bitstream if it has moved', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
const entry = Object.assign({}, defaultEntry, {
originalPosition: 0,
currentPosition: 3,
});
service.selectBitstreamEntry(entry);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
service.cancelSelection();
tick();
expect(emittedActions.length).toBe(3);
expect(emittedActions[2]).toEqual({ action: 'Cancelled', selectedEntry: entry });
}));
it('should announce a clear if the bitstream has not moved', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 7,
currentPosition: 7,
},
);
spyOn(service, 'announceClear');
spyOn(service, 'announceCancel');
service.selectBitstreamEntry(entry);
service.cancelSelection();
expect(service.announceClear).toHaveBeenCalledWith(entry.bitstream.name);
expect(service.announceCancel).not.toHaveBeenCalled();
});
it('should announce a cancel if the bitstream has moved', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: 7,
},
);
spyOn(service, 'announceClear');
spyOn(service, 'announceCancel');
service.selectBitstreamEntry(entry);
service.cancelSelection();
expect(service.announceClear).not.toHaveBeenCalled();
expect(service.announceCancel).toHaveBeenCalledWith(entry.bitstream.name, entry.originalPosition);
});
it('should return the bitstream to its original position if it has moved', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: 7,
},
);
spyOn(service, 'performBitstreamMoveRequest');
service.selectBitstreamEntry(entry);
service.cancelSelection();
expect(service.performBitstreamMoveRequest).toHaveBeenCalledWith(entry.bundle, entry.currentPosition, entry.originalPosition);
});
it('should not move the bitstream if it has not moved', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 7,
currentPosition: 7,
},
);
spyOn(service, 'performBitstreamMoveRequest');
service.selectBitstreamEntry(entry);
service.cancelSelection();
expect(service.performBitstreamMoveRequest).not.toHaveBeenCalled();
});
it('should not do anything if there is no selected bitstream', () => {
spyOn(service, 'announceClear');
spyOn(service, 'announceCancel');
spyOn(service, 'performBitstreamMoveRequest');
service.cancelSelection();
expect(service.announceClear).not.toHaveBeenCalled();
expect(service.announceCancel).not.toHaveBeenCalled();
expect(service.performBitstreamMoveRequest).not.toHaveBeenCalled();
});
});
describe('moveSelectedBitstream', () => {
beforeEach(() => {
spyOn(service, 'performBitstreamMoveRequest').and.callThrough();
});
describe('up', () => {
it('should move the selected bitstream one position up', () => {
const startPosition = 7;
const endPosition = startPosition - 1;
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: startPosition,
},
);
const movedEntry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: endPosition,
},
);
service.selectBitstreamEntry(entry);
service.moveSelectedBitstreamUp();
expect(service.performBitstreamMoveRequest).toHaveBeenCalledWith(entry.bundle, startPosition, endPosition, jasmine.any(Function));
expect(service.getSelectedBitstream()).toEqual(movedEntry);
});
it('should emit the move', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
const startPosition = 7;
const endPosition = startPosition - 1;
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: startPosition,
},
);
const movedEntry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: endPosition,
},
);
service.selectBitstreamEntry(entry);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
service.moveSelectedBitstreamUp();
tick();
expect(emittedActions.length).toBe(3);
expect(emittedActions[2]).toEqual({ action: 'Moved', selectedEntry: movedEntry });
}));
it('should announce the move', () => {
const startPosition = 7;
const endPosition = startPosition - 1;
spyOn(service, 'announceMove');
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: startPosition,
},
);
service.selectBitstreamEntry(entry);
service.moveSelectedBitstreamUp();
expect(service.announceMove).toHaveBeenCalledWith(entry.bitstream.name, endPosition);
});
it('should not do anything if the bitstream is already at the top', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: 0,
},
);
service.selectBitstreamEntry(entry);
service.moveSelectedBitstreamUp();
expect(service.performBitstreamMoveRequest).not.toHaveBeenCalled();
});
it('should not do anything if there is no selected bitstream', () => {
service.moveSelectedBitstreamUp();
expect(service.performBitstreamMoveRequest).not.toHaveBeenCalled();
});
});
describe('down', () => {
it('should move the selected bitstream one position down', () => {
const startPosition = 7;
const endPosition = startPosition + 1;
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: startPosition,
},
);
const movedEntry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: endPosition,
},
);
service.selectBitstreamEntry(entry);
service.moveSelectedBitstreamDown();
expect(service.performBitstreamMoveRequest).toHaveBeenCalledWith(entry.bundle, startPosition, endPosition, jasmine.any(Function));
expect(service.getSelectedBitstream()).toEqual(movedEntry);
});
it('should emit the move', fakeAsync(() => {
const emittedActions = [];
service.getSelectionAction$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeNull();
const startPosition = 7;
const endPosition = startPosition + 1;
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: startPosition,
},
);
const movedEntry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: endPosition,
},
);
service.selectBitstreamEntry(entry);
tick();
expect(emittedActions.length).toBe(2);
expect(emittedActions[1]).toEqual({ action: 'Selected', selectedEntry: entry });
service.moveSelectedBitstreamDown();
tick();
expect(emittedActions.length).toBe(3);
expect(emittedActions[2]).toEqual({ action: 'Moved', selectedEntry: movedEntry });
}));
it('should announce the move', () => {
const startPosition = 7;
const endPosition = startPosition + 1;
spyOn(service, 'announceMove');
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: startPosition,
},
);
service.selectBitstreamEntry(entry);
service.moveSelectedBitstreamDown();
expect(service.announceMove).toHaveBeenCalledWith(entry.bitstream.name, endPosition);
});
it('should not do anything if the bitstream is already at the bottom of the bundle', () => {
const entry = Object.assign({}, defaultEntry,
{
originalPosition: 5,
currentPosition: 9,
},
);
service.selectBitstreamEntry(entry);
service.moveSelectedBitstreamDown();
expect(service.performBitstreamMoveRequest).not.toHaveBeenCalled();
});
it('should not do anything if there is no selected bitstream', () => {
service.moveSelectedBitstreamDown();
expect(service.performBitstreamMoveRequest).not.toHaveBeenCalled();
});
});
});
describe('performBitstreamMoveRequest', () => {
const bundle: Bundle = defaultEntry.bundle;
const from = 5;
const to = 7;
const callback = createSpy('callbackFunction');
it('should correctly create the Move request', () => {
const expectedOperation: MoveOperation = {
op: 'move',
from: `/_links/bitstreams/${from}/href`,
path: `/_links/bitstreams/${to}/href`,
};
service.performBitstreamMoveRequest(bundle, from, to, callback);
expect(bundleDataService.patch).toHaveBeenCalledWith(bundle, [expectedOperation]);
});
it('should correctly make the bundle\'s self link stale', () => {
service.performBitstreamMoveRequest(bundle, from, to, callback);
expect(requestService.setStaleByHrefSubstring).toHaveBeenCalledWith(bundle._links.self.href);
});
it('should attempt to show a message should the request have failed', () => {
spyOn(service, 'displayFailedResponseNotifications');
service.performBitstreamMoveRequest(bundle, from, to, callback);
expect(service.displayFailedResponseNotifications).toHaveBeenCalled();
});
it('should correctly call the provided function once the request has finished', () => {
service.performBitstreamMoveRequest(bundle, from, to, callback);
expect(callback).toHaveBeenCalled();
});
it('should emit at the start and end of the request', fakeAsync(() => {
const emittedActions = [];
service.getPerformingMoveRequest$().subscribe(selected => emittedActions.push(selected));
expect(emittedActions.length).toBe(1);
expect(emittedActions[0]).toBeFalse();
service.performBitstreamMoveRequest(bundle, from, to, callback);
tick();
expect(emittedActions.length).toBe(3);
expect(emittedActions[1]).toBeTrue();
expect(emittedActions[2]).toBeFalse();
}));
});
describe('displayNotifications', () => {
it('should display an error notification if a response failed', () => {
const responses = [
createFailedRemoteDataObject(),
];
const key = 'some.key';
service.displayNotifications(key, responses);
expect(notificationsService.success).not.toHaveBeenCalled();
expect(notificationsService.error).toHaveBeenCalled();
expect(translateService.instant).toHaveBeenCalledWith('some.key.failed.title');
});
it('should display a success notification if a response succeeded', () => {
const responses = [
createSuccessfulRemoteDataObject(undefined),
];
const key = 'some.key';
service.displayNotifications(key, responses);
expect(notificationsService.success).toHaveBeenCalled();
expect(notificationsService.error).not.toHaveBeenCalled();
expect(translateService.instant).toHaveBeenCalledWith('some.key.saved.title');
});
it('should display both notifications if some failed and some succeeded', () => {
const responses = [
createFailedRemoteDataObject(),
createSuccessfulRemoteDataObject(undefined),
];
const key = 'some.key';
service.displayNotifications(key, responses);
expect(notificationsService.success).toHaveBeenCalled();
expect(notificationsService.error).toHaveBeenCalled();
expect(translateService.instant).toHaveBeenCalledWith('some.key.saved.title');
expect(translateService.instant).toHaveBeenCalledWith('some.key.saved.title');
});
});
describe('mapBitstreamsToTableEntries', () => {
it('should correctly map a Bitstream to a BitstreamTableEntry', () => {
const format: BitstreamFormat = new BitstreamFormat();
const bitstream: Bitstream = Object.assign(new Bitstream(), {
uuid: 'testUUID',
format: createSuccessfulRemoteDataObject$(format),
});
spyOn(dsoNameService, 'getName').and.returnValue('Test Name');
spyOn(bitstream, 'firstMetadataValue').and.returnValue('description');
const tableEntry = service.mapBitstreamsToTableEntries([bitstream])[0];
expect(tableEntry.name).toEqual('Test Name');
expect(tableEntry.nameStripped).toEqual('TestName');
expect(tableEntry.bitstream).toBe(bitstream);
expect(tableEntry.id).toEqual('testUUID');
expect(tableEntry.description).toEqual('description');
expect(tableEntry.downloadUrl).toEqual('/bitstreams/testUUID/download');
});
});
describe('nameToHeader', () => {
it('should correctly transform a string to an appropriate header ID', () => {
const stringA = 'Test String';
const stringAResult = 'TestString';
expect(service.nameToHeader(stringA)).toEqual(stringAResult);
const stringB = 'Test String Two';
const stringBResult = 'TestStringTwo';
expect(service.nameToHeader(stringB)).toEqual(stringBResult);
const stringC = 'Test String Three';
const stringCResult = 'TestStringThree';
expect(service.nameToHeader(stringC)).toEqual(stringCResult);
});
});
});

View File

@@ -0,0 +1,79 @@
import { of } from 'rxjs';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes';
export function getItemBitstreamsServiceStub(): ItemBitstreamsServiceStub {
return new ItemBitstreamsServiceStub();
}
export class ItemBitstreamsServiceStub {
getSelectionAction$ = jasmine.createSpy('getSelectedBitstream$').and
.returnValue(of(null));
getSelectedBitstream = jasmine.createSpy('getSelectedBitstream').and
.returnValue(null);
hasSelectedBitstream = jasmine.createSpy('hasSelectedBitstream').and
.returnValue(false);
selectBitstreamEntry = jasmine.createSpy('selectBitstreamEntry');
clearSelection = jasmine.createSpy('clearSelection');
cancelSelection = jasmine.createSpy('cancelSelection');
moveSelectedBitstreamUp = jasmine.createSpy('moveSelectedBitstreamUp');
moveSelectedBitstreamDown = jasmine.createSpy('moveSelectedBitstreamDown');
performBitstreamMoveRequest = jasmine.createSpy('performBitstreamMoveRequest');
getPerformingMoveRequest = jasmine.createSpy('getPerformingMoveRequest').and.returnValue(false);
getPerformingMoveRequest$ = jasmine.createSpy('getPerformingMoveRequest$').and.returnValue(of(false));
getInitialBundlesPaginationOptions = jasmine.createSpy('getInitialBundlesPaginationOptions').and
.returnValue(new PaginationComponentOptions());
getInitialBitstreamsPaginationOptions = jasmine.createSpy('getInitialBitstreamsPaginationOptions').and
.returnValue(new PaginationComponentOptions());
getColumnSizes = jasmine.createSpy('getColumnSizes').and
.returnValue(
new ResponsiveTableSizes([
new ResponsiveColumnSizes(2, 2, 3, 4, 4),
new ResponsiveColumnSizes(2, 3, 3, 3, 3),
new ResponsiveColumnSizes(2, 2, 2, 2, 2),
new ResponsiveColumnSizes(6, 5, 4, 3, 3),
]),
);
displayNotifications = jasmine.createSpy('displayNotifications');
displayFailedResponseNotifications = jasmine.createSpy('displayFailedResponseNotifications');
displayErrorNotification = jasmine.createSpy('displayErrorNotification');
displaySuccessFulResponseNotifications = jasmine.createSpy('displaySuccessFulResponseNotifications');
displaySuccessNotification = jasmine.createSpy('displaySuccessNotification');
removeMarkedBitstreams = jasmine.createSpy('removeMarkedBitstreams').and
.returnValue(createSuccessfulRemoteDataObject$({}));
mapBitstreamsToTableEntries = jasmine.createSpy('mapBitstreamsToTableEntries').and
.returnValue([]);
nameToHeader = jasmine.createSpy('nameToHeader').and.returnValue('header');
stripWhiteSpace = jasmine.createSpy('stripWhiteSpace').and.returnValue('string');
announceSelect = jasmine.createSpy('announceSelect');
announceMove = jasmine.createSpy('announceMove');
announceCancel = jasmine.createSpy('announceCancel');
}

View File

@@ -0,0 +1,568 @@
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { MoveOperation } from 'fast-json-patch';
import {
BehaviorSubject,
Observable,
zip as observableZip,
} from 'rxjs';
import {
map,
switchMap,
take,
tap,
} from 'rxjs/operators';
import { getBitstreamDownloadRoute } from '../../../app-routing-paths';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { BundleDataService } from '../../../core/data/bundle-data.service';
import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model';
import { FieldUpdate } from '../../../core/data/object-updates/field-update.model';
import { FieldUpdates } from '../../../core/data/object-updates/field-updates.model';
import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service';
import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { Bitstream } from '../../../core/shared/bitstream.model';
import { BitstreamFormat } from '../../../core/shared/bitstream-format.model';
import { Bundle } from '../../../core/shared/bundle.model';
import { NoContent } from '../../../core/shared/NoContent.model';
import {
getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload,
} from '../../../core/shared/operators';
import {
hasNoValue,
hasValue,
} from '../../../shared/empty.util';
import { LiveRegionService } from '../../../shared/live-region/live-region.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes';
export const MOVE_KEY = 'item.edit.bitstreams.notifications.move';
/**
* Interface storing all the information necessary to create a row in the bitstream edit table
*/
export interface BitstreamTableEntry {
/**
* The bitstream
*/
bitstream: Bitstream,
/**
* The uuid of the Bitstream
*/
id: string,
/**
* The name of the Bitstream
*/
name: string,
/**
* The name of the Bitstream with all whitespace removed
*/
nameStripped: string,
/**
* The description of the Bitstream
*/
description: string,
/**
* Observable emitting the Format of the Bitstream
*/
format: Observable<BitstreamFormat>,
/**
* The download url of the Bitstream
*/
downloadUrl: string,
}
/**
* Interface storing information necessary to highlight and reorder the selected bitstream entry
*/
export interface SelectedBitstreamTableEntry {
/**
* The selected entry
*/
bitstream: BitstreamTableEntry,
/**
* The bundle the bitstream belongs to
*/
bundle: Bundle,
/**
* The total number of bitstreams in the bundle
*/
bundleSize: number,
/**
* The original position of the bitstream within the bundle.
*/
originalPosition: number,
/**
* The current position of the bitstream within the bundle.
*/
currentPosition: number,
}
/**
* Interface storing data regarding a change in selected bitstream
*/
export interface SelectionAction {
/**
* The different types of actions:
* - Selected: Bitstream was selected
* - Moved: Bitstream was moved
* - Cleared: Selection was cleared, bitstream remains at its current position
* - Cancelled: Selection was cancelled, bitstream returns to its original position
*/
action: 'Selected' | 'Moved' | 'Cleared' | 'Cancelled'
/**
* The table entry to which the selection action applies
*/
selectedEntry: SelectedBitstreamTableEntry,
}
/**
* This service handles the selection and updating of the bitstreams and their order on the
* 'Edit Item' -> 'Bitstreams' page.
*/
@Injectable(
{ providedIn: 'root' },
)
export class ItemBitstreamsService {
/**
* BehaviorSubject which emits every time the selected bitstream changes.
*/
protected selectionAction$: BehaviorSubject<SelectionAction> = new BehaviorSubject(null);
protected isPerformingMoveRequest: BehaviorSubject<boolean> = new BehaviorSubject(false);
constructor(
protected notificationsService: NotificationsService,
protected translateService: TranslateService,
protected objectUpdatesService: ObjectUpdatesService,
protected bitstreamService: BitstreamDataService,
protected bundleService: BundleDataService,
protected dsoNameService: DSONameService,
protected requestService: RequestService,
protected liveRegionService: LiveRegionService,
) {
}
/**
* Returns the observable emitting the selection actions
*/
getSelectionAction$(): Observable<SelectionAction> {
return this.selectionAction$;
}
/**
* Returns the latest selection action
*/
getSelectionAction(): SelectionAction {
const action = this.selectionAction$.value;
if (hasNoValue(action)) {
return null;
}
return Object.assign({}, action);
}
/**
* Returns true if there currently is a selected bitstream
*/
hasSelectedBitstream(): boolean {
const selectionAction = this.getSelectionAction();
if (hasNoValue(selectionAction)) {
return false;
}
const action = selectionAction.action;
return action === 'Selected' || action === 'Moved';
}
/**
* Returns a copy of the currently selected bitstream
*/
getSelectedBitstream(): SelectedBitstreamTableEntry {
if (!this.hasSelectedBitstream()) {
return null;
}
const selectionAction = this.getSelectionAction();
return Object.assign({}, selectionAction.selectedEntry);
}
/**
* Select the provided entry
*/
selectBitstreamEntry(entry: SelectedBitstreamTableEntry) {
if (hasValue(entry) && entry.bitstream !== this.getSelectedBitstream()?.bitstream) {
this.announceSelect(entry.bitstream.name);
this.updateSelectionAction({ action: 'Selected', selectedEntry: entry });
}
}
/**
* Makes the {@link selectionAction$} observable emit the provided {@link SelectedBitstreamTableEntry}.
* @protected
*/
protected updateSelectionAction(action: SelectionAction) {
this.selectionAction$.next(action);
}
/**
* Unselects the selected bitstream. Does nothing if no bitstream is selected.
*/
clearSelection() {
const selected = this.getSelectedBitstream();
if (hasValue(selected)) {
this.updateSelectionAction({ action: 'Cleared', selectedEntry: selected });
this.announceClear(selected.bitstream.name);
if (selected.currentPosition !== selected.originalPosition) {
this.displaySuccessNotification(MOVE_KEY);
}
}
}
/**
* Returns the currently selected bitstream to its original position and unselects the bitstream.
* Does nothing if no bitstream is selected.
*/
cancelSelection() {
const selected = this.getSelectedBitstream();
if (hasNoValue(selected) || this.getPerformingMoveRequest()) {
return;
}
const originalPosition = selected.originalPosition;
const currentPosition = selected.currentPosition;
// If the selected bitstream has not moved, there is no need to return it to its original position
if (currentPosition === originalPosition) {
this.announceClear(selected.bitstream.name);
this.updateSelectionAction({ action: 'Cleared', selectedEntry: selected });
} else {
this.announceCancel(selected.bitstream.name, originalPosition);
this.performBitstreamMoveRequest(selected.bundle, currentPosition, originalPosition);
this.updateSelectionAction({ action: 'Cancelled', selectedEntry: selected });
}
}
/**
* Moves the selected bitstream one position up in the bundle. Does nothing if no bitstream is selected or the
* selected bitstream already is at the beginning of the bundle.
*/
moveSelectedBitstreamUp() {
const selected = this.getSelectedBitstream();
if (hasNoValue(selected) || this.getPerformingMoveRequest()) {
return;
}
const originalPosition = selected.currentPosition;
if (originalPosition > 0) {
const newPosition = originalPosition - 1;
selected.currentPosition = newPosition;
const onRequestCompleted = () => {
this.announceMove(selected.bitstream.name, newPosition);
};
this.performBitstreamMoveRequest(selected.bundle, originalPosition, newPosition, onRequestCompleted);
this.updateSelectionAction({ action: 'Moved', selectedEntry: selected });
}
}
/**
* Moves the selected bitstream one position down in the bundle. Does nothing if no bitstream is selected or the
* selected bitstream already is at the end of the bundle.
*/
moveSelectedBitstreamDown() {
const selected = this.getSelectedBitstream();
if (hasNoValue(selected) || this.getPerformingMoveRequest()) {
return;
}
const originalPosition = selected.currentPosition;
if (originalPosition < selected.bundleSize - 1) {
const newPosition = originalPosition + 1;
selected.currentPosition = newPosition;
const onRequestCompleted = () => {
this.announceMove(selected.bitstream.name, newPosition);
};
this.performBitstreamMoveRequest(selected.bundle, originalPosition, newPosition, onRequestCompleted);
this.updateSelectionAction({ action: 'Moved', selectedEntry: selected });
}
}
/**
* Sends out a Move Patch request to the REST API, display notifications,
* refresh the bundle's cache (so the lists can properly reload)
* @param bundle The bundle to send patch requests to
* @param fromIndex The index to move from
* @param toIndex The index to move to
* @param finish Optional: Function to execute once the response has been received
*/
performBitstreamMoveRequest(bundle: Bundle, fromIndex: number, toIndex: number, finish?: () => void) {
if (this.getPerformingMoveRequest()) {
console.warn('Attempted to perform move request while previous request has not completed yet');
return;
}
const moveOperation: MoveOperation = {
op: 'move',
from: `/_links/bitstreams/${fromIndex}/href`,
path: `/_links/bitstreams/${toIndex}/href`,
};
this.announceLoading();
this.isPerformingMoveRequest.next(true);
this.bundleService.patch(bundle, [moveOperation]).pipe(
getFirstCompletedRemoteData(),
tap((response: RemoteData<Bundle>) => this.displayFailedResponseNotifications(MOVE_KEY, [response])),
switchMap(() => this.requestService.setStaleByHrefSubstring(bundle.self)),
take(1),
).subscribe(() => {
this.isPerformingMoveRequest.next(false);
finish?.();
});
}
/**
* Whether the service currently is processing a 'move' request
*/
getPerformingMoveRequest(): boolean {
return this.isPerformingMoveRequest.value;
}
/**
* Returns an observable which emits when the service starts, or ends, processing a 'move' request
*/
getPerformingMoveRequest$(): Observable<boolean> {
return this.isPerformingMoveRequest;
}
/**
* Returns the pagination options to use when fetching the bundles
*/
getInitialBundlesPaginationOptions(): PaginationComponentOptions {
return Object.assign(new PaginationComponentOptions(), {
id: 'bundles-pagination-options',
currentPage: 1,
pageSize: 9999,
});
}
/**
* Returns the initial pagination options to use when fetching the bitstreams
* @param bundleName The name of the bundle, will be as pagination id.
*/
getInitialBitstreamsPaginationOptions(bundleName: string): PaginationComponentOptions {
return Object.assign(new PaginationComponentOptions(),{
id: bundleName, // This might behave unexpectedly if the item contains two bundles with the same name
currentPage: 1,
pageSize: 10,
});
}
/**
* Returns the {@link ResponsiveTableSizes} for use in the columns of the edit bitstreams table
*/
getColumnSizes(): ResponsiveTableSizes {
return new ResponsiveTableSizes([
// Name column
new ResponsiveColumnSizes(2, 2, 3, 4, 4),
// Description column
new ResponsiveColumnSizes(2, 3, 3, 3, 3),
// Format column
new ResponsiveColumnSizes(2, 2, 2, 2, 2),
// Actions column
new ResponsiveColumnSizes(6, 5, 4, 3, 3),
]);
}
/**
* Display notifications
* - Error notification for each failed response with their message
* - Success notification in case there's at least one successful response
* @param key The i18n key for the notification messages
* @param responses The returned responses to display notifications for
*/
displayNotifications(key: string, responses: RemoteData<any>[]) {
this.displayFailedResponseNotifications(key, responses);
this.displaySuccessFulResponseNotifications(key, responses);
}
/**
* Display an error notification for each failed response with their message
* @param key The i18n key for the notification messages
* @param responses The returned responses to display notifications for
*/
displayFailedResponseNotifications(key: string, responses: RemoteData<any>[]) {
const failedResponses = responses.filter((response: RemoteData<Bundle>) => hasValue(response) && response.hasFailed);
failedResponses.forEach((response: RemoteData<Bundle>) => {
this.displayErrorNotification(key, response.errorMessage);
});
}
/**
* Display an error notification with the provided key and message
* @param key The i18n key for the notification messages
* @param errorMessage The error message to display
*/
displayErrorNotification(key: string, errorMessage: string) {
this.notificationsService.error(this.translateService.instant(`${key}.failed.title`), errorMessage);
}
/**
* Display a success notification in case there's at least one successful response
* @param key The i18n key for the notification messages
* @param responses The returned responses to display notifications for
*/
displaySuccessFulResponseNotifications(key: string, responses: RemoteData<any>[]) {
const successfulResponses = responses.filter((response: RemoteData<Bundle>) => hasValue(response) && response.hasSucceeded);
if (successfulResponses.length > 0) {
this.displaySuccessNotification(key);
}
}
/**
* Display a success notification with the provided key
* @param key The i18n key for the notification messages
*/
displaySuccessNotification(key: string) {
this.notificationsService.success(this.translateService.instant(`${key}.saved.title`), this.translateService.instant(`${key}.saved.content`));
}
/**
* Removes the bitstreams marked for deletion from the Bundles emitted by the provided observable.
* @param bundles$
*/
removeMarkedBitstreams(bundles$: Observable<Bundle[]>): Observable<RemoteData<NoContent>> {
const bundlesOnce$ = bundles$.pipe(take(1));
// Fetch all removed bitstreams from the object update service
const removedBitstreams$ = bundlesOnce$.pipe(
switchMap((bundles: Bundle[]) => observableZip(
...bundles.map((bundle: Bundle) => this.objectUpdatesService.getFieldUpdates(bundle.self, [], true)),
)),
map((fieldUpdates: FieldUpdates[]) => ([] as FieldUpdate[]).concat(
...fieldUpdates.map((updates: FieldUpdates) => Object.values(updates).filter((fieldUpdate: FieldUpdate) => fieldUpdate.changeType === FieldChangeType.REMOVE)),
)),
map((fieldUpdates: FieldUpdate[]) => fieldUpdates.map((fieldUpdate: FieldUpdate) => fieldUpdate.field)),
);
// Send out delete requests for all deleted bitstreams
return removedBitstreams$.pipe(
take(1),
switchMap((removedBitstreams: Bitstream[]) => {
return this.bitstreamService.removeMultiple(removedBitstreams);
}),
);
}
/**
* Creates an array of {@link BitstreamTableEntry}s from an array of {@link Bitstream}s
* @param bitstreams The bitstreams array to map to table entries
*/
mapBitstreamsToTableEntries(bitstreams: Bitstream[]): BitstreamTableEntry[] {
return bitstreams.map((bitstream) => {
const name = this.dsoNameService.getName(bitstream);
return {
bitstream: bitstream,
id: bitstream.uuid,
name: name,
nameStripped: this.nameToHeader(name),
description: bitstream.firstMetadataValue('dc.description'),
format: bitstream.format.pipe(getFirstSucceededRemoteDataPayload()),
downloadUrl: getBitstreamDownloadRoute(bitstream),
};
});
}
/**
* Returns a string appropriate to be used as header ID
* @param name
*/
nameToHeader(name: string): string {
// Whitespace is stripped from the Bitstream names for accessibility reasons.
// To make it clear which headers are relevant for a specific field in the table, the 'headers' attribute is used to
// refer to specific headers. The Bitstream's name is used as header ID for the row containing information regarding
// that bitstream. As the 'headers' attribute contains a space-separated string of header IDs, the Bitstream's header
// ID can not contain spaces itself.
return this.stripWhiteSpace(name);
}
/**
* Returns a string equal to the input string with all whitespace removed.
* @param str
*/
stripWhiteSpace(str: string): string {
// '/\s+/g' matches all occurrences of any amount of whitespace characters
return str.replace(/\s+/g, '');
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name was selected.
* @param bitstreamName The name of the bitstream that was selected.
*/
announceSelect(bitstreamName: string) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.select',
{ bitstream: bitstreamName });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name was moved to the provided
* position.
* @param bitstreamName The name of the bitstream that moved.
* @param toPosition The zero-indexed position that the bitstream moved to.
*/
announceMove(bitstreamName: string, toPosition: number) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.move',
{ bitstream: bitstreamName, toIndex: toPosition + 1 });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name is no longer selected and
* was returned to the provided position.
* @param bitstreamName The name of the bitstream that is no longer selected
* @param toPosition The zero-indexed position the bitstream returned to.
*/
announceCancel(bitstreamName: string, toPosition: number) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.cancel',
{ bitstream: bitstreamName, toIndex: toPosition + 1 });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the bitstream with the provided name is no longer selected.
* @param bitstreamName The name of the bitstream that is no longer selected.
*/
announceClear(bitstreamName: string) {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.clear',
{ bitstream: bitstreamName });
this.liveRegionService.addMessage(message);
}
/**
* Adds a message to the live region mentioning that the
*/
announceLoading() {
const message = this.translateService.instant('item.edit.bitstreams.edit.live.loading');
this.liveRegionService.addMessage(message);
}
}

View File

@@ -1,13 +1,43 @@
<ng-template #bundleView>
<div class="row bundle-row">
<div class="{{bundleNameColumn.buildClasses()}} font-weight-bold row-element d-flex">
<ds-item-edit-bitstream-drag-handle></ds-item-edit-bitstream-drag-handle>
<div class="float-left d-flex align-items-center">
{{'item.edit.bitstreams.bundle.name' | translate:{ name: dsoNameService.getName(bundle) } }}
</div>
</div>
<div class="{{columnSizes.columns[3].buildClasses()}} text-center row-element">
<div class="btn-group bundle-action-buttons">
<ds-pagination *ngIf="(bitstreamsRD$ | async)?.payload as bitstreamsList"
[hideGear]="true"
[hidePagerWhenSinglePage]="true"
[hidePaginationDetail]="true"
[paginationOptions]="paginationOptions"
[collectionSize]="bitstreamsList.totalElements"
[retainScrollPosition]="true"
[ngbTooltip]="'item.edit.bitstreams.bundle.tooltip' | translate" placement="bottom"
[autoClose]="false" triggers="manual" #dragTooltip="ngbTooltip">
<ng-container *ngIf="(updates$ | async) as updates">
<table class="table" [class.mt-n1]="!isFirstTable"
[attr.aria-label]="'item.edit.bitstreams.bundle.table.aria-label' | translate: { bundle: bundleName } ">
<thead [class.visually-hidden]="!isFirstTable">
<tr class="header-row font-weight-bold">
<th id="name" scope="col" class="{{ columnSizes.columns[0].buildClasses() }}">
{{'item.edit.bitstreams.headers.name' | translate}}
</th>
<th id="description" scope="col" class="{{ columnSizes.columns[1].buildClasses() }}">
{{'item.edit.bitstreams.headers.description' | translate}}
</th>
<th id="format" scope="col" class="{{ columnSizes.columns[2].buildClasses() }}">
{{'item.edit.bitstreams.headers.format' | translate}}
</th>
<th id="actions" scope="col" class="{{ columnSizes.columns[3].buildClasses() }} text-center">
{{'item.edit.bitstreams.headers.actions' | translate}}
</th>
</tr>
</thead>
<tbody cdkDropList (cdkDropListDropped)="drop($event)">
<tr class="bundle-row">
<th id="{{ bundleName }}" class="span" colspan="3" scope="colgroup">
{{'item.edit.bitstreams.bundle.name' | translate:{ name: bundleName } }}
</th>
<td class="text-center">
<div class="btn-group">
<button [routerLink]="[itemPageRoute, 'bitstreams', 'new']"
[queryParams]="{bundle: bundle.id}"
[attr.aria-label]="'item.edit.bitstreams.bundle.edit.buttons.upload' | translate"
@@ -15,8 +45,96 @@
title="{{'item.edit.bitstreams.bundle.edit.buttons.upload' | translate}}">
<i class="fas fa-upload fa-fw"></i>
</button>
<div ngbDropdown #paginationControls="ngbDropdown" class="btn-group float-right btn-sm p-0"
placement="bottom-right">
<button class="btn btn-outline-secondary" id="paginationControls" ngbDropdownToggle
[title]="'pagination.options.description' | translate"
[attr.aria-label]="'pagination.options.description' | translate" aria-haspopup="true"
aria-expanded="false">
<i class="fas fa-cog" aria-hidden="true"></i>
</button>
<ul id="paginationControlsDropdownMenu" aria-labelledby="paginationControls" role="menu"
ngbDropdownMenu>
<li role="menuitem">
<span class="dropdown-header" id="pagination-control_results-per-page"
role="heading">{{ 'pagination.results-per-page' | translate}}</span>
<ul aria-labelledby="pagination-control_results-per-page" class="list-unstyled" role="listbox">
<li *ngFor="let size of paginationOptions.pageSizeOptions" role="option"
[attr.aria-selected]="size === (pageSize$ | async)">
<button (click)="doPageSizeChange(size)" class="dropdown-item">
<i [ngClass]="{'invisible': size !== (pageSize$ | async) }" class="fas fa-check"
aria-hidden="true"></i> {{size}}
</button>
</li>
</ul>
</li>
</ul>
</div>
</div>
</td>
</tr>
<ng-container *ngFor="let entry of (tableEntries$ | async)">
<tr *ngIf="updates[entry.id] as update" [ngClass]="getRowClass(update, entry)" class="bitstream-row" cdkDrag
(cdkDragStarted)="dragStart()" (cdkDragEnded)="dragEnd()">
<th class="bitstream-name row-element {{ columnSizes.columns[0].buildClasses() }}"
scope="row" id="{{ entry.nameStripped }}" headers="{{ bundleName }} name">
<div class="drag-handle text-muted float-left p-1 mr-2" tabindex="0" cdkDragHandle
(keydown.enter)="select($event, entry)" (keydown.space)="select($event, entry)" (click)="select($event, entry)">
<i class="fas fa-grip-vertical fa-fw"
[title]="'item.edit.bitstreams.edit.buttons.drag' | translate"></i>
</div>
<ds-paginated-drag-and-drop-bitstream-list [bundle]="bundle" [columnSizes]="columnSizes" (dropObject)="dropObject.emit($event)"></ds-paginated-drag-and-drop-bitstream-list>
{{ entry.name }}
</th>
<td class="row-element {{ columnSizes.columns[1].buildClasses() }}"
headers="{{ entry.nameStripped }} {{ bundleName }} description">
{{ entry.description }}
</td>
<td class="row-element {{ columnSizes.columns[2].buildClasses() }}"
headers="{{ entry.nameStripped }} {{ bundleName }} format">
{{ (entry.format | async)?.shortDescription }}
</td>
<td class="row-element {{ columnSizes.columns[3].buildClasses() }}"
headers="{{ entry.nameStripped }} {{ bundleName }} actions">
<div class="text-center w-100">
<div class="btn-group relationship-action-buttons">
<a [href]="entry.downloadUrl"
[attr.aria-label]="'item.edit.bitstreams.edit.buttons.download' | translate"
class="btn btn-outline-primary btn-sm"
title="{{'item.edit.bitstreams.edit.buttons.download' | translate}}"
[attr.data-test]="'download-button' | dsBrowserOnly">
<i class="fas fa-download fa-fw"></i>
</a>
<button [routerLink]="['/bitstreams/', entry.id, 'edit']" class="btn btn-outline-primary btn-sm"
[attr.aria-label]="'item.edit.bitstreams.edit.buttons.edit' | translate"
title="{{'item.edit.bitstreams.edit.buttons.edit' | translate}}">
<i class="fas fa-edit fa-fw"></i>
</button>
<button [disabled]="!canRemove(update)" (click)="remove(entry.bitstream)"
[attr.aria-label]=" 'item. edit bitstreams.edit.buttons.remove' | translate"
class="btn btn-outline-danger btn-sm"
title="{{'item.edit.bitstreams.edit.buttons.remove' | translate}}">
<i class="fas fa-trash-alt fa-fw"></i>
</button>
<button [disabled]="!canUndo(update)" (click)="undo(entry.bitstream)"
[attr.aria-label]="'item.edit.bitstreams.edit.buttons.undo' | translate"
class="btn btn-outline-warning btn-sm"
title="{{'item.edit.bitstreams.edit.buttons.undo' | translate}}">
<i class="fas fa-undo-alt fa-fw"></i>
</button>
</div>
</div>
</td>
</tr>
</ng-container>
</tbody>
</table>
</ng-container>
</ds-pagination>
</ng-template>

View File

@@ -0,0 +1,24 @@
.header-row {
color: var(--bs-table-dark-color);
background-color: var(--bs-table-dark-bg);
border-color: var(--bs-table-dark-bg);
}
.bundle-row {
color: var(--bs-table-head-color);
background-color: var(--bs-table-head-bg);
border-color: var(--bs-table-border-color);
}
.row-element {
padding: 0.75em;
border-bottom: var(--bs-table-border-width) solid var(--bs-table-border-color);
}
.bitstream-name {
font-weight: normal;
}
.table {
margin-bottom: 0;
}

View File

@@ -1,3 +1,4 @@
import { CdkDragDrop } from '@angular/cdk/drag-drop';
import {
NO_ERRORS_SCHEMA,
ViewContainerRef,
@@ -8,11 +9,35 @@ import {
waitForAsync,
} from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import {
of as observableOf,
of,
Subject,
} from 'rxjs';
import { BundleDataService } from '../../../../core/data/bundle-data.service';
import { FieldChangeType } from '../../../../core/data/object-updates/field-change-type.model';
import { FieldUpdate } from '../../../../core/data/object-updates/field-update.model';
import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service';
import { RequestService } from '../../../../core/data/request.service';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { Bundle } from '../../../../core/shared/bundle.model';
import { Item } from '../../../../core/shared/item.model';
import { getMockRequestService } from '../../../../shared/mocks/request.service.mock';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub';
import { createPaginatedList } from '../../../../shared/testing/utils.test';
import {
BitstreamTableEntry,
ItemBitstreamsService,
SelectedBitstreamTableEntry,
} from '../item-bitstreams.service';
import {
getItemBitstreamsServiceStub,
ItemBitstreamsServiceStub,
} from '../item-bitstreams.service.stub';
import { ItemEditBitstreamBundleComponent } from './item-edit-bitstream-bundle.component';
describe('ItemEditBitstreamBundleComponent', () => {
@@ -39,9 +64,32 @@ describe('ItemEditBitstreamBundleComponent', () => {
},
});
const restEndpoint = 'fake-rest-endpoint';
const bundleService = jasmine.createSpyObj('bundleService', {
getBitstreamsEndpoint: observableOf(restEndpoint),
getBitstreams: createSuccessfulRemoteDataObject$(createPaginatedList([])),
});
let objectUpdatesService: any;
let itemBitstreamsService: ItemBitstreamsServiceStub;
beforeEach(waitForAsync(() => {
objectUpdatesService = jasmine.createSpyObj('objectUpdatesService', {
initialize: undefined,
getFieldUpdatesExclusive: of(null),
});
itemBitstreamsService = getItemBitstreamsServiceStub();
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), ItemEditBitstreamBundleComponent],
providers: [
{ provide: BundleDataService, useValue: bundleService },
{ provide: ObjectUpdatesService, useValue: objectUpdatesService },
{ provide: PaginationService, useValue: new PaginationServiceStub() },
{ provide: RequestService, useValue: getMockRequestService() },
{ provide: ItemBitstreamsService, useValue: itemBitstreamsService },
],
schemas: [
NO_ERRORS_SCHEMA,
],
@@ -62,4 +110,251 @@ describe('ItemEditBitstreamBundleComponent', () => {
it('should create an embedded view of the component', () => {
expect(viewContainerRef.createEmbeddedView).toHaveBeenCalled();
});
describe('on selected entry change', () => {
let paginationComponent: any;
let testSubject: Subject<SelectedBitstreamTableEntry> = new Subject();
beforeEach(() => {
paginationComponent = jasmine.createSpyObj('paginationComponent', {
doPageChange: undefined,
});
comp.paginationComponent = paginationComponent;
spyOn<any>(comp, 'getCurrentPageSize').and.returnValue(2);
});
it('should move to the page the selected entry is on if were not on that page', () => {
const entry: SelectedBitstreamTableEntry = {
bitstream: null,
bundle: bundle,
bundleSize: 5,
originalPosition: 1,
currentPosition: 2,
};
comp.handleSelectionAction({ action: 'Moved', selectedEntry: entry });
expect(paginationComponent.doPageChange).toHaveBeenCalledWith(2);
});
it('should not change page when we are already on the correct page', () => {
const entry: SelectedBitstreamTableEntry = {
bitstream: null,
bundle: bundle,
bundleSize: 5,
originalPosition: 0,
currentPosition: 1,
};
comp.handleSelectionAction({ action: 'Moved', selectedEntry: entry });
expect(paginationComponent.doPageChange).not.toHaveBeenCalled();
});
it('should change to the original page when cancelling', () => {
const entry: SelectedBitstreamTableEntry = {
bitstream: null,
bundle: bundle,
bundleSize: 5,
originalPosition: 3,
currentPosition: 0,
};
comp.handleSelectionAction({ action: 'Cancelled', selectedEntry: entry });
expect(paginationComponent.doPageChange).toHaveBeenCalledWith(2);
});
it('should not change page when we are already on the correct page when cancelling', () => {
const entry: SelectedBitstreamTableEntry = {
bitstream: null,
bundle: bundle,
bundleSize: 5,
originalPosition: 0,
currentPosition: 3,
};
comp.handleSelectionAction({ action: 'Cancelled', selectedEntry: entry });
expect(paginationComponent.doPageChange).not.toHaveBeenCalled();
});
});
describe('getRowClass', () => {
it('should return \'table-info\' when the bitstream is the selected bitstream', () => {
itemBitstreamsService.getSelectedBitstream.and.returnValue({
bitstream: { id: 'bitstream-id' },
});
const bitstreamEntry = {
id: 'bitstream-id',
} as BitstreamTableEntry;
expect(comp.getRowClass(undefined, bitstreamEntry)).toEqual('table-info');
});
it('should return \'table-warning\' when the update is of type \'UPDATE\'', () => {
const update = {
changeType: FieldChangeType.UPDATE,
} as FieldUpdate;
expect(comp.getRowClass(update, undefined)).toEqual('table-warning');
});
it('should return \'table-success\' when the update is of type \'ADD\'', () => {
const update = {
changeType: FieldChangeType.ADD,
} as FieldUpdate;
expect(comp.getRowClass(update, undefined)).toEqual('table-success');
});
it('should return \'table-danger\' when the update is of type \'REMOVE\'', () => {
const update = {
changeType: FieldChangeType.REMOVE,
} as FieldUpdate;
expect(comp.getRowClass(update, undefined)).toEqual('table-danger');
});
it('should return \'bg-white\' in any other case', () => {
const update = {
changeType: undefined,
} as FieldUpdate;
expect(comp.getRowClass(update, undefined)).toEqual('bg-white');
});
});
describe('drag', () => {
let dragTooltip;
let paginationComponent;
beforeEach(() => {
dragTooltip = jasmine.createSpyObj('dragTooltip', {
open: undefined,
close: undefined,
});
comp.dragTooltip = dragTooltip;
});
describe('Start', () => {
it('should open the tooltip when there are multiple pages', () => {
paginationComponent = jasmine.createSpyObj('paginationComponent', {
doPageChange: undefined,
}, {
shouldShowBottomPager: of(true),
});
comp.paginationComponent = paginationComponent;
comp.dragStart();
expect(dragTooltip.open).toHaveBeenCalled();
});
it('should not open the tooltip when there is only a single page', () => {
paginationComponent = jasmine.createSpyObj('paginationComponent', {
doPageChange: undefined,
}, {
shouldShowBottomPager: of(false),
});
comp.paginationComponent = paginationComponent;
comp.dragStart();
expect(dragTooltip.open).not.toHaveBeenCalled();
});
});
describe('end', () => {
it('should always close the tooltip', () => {
paginationComponent = jasmine.createSpyObj('paginationComponent', {
doPageChange: undefined,
}, {
shouldShowBottomPager: of(false),
});
comp.paginationComponent = paginationComponent;
comp.dragEnd();
expect(dragTooltip.close).toHaveBeenCalled();
});
});
});
describe('drop', () => {
it('should correctly move the bitstream on drop', () => {
const event = {
previousIndex: 1,
currentIndex: 8,
dropPoint: { x: 100, y: 200 },
} as CdkDragDrop<any>;
comp.drop(event);
expect(itemBitstreamsService.performBitstreamMoveRequest).toHaveBeenCalledWith(jasmine.any(Bundle), 1, 8, jasmine.any(Function));
});
it('should not move the bitstream if dropped in the same place', () => {
const event = {
previousIndex: 1,
currentIndex: 1,
dropPoint: { x: 100, y: 200 },
} as CdkDragDrop<any>;
comp.drop(event);
expect(itemBitstreamsService.performBitstreamMoveRequest).not.toHaveBeenCalled();
});
it('should move to a different page if dropped on a page number', () => {
spyOn(document, 'elementFromPoint').and.returnValue({
textContent: '2',
classList: { contains: (token: string) => true },
} as Element);
const event = {
previousIndex: 1,
currentIndex: 1,
dropPoint: { x: 100, y: 200 },
} as CdkDragDrop<any>;
comp.drop(event);
expect(itemBitstreamsService.performBitstreamMoveRequest).toHaveBeenCalledWith(jasmine.any(Bundle), 1, 20, jasmine.any(Function));
});
});
describe('select', () => {
it('should select the bitstream', () => {
const event = new KeyboardEvent('keydown');
spyOnProperty(event, 'repeat', 'get').and.returnValue(false);
const entry = { } as BitstreamTableEntry;
comp.tableEntries$.next([entry]);
comp.select(event, entry);
expect(itemBitstreamsService.selectBitstreamEntry).toHaveBeenCalledWith(jasmine.objectContaining({ bitstream: entry }));
});
it('should cancel the selection if the bitstream already is selected', () => {
const event = new KeyboardEvent('keydown');
spyOnProperty(event, 'repeat', 'get').and.returnValue(false);
const entry = { } as BitstreamTableEntry;
comp.tableEntries$.next([entry]);
itemBitstreamsService.getSelectedBitstream.and.returnValue({ bitstream: entry });
comp.select(event, entry);
expect(itemBitstreamsService.selectBitstreamEntry).not.toHaveBeenCalled();
expect(itemBitstreamsService.cancelSelection).toHaveBeenCalled();
});
it('should not do anything if the user is holding down the select key', () => {
const event = new KeyboardEvent('keydown');
spyOnProperty(event, 'repeat', 'get').and.returnValue(true);
const entry = { } as BitstreamTableEntry;
comp.tableEntries$.next([entry]);
itemBitstreamsService.getSelectedBitstream.and.returnValue({ bitstream: entry });
comp.select(event, entry);
expect(itemBitstreamsService.selectBitstreamEntry).not.toHaveBeenCalled();
expect(itemBitstreamsService.cancelSelection).not.toHaveBeenCalled();
});
});
});

View File

@@ -1,34 +1,92 @@
import {
CdkDrag,
CdkDragDrop,
CdkDropList,
} from '@angular/cdk/drag-drop';
import {
AsyncPipe,
CommonModule,
} from '@angular/common';
import {
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import {
NgbDropdownModule,
NgbTooltipModule,
} from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import {
BehaviorSubject,
Observable,
shareReplay,
Subscription,
switchMap,
} from 'rxjs';
import {
filter,
map,
take,
tap,
} from 'rxjs/operators';
import { PaginatedList } from 'src/app/core/data/paginated-list.model';
import { RemoteData } from 'src/app/core/data/remote-data';
import { Bitstream } from 'src/app/core/shared/bitstream.model';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { BundleDataService } from '../../../../core/data/bundle-data.service';
import { FieldChangeType } from '../../../../core/data/object-updates/field-change-type.model';
import { FieldUpdate } from '../../../../core/data/object-updates/field-update.model';
import { FieldUpdates } from '../../../../core/data/object-updates/field-updates.model';
import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service';
import { RequestService } from '../../../../core/data/request.service';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { Bundle } from '../../../../core/shared/bundle.model';
import { Item } from '../../../../core/shared/item.model';
import {
getAllSucceededRemoteData,
paginatedListToArray,
} from '../../../../core/shared/operators';
import {
hasNoValue,
hasValue,
} from '../../../../shared/empty.util';
import { PaginationComponent } from '../../../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { PaginatedSearchOptions } from '../../../../shared/search/models/paginated-search-options.model';
import { BrowserOnlyPipe } from '../../../../shared/utils/browser-only.pipe';
import { followLink } from '../../../../shared/utils/follow-link-config.model';
import { getItemPageRoute } from '../../../item-page-routing-paths';
import { ItemEditBitstreamDragHandleComponent } from '../item-edit-bitstream-drag-handle/item-edit-bitstream-drag-handle.component';
import { PaginatedDragAndDropBitstreamListComponent } from './paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component';
import {
BitstreamTableEntry,
ItemBitstreamsService,
MOVE_KEY,
SelectedBitstreamTableEntry,
SelectionAction,
} from '../item-bitstreams.service';
@Component({
selector: 'ds-item-edit-bitstream-bundle',
styleUrls: ['../item-bitstreams.component.scss'],
styleUrls: ['../item-bitstreams.component.scss', './item-edit-bitstream-bundle.component.scss'],
templateUrl: './item-edit-bitstream-bundle.component.html',
imports: [
PaginatedDragAndDropBitstreamListComponent,
CommonModule,
TranslateModule,
RouterLink,
ItemEditBitstreamDragHandleComponent,
AsyncPipe,
PaginationComponent,
NgbTooltipModule,
CdkDropList,
NgbDropdownModule,
CdkDrag,
BrowserOnlyPipe,
],
standalone: true,
})
@@ -38,12 +96,23 @@ import { PaginatedDragAndDropBitstreamListComponent } from './paginated-drag-and
* (which means it'll be added to the parents html without a wrapping ds-item-edit-bitstream-bundle element)
*/
export class ItemEditBitstreamBundleComponent implements OnInit, OnDestroy {
protected readonly FieldChangeType = FieldChangeType;
/**
* The view on the bundle information and bitstreams
*/
@ViewChild('bundleView', { static: true }) bundleView;
/**
* The view on the pagination component
*/
@ViewChild(PaginationComponent) paginationComponent: PaginationComponent;
/**
* The view on the drag tooltip
*/
@ViewChild('dragTooltip') dragTooltip;
/**
* The bundle to display bitstreams for
*/
@@ -60,11 +129,9 @@ export class ItemEditBitstreamBundleComponent implements OnInit, OnDestroy {
@Input() columnSizes: ResponsiveTableSizes;
/**
* Send an event when the user drops an object on the pagination
* The event contains details about the index the object came from and is dropped to (across the entirety of the list,
* not just within a single page)
* Whether this is the first in a series of bundle tables
*/
@Output() dropObject: EventEmitter<any> = new EventEmitter<any>();
@Input() isFirstTable = false;
/**
* The bootstrap sizes used for the Bundle Name column
@@ -77,9 +144,65 @@ export class ItemEditBitstreamBundleComponent implements OnInit, OnDestroy {
*/
itemPageRoute: string;
/**
* The name of the bundle
*/
bundleName: string;
/**
* The number of bitstreams in the bundle
*/
bundleSize: number;
/**
* The bitstreams to show in the table
*/
bitstreamsRD$: Observable<RemoteData<PaginatedList<Bitstream>>>;
/**
* The data to show in the table
*/
tableEntries$: BehaviorSubject<BitstreamTableEntry[]> = new BehaviorSubject([]);
/**
* The initial page options to use for fetching the bitstreams
*/
paginationOptions: PaginationComponentOptions;
/**
* The current page options
*/
currentPaginationOptions$: BehaviorSubject<PaginationComponentOptions>;
/**
* The currently selected page size
*/
pageSize$: BehaviorSubject<number>;
/**
* The self url of the bundle, also used when retrieving fieldUpdates
*/
bundleUrl: string;
/**
* The updates to the current bitstreams
*/
updates$: BehaviorSubject<FieldUpdates> = new BehaviorSubject(null);
/**
* Array containing all subscriptions created by this component
*/
subscriptions: Subscription[] = [];
constructor(
protected viewContainerRef: ViewContainerRef,
public dsoNameService: DSONameService,
protected bundleService: BundleDataService,
protected objectUpdatesService: ObjectUpdatesService,
protected paginationService: PaginationService,
protected requestService: RequestService,
protected itemBitstreamsService: ItemBitstreamsService,
) {
}
@@ -87,10 +210,384 @@ export class ItemEditBitstreamBundleComponent implements OnInit, OnDestroy {
this.bundleNameColumn = this.columnSizes.combineColumns(0, 2);
this.viewContainerRef.createEmbeddedView(this.bundleView);
this.itemPageRoute = getItemPageRoute(this.item);
this.bundleName = this.dsoNameService.getName(this.bundle);
this.bundleUrl = this.bundle.self;
this.initializePagination();
this.initializeBitstreams();
this.initializeSelectionActions();
}
ngOnDestroy(): void {
ngOnDestroy() {
this.viewContainerRef.clear();
this.subscriptions.forEach(sub => sub?.unsubscribe());
}
protected initializePagination() {
this.paginationOptions = this.itemBitstreamsService.getInitialBitstreamsPaginationOptions(this.bundleName);
this.currentPaginationOptions$ = new BehaviorSubject(this.paginationOptions);
this.pageSize$ = new BehaviorSubject(this.paginationOptions.pageSize);
this.subscriptions.push(
this.paginationService.getCurrentPagination(this.paginationOptions.id, this.paginationOptions)
.subscribe((pagination) => {
this.currentPaginationOptions$.next(pagination);
this.pageSize$.next(pagination.pageSize);
}),
);
}
protected initializeBitstreams() {
this.bitstreamsRD$ = this.currentPaginationOptions$.pipe(
switchMap((page: PaginationComponentOptions) => {
const paginatedOptions = new PaginatedSearchOptions({ pagination: Object.assign({}, page) });
return this.bundleService.getBitstreamsEndpoint(this.bundle.id, paginatedOptions).pipe(
switchMap((href) => this.requestService.hasByHref$(href)),
switchMap(() => this.bundleService.getBitstreams(
this.bundle.id,
paginatedOptions,
followLink('format'),
)),
);
}),
getAllSucceededRemoteData(),
shareReplay({ bufferSize: 1, refCount: true }),
);
this.subscriptions.push(
this.bitstreamsRD$.pipe(
take(1),
tap(bitstreamsRD => this.bundleSize = bitstreamsRD.payload.totalElements),
paginatedListToArray(),
).subscribe((bitstreams) => {
this.objectUpdatesService.initialize(this.bundleUrl, bitstreams, new Date());
}),
this.bitstreamsRD$.pipe(
paginatedListToArray(),
switchMap((bitstreams) => this.objectUpdatesService.getFieldUpdatesExclusive(this.bundleUrl, bitstreams)),
).subscribe((updates) => this.updates$.next(updates)),
this.bitstreamsRD$.pipe(
paginatedListToArray(),
map((bitstreams) => this.itemBitstreamsService.mapBitstreamsToTableEntries(bitstreams)),
).subscribe((tableEntries) => this.tableEntries$.next(tableEntries)),
);
}
protected initializeSelectionActions() {
this.subscriptions.push(
this.itemBitstreamsService.getSelectionAction$().subscribe(
selectionAction => this.handleSelectionAction(selectionAction)),
);
}
/**
* Handles a change in selected bitstream by changing the pagination if the change happened on a different page
* @param selectionAction
*/
handleSelectionAction(selectionAction: SelectionAction) {
if (hasNoValue(selectionAction) || selectionAction.selectedEntry.bundle !== this.bundle) {
return;
}
if (selectionAction.action === 'Moved') {
// If the currently selected bitstream belongs to this bundle, it has possibly moved to a different page.
// In that case we want to change the pagination to the new page.
this.redirectToCurrentPage(selectionAction.selectedEntry);
}
if (selectionAction.action === 'Cancelled') {
// If the selection is cancelled (and returned to its original position), it is possible the previously selected
// bitstream is returned to a different page. In that case we want to change the pagination to the place where
// the bitstream was returned to.
this.redirectToOriginalPage(selectionAction.selectedEntry);
}
if (selectionAction.action === 'Cleared') {
// If the selection is cleared, it is possible the previously selected bitstream is on a different page. In that
// case we want to change the pagination to the place where the bitstream is.
this.redirectToCurrentPage(selectionAction.selectedEntry);
}
}
/**
* Redirect the user to the current page of the provided bitstream if it is on a different page.
* @param bitstreamEntry The entry that the current position will be taken from to determine the page to move to
* @protected
*/
protected redirectToCurrentPage(bitstreamEntry: SelectedBitstreamTableEntry) {
const currentPage = this.getCurrentPage();
const selectedEntryPage = this.bundleIndexToPage(bitstreamEntry.currentPosition);
if (currentPage !== selectedEntryPage) {
this.changeToPage(selectedEntryPage);
}
}
/**
* Redirect the user to the original page of the provided bitstream if it is on a different page.
* @param bitstreamEntry The entry that the original position will be taken from to determine the page to move to
* @protected
*/
protected redirectToOriginalPage(bitstreamEntry: SelectedBitstreamTableEntry) {
const currentPage = this.getCurrentPage();
const originPage = this.bundleIndexToPage(bitstreamEntry.originalPosition);
if (currentPage !== originPage) {
this.changeToPage(originPage);
}
}
/**
* Check if a user should be allowed to remove this field
*/
canRemove(fieldUpdate: FieldUpdate): boolean {
return fieldUpdate.changeType !== FieldChangeType.REMOVE;
}
/**
* Check if a user should be allowed to cancel the update to this field
*/
canUndo(fieldUpdate: FieldUpdate): boolean {
return fieldUpdate.changeType >= FieldChangeType.UPDATE;
}
/**
* Sends a new remove update for this field to the object updates service
*/
remove(bitstream: Bitstream): void {
this.objectUpdatesService.saveRemoveFieldUpdate(this.bundleUrl, bitstream);
}
/**
* Cancels the current update for this field in the object updates service
*/
undo(bitstream: Bitstream): void {
this.objectUpdatesService.removeSingleFieldUpdate(this.bundleUrl, bitstream.uuid);
}
/**
* Returns the css class for a table row depending on the state of the table entry.
* @param update
* @param bitstream
*/
getRowClass(update: FieldUpdate, bitstream: BitstreamTableEntry): string {
const selected = this.itemBitstreamsService.getSelectedBitstream();
if (hasValue(selected) && bitstream.id === selected.bitstream.id) {
return 'table-info';
}
switch (update.changeType) {
case FieldChangeType.UPDATE:
return 'table-warning';
case FieldChangeType.ADD:
return 'table-success';
case FieldChangeType.REMOVE:
return 'table-danger';
default:
return 'bg-white';
}
}
/**
* Changes the page size to the provided page size.
* @param pageSize
*/
public doPageSizeChange(pageSize: number) {
this.paginationComponent.doPageSizeChange(pageSize);
}
/**
* Handles start of dragging by opening the tooltip mentioning that it is possible to drag a bitstream to a different
* page by dropping it on the page number, only if there are multiple pages.
*/
dragStart() {
// Only open the drag tooltip when there are multiple pages
this.paginationComponent.shouldShowBottomPager.pipe(
take(1),
filter((hasMultiplePages) => hasMultiplePages),
).subscribe(() => {
this.dragTooltip.open();
});
}
/**
* Handles end of dragging by closing the tooltip.
*/
dragEnd() {
this.dragTooltip.close();
}
/**
* Handles dropping by calculation the target position, and changing the page if the bitstream was dropped on a
* different page.
* @param event
*/
drop(event: CdkDragDrop<any>) {
const dragIndex = event.previousIndex;
let dropIndex = event.currentIndex;
const dragPage = this.getCurrentPage();
let dropPage = this.getCurrentPage();
// Check if the user is hovering over any of the pagination's pages at the time of dropping the object
const droppedOnElement = document.elementFromPoint(event.dropPoint.x, event.dropPoint.y);
if (hasValue(droppedOnElement) && hasValue(droppedOnElement.textContent) && droppedOnElement.classList.contains('page-link')) {
// The user is hovering over a page, fetch the page's number from the element
let droppedPage = Number(droppedOnElement.textContent);
if (hasValue(droppedPage) && !Number.isNaN(droppedPage)) {
droppedPage -= 1;
if (droppedPage !== dragPage) {
dropPage = droppedPage;
if (dropPage > dragPage) {
// When moving to later page, place bitstream at the top
dropIndex = 0;
} else {
// When moving to earlier page, place bitstream at the bottom
dropIndex = this.getCurrentPageSize() - 1;
}
}
}
}
const fromIndex = this.pageIndexToBundleIndex(dragIndex, dragPage);
const toIndex = this.pageIndexToBundleIndex(dropIndex, dropPage);
if (fromIndex === toIndex) {
return;
}
const selectedBitstream = this.tableEntries$.value[dragIndex];
const finish = () => {
this.itemBitstreamsService.announceMove(selectedBitstream.name, toIndex);
if (dropPage !== this.getCurrentPage()) {
this.changeToPage(dropPage);
}
this.itemBitstreamsService.displaySuccessNotification(MOVE_KEY);
};
this.itemBitstreamsService.performBitstreamMoveRequest(this.bundle, fromIndex, toIndex, finish);
}
/**
* Handles a select action for the provided bitstream entry.
* If the selected bitstream is currently selected, the selection is cleared.
* If no, or a different bitstream, is selected, the provided bitstream becomes the selected bitstream.
* @param event The event that triggered the select action
* @param bitstream The bitstream that is the target of the select action
*/
select(event: UIEvent, bitstream: BitstreamTableEntry) {
event.preventDefault();
if (event instanceof KeyboardEvent && event.repeat) {
// Don't handle hold events, otherwise it would change rapidly between being selected and unselected
return;
}
const selectedBitstream = this.itemBitstreamsService.getSelectedBitstream();
if (hasValue(selectedBitstream) && selectedBitstream.bitstream === bitstream) {
this.itemBitstreamsService.cancelSelection();
} else {
const selectionObject = this.createBitstreamSelectionObject(bitstream);
if (hasNoValue(selectionObject)) {
console.warn('Failed to create selection object');
return;
}
this.itemBitstreamsService.selectBitstreamEntry(selectionObject);
}
}
/**
* Creates a {@link SelectedBitstreamTableEntry} from the provided {@link BitstreamTableEntry} so it can be given
* to the {@link ItemBitstreamsService} to select the table entry.
* @param bitstream The table entry to create the selection object from.
* @protected
*/
protected createBitstreamSelectionObject(bitstream: BitstreamTableEntry): SelectedBitstreamTableEntry {
const pageIndex = this.findBitstreamPageIndex(bitstream);
if (pageIndex === -1) {
return null;
}
const position = this.pageIndexToBundleIndex(pageIndex, this.getCurrentPage());
return {
bitstream: bitstream,
bundle: this.bundle,
bundleSize: this.bundleSize,
currentPosition: position,
originalPosition: position,
};
}
/**
* Returns the index of the provided {@link BitstreamTableEntry} relative to the current page
* If the current page size is 10, it will return a value from 0 to 9 (inclusive)
* Returns -1 if the provided bitstream could not be found
* @protected
*/
protected findBitstreamPageIndex(bitstream: BitstreamTableEntry): number {
const entries = this.tableEntries$.value;
return entries.findIndex(entry => entry === bitstream);
}
/**
* Returns the current zero-indexed page
* @protected
*/
protected getCurrentPage(): number {
// The pagination component uses one-based numbering while zero-based numbering is more convenient for calculations
return this.currentPaginationOptions$.value.currentPage - 1;
}
/**
* Returns the current page size
* @protected
*/
protected getCurrentPageSize(): number {
return this.currentPaginationOptions$.value.pageSize;
}
/**
* Converts an index relative to the page to an index relative to the bundle
* @param index The index relative to the page
* @param page The zero-indexed page number
* @protected
*/
protected pageIndexToBundleIndex(index: number, page: number) {
return page * this.getCurrentPageSize() + index;
}
/**
* Calculates the zero-indexed page number from the index relative to the bundle
* @param index The index relative to the bundle
* @protected
*/
protected bundleIndexToPage(index: number) {
return Math.floor(index / this.getCurrentPageSize());
}
/**
* Change the pagination for this bundle to the provided zero-indexed page
* @param page The zero-indexed page to change to
* @protected
*/
protected changeToPage(page: number) {
// Increments page by one because zero-indexing is way easier for calculations but the pagination component
// uses one-indexing.
this.paginationComponent.doPageChange(page + 1);
}
}

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