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

# Conflicts:
#	src/app/profile-page/profile-page.component.html
#	src/app/shared/notifications/notifications-board/notifications-board.component.spec.ts
#	src/app/shared/notifications/notifications-board/notifications-board.component.ts
This commit is contained in:
Andreas Awouters
2025-01-22 15:56:10 +01:00
172 changed files with 5143 additions and 2847 deletions

View File

@@ -7,7 +7,8 @@ name: Build
on: [push, pull_request] on: [push, pull_request]
permissions: permissions:
contents: read # to fetch code (actions/checkout) contents: read # to fetch code (actions/checkout)
packages: read # to fetch private images from GitHub Container Registry (GHCR)
jobs: jobs:
tests: tests:
@@ -35,6 +36,9 @@ jobs:
NODE_OPTIONS: '--max-old-space-size=4096' NODE_OPTIONS: '--max-old-space-size=4096'
# Project name to use when running "docker compose" prior to e2e tests # Project name to use when running "docker compose" prior to e2e tests
COMPOSE_PROJECT_NAME: 'ci' 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: strategy:
# Create a matrix of Node versions to test against (in parallel) # Create a matrix of Node versions to test against (in parallel)
matrix: matrix:
@@ -108,6 +112,14 @@ jobs:
path: 'coverage/dspace-angular/lcov.info' path: 'coverage/dspace-angular/lcov.info'
retention-days: 14 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 # Using "docker compose" start backend using CI configuration
# and load assetstore from a cached copy # and load assetstore from a cached copy
- name: Start DSpace REST Backend via Docker (for e2e tests) - name: Start DSpace REST Backend via Docker (for e2e tests)

View File

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

View File

@@ -1,7 +1,7 @@
# This image will be published as dspace/dspace-angular # This image will be published as dspace/dspace-angular
# See https://github.com/DSpace/dspace-angular/tree/main/docker for usage details # 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 # Ensure Python and other build tools are available
# These are needed to install some node modules, especially on linux/arm64 # 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. # Listen / accept connections from all IP addresses.
# NOTE: At this time it is only possible to run Docker container in Production mode # 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 # 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 CMD yarn serve --host 0.0.0.0

View File

@@ -4,7 +4,7 @@
# Test build: # Test build:
# docker build -f Dockerfile.dist -t dspace/dspace-angular:dspace-7_x-dist . # docker build -f Dockerfile.dist -t dspace/dspace-angular:dspace-7_x-dist .
FROM node:18-alpine AS build FROM docker.io/node:18-alpine AS build
# Ensure Python and other build tools are available # Ensure Python and other build tools are available
# These are needed to install some node modules, especially on linux/arm64 # 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 WORKDIR /app
USER node USER node
ENV NODE_ENV production ENV NODE_ENV=production
EXPOSE 4000 EXPOSE 4000
CMD pm2-runtime start dspace-ui.json --json CMD pm2-runtime start dspace-ui.json --json

View File

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

View File

@@ -12,6 +12,7 @@ describe('Admin Add New Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-new-title').click();
cy.get('a[data-test="menu.section.new_community"]').click(); cy.get('a[data-test="menu.section.new_community"]').click();
@@ -25,6 +26,7 @@ describe('Admin Add New Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-new-title').click();
cy.get('a[data-test="menu.section.new_collection"]').click(); cy.get('a[data-test="menu.section.new_collection"]').click();
@@ -38,6 +40,7 @@ describe('Admin Add New Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-new-title').click();
cy.get('a[data-test="menu.section.new_item"]').click(); cy.get('a[data-test="menu.section.new_item"]').click();

View File

@@ -12,6 +12,7 @@ describe('Admin Edit Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-edit-title').click();
cy.get('a[data-test="menu.section.edit_community"]').click(); cy.get('a[data-test="menu.section.edit_community"]').click();
@@ -25,6 +26,7 @@ describe('Admin Edit Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-edit-title').click();
cy.get('a[data-test="menu.section.edit_collection"]').click(); cy.get('a[data-test="menu.section.edit_collection"]').click();
@@ -38,6 +40,7 @@ describe('Admin Edit Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-edit-title').click();
cy.get('a[data-test="menu.section.edit_item"]').click(); cy.get('a[data-test="menu.section.edit_item"]').click();

View File

@@ -12,6 +12,7 @@ describe('Admin Export Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-export-title').click();
cy.get('a[data-test="menu.section.export_metadata"]').click(); cy.get('a[data-test="menu.section.export_metadata"]').click();
@@ -25,6 +26,7 @@ describe('Admin Export Modals', () => {
cy.get('#sidebar-collapse-toggle').click(); cy.get('#sidebar-collapse-toggle').click();
// Click on entry of menu // 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('#admin-menu-section-export-title').click();
cy.get('a[data-test="menu.section.export_batch"]').click(); cy.get('a[data-test="menu.section.export_batch"]').click();

View File

@@ -13,16 +13,16 @@ beforeEach(() => {
describe('Edit Item > Edit Metadata tab', () => { describe('Edit Item > Edit Metadata tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="metadata"]').should('be.visible');
cy.get('a[data-test="metadata"]').click(); cy.get('a[data-test="metadata"]').click();
// 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 // <ds-edit-item-page> tag must be loaded
cy.get('ds-edit-item-page').should('be.visible'); cy.get('ds-edit-item-page').should('be.visible');
// wait for all the Edit Item tabs to be rendered
cy.get('ds-edit-item-page ul[role="tablist"]').each(($row: HTMLDivElement) => {
cy.wrap($row).find('li[role="presentation"]').should('be.visible');
});
// wait for all the ds-dso-edit-metadata-value components to be rendered // wait for all the ds-dso-edit-metadata-value components to be rendered
cy.get('ds-dso-edit-metadata-value div[role="row"]').each(($row: HTMLDivElement) => { cy.get('ds-dso-edit-metadata-value div[role="row"]').each(($row: HTMLDivElement) => {
cy.wrap($row).find('div[role="cell"]').should('be.visible'); cy.wrap($row).find('div[role="cell"]').should('be.visible');
@@ -36,8 +36,13 @@ describe('Edit Item > Edit Metadata tab', () => {
describe('Edit Item > Status tab', () => { describe('Edit Item > Status tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="status"]').should('be.visible');
cy.get('a[data-test="status"]').click(); cy.get('a[data-test="status"]').click();
// 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 // <ds-item-status> tag must be loaded
cy.get('ds-item-status').should('be.visible'); cy.get('ds-item-status').should('be.visible');
@@ -49,8 +54,13 @@ describe('Edit Item > Status tab', () => {
describe('Edit Item > Bitstreams tab', () => { describe('Edit Item > Bitstreams tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="bitstreams"]').should('be.visible');
cy.get('a[data-test="bitstreams"]').click(); cy.get('a[data-test="bitstreams"]').click();
// 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 // <ds-item-bitstreams> tag must be loaded
cy.get('ds-item-bitstreams').should('be.visible'); cy.get('ds-item-bitstreams').should('be.visible');
@@ -73,8 +83,13 @@ describe('Edit Item > Bitstreams tab', () => {
describe('Edit Item > Curate tab', () => { describe('Edit Item > Curate tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="curate"]').should('be.visible');
cy.get('a[data-test="curate"]').click(); cy.get('a[data-test="curate"]').click();
// 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 // <ds-item-curate> tag must be loaded
cy.get('ds-item-curate').should('be.visible'); cy.get('ds-item-curate').should('be.visible');
@@ -86,8 +101,13 @@ describe('Edit Item > Curate tab', () => {
describe('Edit Item > Relationships tab', () => { describe('Edit Item > Relationships tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="relationships"]').should('be.visible');
cy.get('a[data-test="relationships"]').click(); cy.get('a[data-test="relationships"]').click();
// 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 // <ds-item-relationships> tag must be loaded
cy.get('ds-item-relationships').should('be.visible'); cy.get('ds-item-relationships').should('be.visible');
@@ -99,8 +119,13 @@ describe('Edit Item > Relationships tab', () => {
describe('Edit Item > Version History tab', () => { describe('Edit Item > Version History tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="versionhistory"]').should('be.visible');
cy.get('a[data-test="versionhistory"]').click(); cy.get('a[data-test="versionhistory"]').click();
// 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 // <ds-item-version-history> tag must be loaded
cy.get('ds-item-version-history').should('be.visible'); cy.get('ds-item-version-history').should('be.visible');
@@ -112,8 +137,13 @@ describe('Edit Item > Version History tab', () => {
describe('Edit Item > Access Control tab', () => { describe('Edit Item > Access Control tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="access-control"]').should('be.visible');
cy.get('a[data-test="access-control"]').click(); cy.get('a[data-test="access-control"]').click();
// 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 // <ds-item-access-control> tag must be loaded
cy.get('ds-item-access-control').should('be.visible'); cy.get('ds-item-access-control').should('be.visible');
@@ -125,8 +155,13 @@ describe('Edit Item > Access Control tab', () => {
describe('Edit Item > Collection Mapper tab', () => { describe('Edit Item > Collection Mapper tab', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.get('a[data-test="mapper"]').should('be.visible');
cy.get('a[data-test="mapper"]').click(); cy.get('a[data-test="mapper"]').click();
// 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 // <ds-item-collection-mapper> tag must be loaded
cy.get('ds-item-collection-mapper').should('be.visible'); cy.get('ds-item-collection-mapper').should('be.visible');

View File

@@ -21,7 +21,7 @@ networks:
external: true external: true
services: services:
dspace-cli: dspace-cli:
image: "${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-dspace-7_x}" image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-dspace-7_x}"
container_name: dspace-cli container_name: dspace-cli
environment: environment:
# Below syntax may look odd, but it is how to override dspace.cfg settings via env variables. # Below syntax may look odd, but it is how to override dspace.cfg settings via env variables.

View File

@@ -14,7 +14,7 @@
# # Therefore, it should be kept in sync with that file # # Therefore, it should be kept in sync with that file
services: services:
dspacedb: dspacedb:
image: dspace/dspace-postgres-pgcrypto:loadsql image: ${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-7_x}-loadsql
environment: environment:
# This LOADSQL should be kept in sync with the URL in DSpace/DSpace # 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 # This SQL is available from https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data

View File

@@ -33,7 +33,7 @@ services:
# This allows us to generate statistics in e2e tests so that statistics pages can be tested thoroughly. # This allows us to generate statistics in e2e tests so that statistics pages can be tested thoroughly.
solr__D__statistics__P__autoCommit: 'false' solr__D__statistics__P__autoCommit: 'false'
LOGGING_CONFIG: /dspace/config/log4j2-container.xml LOGGING_CONFIG: /dspace/config/log4j2-container.xml
image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-7_x-test}" image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-7_x-test}"
depends_on: depends_on:
- dspacedb - dspacedb
networks: networks:
@@ -60,7 +60,7 @@ services:
# NOTE: This is customized to use our loadsql image, so that we are using a database with existing test data # NOTE: This is customized to use our loadsql image, so that we are using a database with existing test data
dspacedb: dspacedb:
container_name: dspacedb container_name: dspacedb
image: "${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-7_x-loadsql}" image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-7_x}-loadsql"
environment: environment:
# This LOADSQL should be kept in sync with the LOADSQL in # 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 # https://github.com/DSpace/DSpace/blob/main/dspace/src/main/docker-compose/db.entities.yml
@@ -81,7 +81,7 @@ services:
# DSpace Solr container # DSpace Solr container
dspacesolr: dspacesolr:
container_name: dspacesolr container_name: dspacesolr
image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-dspace-7_x}" image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-dspace-7_x}"
networks: networks:
- dspacenet - dspacenet
ports: ports:

View File

@@ -26,7 +26,7 @@ services:
DSPACE_REST_HOST: demo.dspace.org DSPACE_REST_HOST: demo.dspace.org
DSPACE_REST_PORT: 443 DSPACE_REST_PORT: 443
DSPACE_REST_NAMESPACE: /server DSPACE_REST_NAMESPACE: /server
image: dspace/dspace-angular:dspace-7_x-dist image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-angular:${DSPACE_VER:-dspace-7_x}-dist"
build: build:
context: .. context: ..
dockerfile: Dockerfile.dist 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. # from the host machine. This IP range MUST correspond to the 'dspacenet' subnet defined above.
proxies__P__trusted__P__ipranges: '172.23.0' proxies__P__trusted__P__ipranges: '172.23.0'
LOGGING_CONFIG: /dspace/config/log4j2-container.xml LOGGING_CONFIG: /dspace/config/log4j2-container.xml
image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-7_x-test}" image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-7_x-test}"
depends_on: depends_on:
- dspacedb - dspacedb
networks: networks:
@@ -67,7 +67,7 @@ services:
dspacedb: dspacedb:
container_name: dspacedb container_name: dspacedb
# Uses a custom Postgres image with pgcrypto installed # Uses a custom Postgres image with pgcrypto installed
image: "${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-7_x}" image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-dspace-7_x}"
environment: environment:
PGDATA: /pgdata PGDATA: /pgdata
POSTGRES_PASSWORD: dspace POSTGRES_PASSWORD: dspace
@@ -84,7 +84,7 @@ services:
# DSpace Solr container # DSpace Solr container
dspacesolr: dspacesolr:
container_name: dspacesolr container_name: dspacesolr
image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-dspace-7_x}" image: "${DOCKER_REGISTRY:-docker.io}/${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-dspace-7_x}"
networks: networks:
- dspacenet - dspacenet
ports: ports:

View File

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

View File

@@ -73,25 +73,25 @@
"@nicky-lenaers/ngx-scroll-to": "^14.0.0", "@nicky-lenaers/ngx-scroll-to": "^14.0.0",
"angular-idle-preload": "3.0.0", "angular-idle-preload": "3.0.0",
"angulartics2": "^12.2.1", "angulartics2": "^12.2.1",
"axios": "^1.7.7", "axios": "^1.7.9",
"bootstrap": "^4.6.1", "bootstrap": "^4.6.1",
"cerialize": "0.1.18", "cerialize": "0.1.18",
"cli-progress": "^3.12.0", "cli-progress": "^3.12.0",
"colors": "^1.4.0", "colors": "^1.4.0",
"compression": "^1.7.4", "compression": "^1.7.5",
"cookie-parser": "1.4.7", "cookie-parser": "1.4.7",
"core-js": "^3.38.1", "core-js": "^3.39.0",
"date-fns": "^2.30.0", "date-fns": "^2.30.0",
"date-fns-tz": "^1.3.7", "date-fns-tz": "^1.3.7",
"deepmerge": "^4.3.1", "deepmerge": "^4.3.1",
"ejs": "^3.1.10", "ejs": "^3.1.10",
"express": "^4.21.1", "express": "^4.21.2",
"express-rate-limit": "^5.1.3", "express-rate-limit": "^5.1.3",
"fast-json-patch": "^3.1.1", "fast-json-patch": "^3.1.1",
"filesize": "^6.1.0", "filesize": "^6.1.0",
"http-proxy-middleware": "^2.0.7", "http-proxy-middleware": "^2.0.7",
"http-terminator": "^3.2.0", "http-terminator": "^3.2.0",
"isbot": "^5.1.17", "isbot": "^5.1.21",
"js-cookie": "2.2.1", "js-cookie": "2.2.1",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"json5": "^2.2.3", "json5": "^2.2.3",
@@ -102,7 +102,7 @@
"lru-cache": "^7.14.1", "lru-cache": "^7.14.1",
"markdown-it": "^13.0.2", "markdown-it": "^13.0.2",
"markdown-it-mathjax3": "^4.3.2", "markdown-it-mathjax3": "^4.3.2",
"mirador": "^3.3.0", "mirador": "^3.4.2",
"mirador-dl-plugin": "^0.13.0", "mirador-dl-plugin": "^0.13.0",
"mirador-share-plugin": "^0.16.0", "mirador-share-plugin": "^0.16.0",
"morgan": "^1.10.0", "morgan": "^1.10.0",
@@ -116,8 +116,8 @@
"pem": "1.14.8", "pem": "1.14.8",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.0", "rxjs": "^7.8.0",
"sanitize-html": "^2.13.1", "sanitize-html": "^2.14.0",
"sortablejs": "1.15.3", "sortablejs": "1.15.6",
"uuid": "^8.3.2", "uuid": "^8.3.2",
"zone.js": "~0.13.3" "zone.js": "~0.13.3"
}, },
@@ -133,7 +133,7 @@
"@angular/compiler-cli": "^15.2.10", "@angular/compiler-cli": "^15.2.10",
"@angular/language-service": "^15.2.10", "@angular/language-service": "^15.2.10",
"@cypress/schematic": "^1.5.0", "@cypress/schematic": "^1.5.0",
"@fortawesome/fontawesome-free": "^6.6.0", "@fortawesome/fontawesome-free": "^6.7.2",
"@material-ui/core": "^4.12.4", "@material-ui/core": "^4.12.4",
"@material-ui/icons": "^4.11.3", "@material-ui/icons": "^4.11.3",
"@ngrx/store-devtools": "^15.4.0", "@ngrx/store-devtools": "^15.4.0",
@@ -145,7 +145,7 @@
"@types/grecaptcha": "^3.0.9", "@types/grecaptcha": "^3.0.9",
"@types/jasmine": "~3.6.0", "@types/jasmine": "~3.6.0",
"@types/js-cookie": "2.2.6", "@types/js-cookie": "2.2.6",
"@types/lodash": "^4.17.12", "@types/lodash": "^4.17.13",
"@types/node": "^14.18.63", "@types/node": "^14.18.63",
"@types/sanitize-html": "^2.13.0", "@types/sanitize-html": "^2.13.0",
"@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/eslint-plugin": "^5.62.0",
@@ -155,17 +155,17 @@
"copy-webpack-plugin": "^6.4.1", "copy-webpack-plugin": "^6.4.1",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"csstype": "^3.1.3", "csstype": "^3.1.3",
"cypress": "^13.15.1", "cypress": "^13.17.0",
"cypress-axe": "^1.5.0", "cypress-axe": "^1.5.0",
"deep-freeze": "0.0.1", "deep-freeze": "0.0.1",
"eslint": "^8.39.0", "eslint": "^8.39.0",
"eslint-plugin-deprecation": "^1.5.0", "eslint-plugin-deprecation": "^1.5.0",
"eslint-plugin-import": "^2.31.0", "eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsdoc": "^45.0.0", "eslint-plugin-jsdoc": "^45.0.0",
"eslint-plugin-jsonc": "^2.16.0", "eslint-plugin-jsonc": "^2.18.2",
"eslint-plugin-lodash": "^7.4.0", "eslint-plugin-lodash": "^7.4.0",
"eslint-plugin-unused-imports": "^2.0.0", "eslint-plugin-unused-imports": "^2.0.0",
"express-static-gzip": "^2.1.8", "express-static-gzip": "^2.2.0",
"jasmine-core": "^3.8.0", "jasmine-core": "^3.8.0",
"jasmine-marbles": "0.9.2", "jasmine-marbles": "0.9.2",
"karma": "^6.4.4", "karma": "^6.4.4",
@@ -174,7 +174,7 @@
"karma-jasmine": "~4.0.0", "karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0", "karma-jasmine-html-reporter": "^1.5.0",
"karma-mocha-reporter": "2.2.5", "karma-mocha-reporter": "2.2.5",
"ng-mocks": "^14.13.1", "ng-mocks": "^14.13.2",
"ngx-mask": "^13.1.7", "ngx-mask": "^13.1.7",
"nodemon": "^2.0.22", "nodemon": "^2.0.22",
"postcss": "^8.4", "postcss": "^8.4",
@@ -186,7 +186,7 @@
"react-copy-to-clipboard": "^5.1.0", "react-copy-to-clipboard": "^5.1.0",
"react-dom": "^16.14.0", "react-dom": "^16.14.0",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"sass": "~1.80.4", "sass": "~1.83.1",
"sass-loader": "^12.6.0", "sass-loader": "^12.6.0",
"sass-resources-loader": "^2.2.5", "sass-resources-loader": "^2.2.5",
"ts-node": "^8.10.2", "ts-node": "^8.10.2",

View File

@@ -61,7 +61,7 @@
</thead> </thead>
<tbody> <tbody>
<tr *ngFor="let epersonDto of (ePeopleDto$ | async)?.page" <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>{{epersonDto.eperson.id}}</td>
<td>{{ dsoNameService.getName(epersonDto.eperson) }}</td> <td>{{ dsoNameService.getName(epersonDto.eperson) }}</td>
<td>{{epersonDto.eperson.email}}</td> <td>{{epersonDto.eperson.email}}</td>

View File

@@ -46,6 +46,8 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
*/ */
ePeopleDto$: BehaviorSubject<PaginatedList<EpersonDtoModel>> = new BehaviorSubject<PaginatedList<EpersonDtoModel>>({} as any); 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 * An observable for the pageInfo, needed to pass to the pagination component
*/ */
@@ -111,6 +113,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
initialisePage() { initialisePage() {
this.searching$.next(true); this.searching$.next(true);
this.search({scope: this.currentSearchScope, query: this.currentSearchQuery}); this.search({scope: this.currentSearchScope, query: this.currentSearchQuery});
this.activeEPerson$ = this.epersonService.getActiveEPerson();
this.subs.push(this.ePeople$.pipe( this.subs.push(this.ePeople$.pipe(
switchMap((epeople: PaginatedList<EPerson>) => { switchMap((epeople: PaginatedList<EPerson>) => {
if (epeople.pageInfo.totalElements > 0) { if (epeople.pageInfo.totalElements > 0) {
@@ -178,23 +181,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 * Deletes EPerson, show notification on success/failure & updates EPeople list
*/ */

View File

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

View File

@@ -1,11 +1,11 @@
import { Observable, of as observableOf } from 'rxjs'; import { Observable, of as observableOf } from 'rxjs';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { BrowserModule, By } from '@angular/platform-browser'; import { BrowserModule, By } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { buildPaginatedList, PaginatedList } from '../../../core/data/paginated-list.model'; import { buildPaginatedList, PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data'; import { RemoteData } from '../../../core/data/remote-data';
import { EPersonDataService } from '../../../core/eperson/eperson-data.service'; import { EPersonDataService } from '../../../core/eperson/eperson-data.service';
@@ -19,7 +19,6 @@ import { EPersonMock, EPersonMock2 } from '../../../shared/testing/eperson.mock'
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock'; import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
import { AuthService } from '../../../core/auth/auth.service'; import { AuthService } from '../../../core/auth/auth.service';
import { AuthServiceStub } from '../../../shared/testing/auth-service.stub'; import { AuthServiceStub } from '../../../shared/testing/auth-service.stub';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service'; import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
@@ -35,6 +34,7 @@ import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { RouterStub } from '../../../shared/testing/router.stub'; import { RouterStub } from '../../../shared/testing/router.stub';
import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub'; import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
import { RouterTestingModule } from '@angular/router/testing';
describe('EPersonFormComponent', () => { describe('EPersonFormComponent', () => {
let component: EPersonFormComponent; let component: EPersonFormComponent;
@@ -59,9 +59,6 @@ describe('EPersonFormComponent', () => {
ePersonDataServiceStub = { ePersonDataServiceStub = {
activeEPerson: null, activeEPerson: null,
allEpeople: mockEPeople, allEpeople: mockEPeople,
getEPeople(): Observable<RemoteData<PaginatedList<EPerson>>> {
return createSuccessfulRemoteDataObject$(buildPaginatedList(null, this.allEpeople));
},
getActiveEPerson(): Observable<EPerson> { getActiveEPerson(): Observable<EPerson> {
return observableOf(this.activeEPerson); return observableOf(this.activeEPerson);
}, },
@@ -195,12 +192,8 @@ describe('EPersonFormComponent', () => {
router = new RouterStub(); router = new RouterStub();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({ RouterTestingModule,
loader: { TranslateModule.forRoot(),
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
], ],
declarations: [EPersonFormComponent], declarations: [EPersonFormComponent],
providers: [ providers: [
@@ -217,7 +210,7 @@ describe('EPersonFormComponent', () => {
{ provide: Router, useValue: router }, { provide: Router, useValue: router },
EPeopleRegistryComponent EPeopleRegistryComponent
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents(); }).compileComponents();
})); }));
@@ -236,37 +229,13 @@ describe('EPersonFormComponent', () => {
}); });
describe('check form validation', () => { describe('check form validation', () => {
let firstName; let canLogIn: boolean;
let lastName; let requireCertificate: boolean;
let email;
let canLogIn;
let requireCertificate;
let expected;
beforeEach(() => { beforeEach(() => {
firstName = 'testName';
lastName = 'testLastName';
email = 'testEmail@test.com';
canLogIn = false; canLogIn = false;
requireCertificate = 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'); spyOn(component.submitForm, 'emit');
component.canLogIn.value = canLogIn; component.canLogIn.value = canLogIn;
component.requireCertificate.value = requireCertificate; component.requireCertificate.value = requireCertificate;
@@ -340,15 +309,13 @@ describe('EPersonFormComponent', () => {
expect(component.formGroup.controls.email.errors.emailTaken).toBeTruthy(); expect(component.formGroup.controls.email.errors.emailTaken).toBeTruthy();
}); });
}); });
}); });
describe('when submitting the form', () => { describe('when submitting the form', () => {
let firstName; let firstName;
let lastName; let lastName;
let email; let email;
let canLogIn; let canLogIn: boolean;
let requireCertificate; let requireCertificate;
let expected; let expected;
@@ -377,6 +344,7 @@ describe('EPersonFormComponent', () => {
requireCertificate: requireCertificate, requireCertificate: requireCertificate,
}); });
spyOn(component.submitForm, 'emit'); spyOn(component.submitForm, 'emit');
component.ngOnInit();
component.firstName.value = firstName; component.firstName.value = firstName;
component.lastName.value = lastName; component.lastName.value = lastName;
component.email.value = email; component.email.value = email;
@@ -416,9 +384,17 @@ describe('EPersonFormComponent', () => {
email: email, email: email,
canLogIn: canLogIn, canLogIn: canLogIn,
requireCertificate: requireCertificate, requireCertificate: requireCertificate,
_links: undefined _links: {
groups: {
href: '',
},
self: {
href: '',
},
},
}); });
spyOn(ePersonDataServiceStub, 'getActiveEPerson').and.returnValue(observableOf(expectedWithId)); spyOn(ePersonDataServiceStub, 'getActiveEPerson').and.returnValue(observableOf(expectedWithId));
component.ngOnInit();
component.onSubmit(); component.onSubmit();
fixture.detectChanges(); fixture.detectChanges();
}); });
@@ -466,22 +442,19 @@ describe('EPersonFormComponent', () => {
}); });
describe('delete', () => { describe('delete', () => {
let ePersonId;
let eperson: EPerson; let eperson: EPerson;
let modalService; let modalService;
beforeEach(() => { beforeEach(() => {
spyOn(authService, 'impersonate').and.callThrough(); spyOn(authService, 'impersonate').and.callThrough();
ePersonId = 'testEPersonId';
eperson = EPersonMock; eperson = EPersonMock;
component.epersonInitial = eperson; component.epersonInitial = eperson;
component.canDelete$ = observableOf(true); component.canDelete$ = observableOf(true);
spyOn(component.epersonService, 'getActiveEPerson').and.returnValue(observableOf(eperson)); spyOn(component.epersonService, 'getActiveEPerson').and.returnValue(observableOf(eperson));
modalService = (component as any).modalService; modalService = (component as any).modalService;
spyOn(modalService, 'open').and.returnValue(Object.assign({ componentInstance: Object.assign({ response: observableOf(true) }) })); spyOn(modalService, 'open').and.returnValue(Object.assign({ componentInstance: Object.assign({ response: observableOf(true) }) }));
component.ngOnInit();
fixture.detectChanges(); fixture.detectChanges();
}); });
it('the delete button should be visible if the ePerson can be deleted', () => { it('the delete button should be visible if the ePerson can be deleted', () => {

View File

@@ -139,6 +139,11 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
*/ */
canImpersonate$: Observable<boolean>; canImpersonate$: Observable<boolean>;
/**
* The current {@link EPerson}
*/
activeEPerson$: Observable<EPerson>;
/** /**
* List of subscriptions * List of subscriptions
*/ */
@@ -199,7 +204,11 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
protected route: ActivatedRoute, protected route: ActivatedRoute,
protected router: Router, 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; this.epersonInitial = eperson;
if (hasValue(eperson)) { if (hasValue(eperson)) {
this.isImpersonated = this.authService.isImpersonatingUser(eperson.id); this.isImpersonated = this.authService.isImpersonatingUser(eperson.id);
@@ -207,9 +216,6 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
this.submitLabel = 'form.submit'; this.submitLabel = 'form.submit';
} }
})); }));
}
ngOnInit() {
this.initialisePage(); this.initialisePage();
} }
@@ -217,126 +223,117 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* This method will initialise the page * This method will initialise the page
*/ */
initialisePage() { initialisePage() {
this.subs.push(this.epersonService.findById(this.route.snapshot.params.id).subscribe((ePersonRD: RemoteData<EPerson>) => { if (this.route.snapshot.params.id) {
this.epersonService.editEPerson(ePersonRD.payload); 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,
name: 'firstName',
validators: {
required: null,
},
required: true,
});
this.lastName = new DynamicInputModel({
id: 'lastName',
label: lastName,
name: 'lastName',
validators: {
required: null,
},
required: true,
});
this.email = new DynamicInputModel({
id: 'email',
label: email,
name: 'email',
validators: {
required: null,
pattern: '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$',
},
required: true,
errorMessages: {
emailTaken: 'error.validation.emailTaken',
pattern: 'error.validation.NotValidEmail'
},
hint: emailHint
});
this.canLogIn = new DynamicCheckboxModel(
{
id: 'canLogIn',
label: canLogIn,
name: 'canLogIn',
value: (this.epersonInitial != null ? this.epersonInitial.canLogIn : true)
});
this.requireCertificate = new DynamicCheckboxModel(
{
id: 'requireCertificate',
label: requireCertificate,
name: 'requireCertificate',
value: (this.epersonInitial != null ? this.epersonInitial.requireCertificate : false)
});
this.formModel = [
this.firstName,
this.lastName,
this.email,
this.canLogIn,
this.requireCertificate,
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
if (eperson != null) {
this.groups = this.groupsDataService.findListByHref(eperson._links.groups.href, {
currentPage: 1,
elementsPerPage: this.config.pageSize
});
}
this.formGroup.patchValue({
firstName: eperson != null ? eperson.firstMetadataValue('eperson.firstname') : '',
lastName: eperson != null ? eperson.firstMetadataValue('eperson.lastname') : '',
email: eperson != null ? eperson.email : '',
canLogIn: eperson != null ? eperson.canLogIn : true,
requireCertificate: eperson != null ? eperson.requireCertificate : false
});
if (eperson === null && !!this.formGroup.controls.email) {
this.formGroup.controls.email.setAsyncValidators(ValidateEmailNotTaken.createValidator(this.epersonService));
this.emailValueChangeSubscribe = this.email.valueChanges.pipe(debounceTime(300)).subscribe(() => {
this.changeDetectorRef.detectChanges();
});
}
})); }));
}
const activeEPerson$ = this.epersonService.getActiveEPerson(); this.firstName = new DynamicInputModel({
id: 'firstName',
this.groups = activeEPerson$.pipe( label: this.translateService.instant(`${this.messagePrefix}.firstName`),
switchMap((eperson) => { name: 'firstName',
return observableCombineLatest([observableOf(eperson), this.paginationService.getFindListOptions(this.config.id, { validators: {
currentPage: 1, required: null,
elementsPerPage: this.config.pageSize },
})]); required: true,
}),
switchMap(([eperson, findListOptions]) => {
if (eperson != null) {
return this.groupsDataService.findListByHref(eperson._links.groups.href, findListOptions, true, true, followLink('object'));
}
return observableOf(undefined);
})
);
this.canImpersonate$ = activeEPerson$.pipe(
switchMap((eperson) => {
if (hasValue(eperson)) {
return this.authorizationService.isAuthorized(FeatureID.LoginOnBehalfOf, eperson.self);
} else {
return observableOf(false);
}
})
);
this.canDelete$ = activeEPerson$.pipe(
switchMap((eperson) => this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined))
);
this.canReset$ = observableOf(true);
}); });
this.lastName = new DynamicInputModel({
id: 'lastName',
label: this.translateService.instant(`${this.messagePrefix}.lastName`),
name: 'lastName',
validators: {
required: null,
},
required: true,
});
this.email = new DynamicInputModel({
id: 'email',
label: this.translateService.instant(`${this.messagePrefix}.email`),
name: 'email',
validators: {
required: null,
pattern: '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$',
},
required: true,
errorMessages: {
emailTaken: 'error.validation.emailTaken',
pattern: 'error.validation.NotValidEmail'
},
hint: this.translateService.instant(`${this.messagePrefix}.emailHint`),
});
this.canLogIn = new DynamicCheckboxModel(
{
id: '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: this.translateService.instant(`${this.messagePrefix}.requireCertificate`),
name: 'requireCertificate',
value: (this.epersonInitial != null ? this.epersonInitial.requireCertificate : false)
});
this.formModel = [
this.firstName,
this.lastName,
this.email,
this.canLogIn,
this.requireCertificate,
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
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') : '',
lastName: eperson != null ? eperson.firstMetadataValue('eperson.lastname') : '',
email: eperson != null ? eperson.email : '',
canLogIn: eperson != null ? eperson.canLogIn : true,
requireCertificate: eperson != null ? eperson.requireCertificate : false
});
if (eperson === null && !!this.formGroup.controls.email) {
this.formGroup.controls.email.setAsyncValidators(ValidateEmailNotTaken.createValidator(this.epersonService));
this.emailValueChangeSubscribe = this.email.valueChanges.pipe(debounceTime(300)).subscribe(() => {
this.changeDetectorRef.detectChanges();
});
}
}));
this.groups = this.activeEPerson$.pipe(
switchMap((eperson) => {
return observableCombineLatest([observableOf(eperson), this.paginationService.getFindListOptions(this.config.id, {
currentPage: 1,
elementsPerPage: this.config.pageSize
})]);
}),
switchMap(([eperson, findListOptions]) => {
if (eperson != null) {
return this.groupsDataService.findListByHref(eperson._links.groups.href, findListOptions, true, true, followLink('object'));
}
return observableOf(undefined);
})
);
this.canImpersonate$ = this.activeEPerson$.pipe(
switchMap((eperson) => {
if (hasValue(eperson)) {
return this.authorizationService.isAuthorized(FeatureID.LoginOnBehalfOf, eperson.self);
} else {
return observableOf(false);
}
})
);
this.canDelete$ = this.activeEPerson$.pipe(
switchMap((eperson) => this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined))
);
this.canReset$ = observableOf(true);
} }
/** /**
@@ -355,7 +352,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* Emit the updated/created eperson using the EventEmitter submitForm * Emit the updated/created eperson using the EventEmitter submitForm
*/ */
onSubmit() { onSubmit() {
this.epersonService.getActiveEPerson().pipe(take(1)).subscribe( this.activeEPerson$.pipe(take(1)).subscribe(
(ePerson: EPerson) => { (ePerson: EPerson) => {
const values = { const values = {
metadata: { metadata: {
@@ -474,7 +471,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. * It'll either show a success or error message depending on whether the delete was successful or not.
*/ */
delete(): void { delete(): void {
this.epersonService.getActiveEPerson().pipe( this.activeEPerson$.pipe(
take(1), take(1),
switchMap((eperson: EPerson) => { switchMap((eperson: EPerson) => {
const modalRef = this.modalService.open(ConfirmationModalComponent); const modalRef = this.modalService.open(ConfirmationModalComponent);
@@ -578,7 +575,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* Update the list of groups by fetching it from the rest api or cache * Update the list of groups by fetching it from the rest api or cache
*/ */
private updateGroups(options) { 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); this.groups = this.groupsDataService.findListByHref(eperson._links.groups.href, options);
})); }));
} }

View File

@@ -2,7 +2,7 @@
<div class="group-form row"> <div class="group-form row">
<div class="col-12"> <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> <ng-template #createHeader>
<h1 class="border-bottom pb-2">{{messagePrefix + '.head.create' | translate}}</h1> <h1 class="border-bottom pb-2">{{messagePrefix + '.head.create' | translate}}</h1>
@@ -23,11 +23,15 @@
</h1> </h1>
</ng-template> </ng-template>
<ds-alert *ngIf="groupBeingEdited?.permanent" [type]="AlertTypeEnum.Warning" <ng-container *ngIf="(activeGroup$ | async) as groupBeingEdited">
[content]="messagePrefix + '.alert.permanent'"></ds-alert> <ds-alert *ngIf="groupBeingEdited?.permanent" [type]="AlertType.Warning"
<ds-alert *ngIf="!(canEdit$ | async) && (groupDataService.getActiveGroup() | async)" [type]="AlertTypeEnum.Warning" [content]="messagePrefix + '.alert.permanent'"></ds-alert>
[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> <ds-alert *ngIf="!(canEdit$ | async)" [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" <ds-form [formId]="formId"
[formModel]="formModel" [formModel]="formModel"
@@ -39,22 +43,21 @@
<button (click)="onCancel()" type="button" <button (click)="onCancel()" type="button"
class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> {{messagePrefix + '.return' | translate}}</button> class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> {{messagePrefix + '.return' | translate}}</button>
</div> </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"> <button (click)="delete()" class="btn btn-danger delete-button" type="button">
<i class="fa fa-trash"></i> {{ messagePrefix + '.actions.delete' | translate}} <i class="fa fa-trash"></i> {{ messagePrefix + '.actions.delete' | translate}}
</button> </button>
</div> </div>
</ds-form> </ds-form>
<div class="mb-5"> <ng-container *ngIf="(activeGroup$ | async) as groupBeingEdited">
<ds-members-list *ngIf="groupBeingEdited != null" <div class="mb-5">
[messagePrefix]="messagePrefix + '.members-list'"></ds-members-list> <ds-members-list *ngIf="groupBeingEdited != null"
</div> [messagePrefix]="messagePrefix + '.members-list'"></ds-members-list>
<ds-subgroups-list *ngIf="groupBeingEdited != null" </div>
[messagePrefix]="messagePrefix + '.subgroups-list'"></ds-subgroups-list> <ds-subgroups-list *ngIf="groupBeingEdited != null"
[messagePrefix]="messagePrefix + '.subgroups-list'"></ds-subgroups-list>
</ng-container>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -1,13 +1,13 @@
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { BrowserModule, By } from '@angular/platform-browser'; import { BrowserModule, By } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { Observable, of as observableOf } from 'rxjs'; import { Observable, of as observableOf } from 'rxjs';
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service'; import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../../../core/cache/object-cache.service'; import { ObjectCacheService } from '../../../core/cache/object-cache.service';
@@ -30,8 +30,6 @@ import { GroupMock, GroupMock2 } from '../../../shared/testing/group-mock';
import { GroupFormComponent } from './group-form.component'; import { GroupFormComponent } from './group-form.component';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock'; import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { getMockTranslateService } from '../../../shared/mocks/translate.service.mock';
import { TranslateLoaderMock } from '../../../shared/testing/translate-loader.mock';
import { RouterMock } from '../../../shared/mocks/router.mock'; import { RouterMock } from '../../../shared/mocks/router.mock';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { Operation } from 'fast-json-patch'; import { Operation } from 'fast-json-patch';
@@ -39,23 +37,24 @@ import { ValidateGroupExists } from './validators/group-exists.validator';
import { NoContent } from '../../../core/shared/NoContent.model'; import { NoContent } from '../../../core/shared/NoContent.model';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { DSONameServiceMock } from '../../../shared/mocks/dso-name.service.mock'; import { DSONameServiceMock } from '../../../shared/mocks/dso-name.service.mock';
import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
describe('GroupFormComponent', () => { describe('GroupFormComponent', () => {
let component: GroupFormComponent; let component: GroupFormComponent;
let fixture: ComponentFixture<GroupFormComponent>; let fixture: ComponentFixture<GroupFormComponent>;
let translateService: TranslateService;
let builderService: FormBuilderService; let builderService: FormBuilderService;
let ePersonDataServiceStub: any; let ePersonDataServiceStub: any;
let groupsDataServiceStub: any; let groupsDataServiceStub: any;
let dsoDataServiceStub: any; let dsoDataServiceStub: any;
let authorizationService: AuthorizationDataService; let authorizationService: AuthorizationDataService;
let notificationService: NotificationsServiceStub; let notificationService: NotificationsServiceStub;
let router; let router: RouterMock;
let route: ActivatedRouteStub;
let groups; let groups: Group[];
let groupName; let groupName: string;
let groupDescription; let groupDescription: string;
let expected; let expected: Group;
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
groups = [GroupMock, GroupMock2]; groups = [GroupMock, GroupMock2];
@@ -70,6 +69,15 @@ describe('GroupFormComponent', () => {
} }
], ],
}, },
object: createSuccessfulRemoteDataObject$(undefined),
_links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
}
},
}); });
ePersonDataServiceStub = {}; ePersonDataServiceStub = {};
groupsDataServiceStub = { groupsDataServiceStub = {
@@ -106,7 +114,14 @@ describe('GroupFormComponent', () => {
create(group: Group): Observable<RemoteData<Group>> { create(group: Group): Observable<RemoteData<Group>> {
this.allGroups = [...this.allGroups, group]; this.allGroups = [...this.allGroups, group];
this.createdGroup = Object.assign({}, group, { this.createdGroup = Object.assign({}, group, {
_links: { self: { href: 'group-selflink' } } _links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
},
},
}); });
return createSuccessfulRemoteDataObject$(this.createdGroup); return createSuccessfulRemoteDataObject$(this.createdGroup);
}, },
@@ -188,17 +203,13 @@ describe('GroupFormComponent', () => {
return typeof value === 'object' && value !== null; return typeof value === 'object' && value !== null;
} }
}); });
translateService = getMockTranslateService();
router = new RouterMock(); router = new RouterMock();
route = new ActivatedRouteStub();
notificationService = new NotificationsServiceStub(); notificationService = new NotificationsServiceStub();
return TestBed.configureTestingModule({ return TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({ TranslateModule.forRoot(),
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
], ],
declarations: [GroupFormComponent], declarations: [GroupFormComponent],
providers: [ providers: [
@@ -216,14 +227,11 @@ describe('GroupFormComponent', () => {
{ provide: Store, useValue: {} }, { provide: Store, useValue: {} },
{ provide: RemoteDataBuildService, useValue: {} }, { provide: RemoteDataBuildService, useValue: {} },
{ provide: HALEndpointService, useValue: {} }, { provide: HALEndpointService, useValue: {} },
{ { provide: ActivatedRoute, useValue: route },
provide: ActivatedRoute,
useValue: { data: observableOf({ dso: { payload: {} } }), params: observableOf({}) }
},
{ provide: Router, useValue: router }, { provide: Router, useValue: router },
{ provide: AuthorizationDataService, useValue: authorizationService }, { provide: AuthorizationDataService, useValue: authorizationService },
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents(); }).compileComponents();
})); }));
@@ -236,8 +244,8 @@ describe('GroupFormComponent', () => {
describe('when submitting the form', () => { describe('when submitting the form', () => {
beforeEach(() => { beforeEach(() => {
spyOn(component.submitForm, 'emit'); spyOn(component.submitForm, 'emit');
component.groupName.value = groupName; component.groupName.setValue(groupName);
component.groupDescription.value = groupDescription; component.groupDescription.setValue(groupDescription);
}); });
describe('without active Group', () => { describe('without active Group', () => {
beforeEach(() => { beforeEach(() => {
@@ -245,14 +253,22 @@ describe('GroupFormComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should emit a new group using the correct values', (async () => { it('should emit a new group using the correct values', (() => {
await fixture.whenStable().then(() => { expect(component.submitForm.emit).toHaveBeenCalledWith(jasmine.objectContaining({
expect(component.submitForm.emit).toHaveBeenCalledWith(expected); name: groupName,
}); metadata: {
'dc.description': [
{
value: groupDescription,
},
],
},
}));
})); }));
}); });
describe('with active Group', () => { describe('with active Group', () => {
let expected2; let expected2: Group;
beforeEach(() => { beforeEach(() => {
expected2 = Object.assign(new Group(), { expected2 = Object.assign(new Group(), {
name: 'newGroupName', name: 'newGroupName',
@@ -263,15 +279,24 @@ describe('GroupFormComponent', () => {
} }
], ],
}, },
object: createSuccessfulRemoteDataObject$(undefined),
_links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
},
},
}); });
spyOn(groupsDataServiceStub, 'getActiveGroup').and.returnValue(observableOf(expected)); spyOn(groupsDataServiceStub, 'getActiveGroup').and.returnValue(observableOf(expected));
spyOn(groupsDataServiceStub, 'patch').and.returnValue(createSuccessfulRemoteDataObject$(expected2)); spyOn(groupsDataServiceStub, 'patch').and.returnValue(createSuccessfulRemoteDataObject$(expected2));
component.groupName.value = 'newGroupName'; component.ngOnInit();
component.onSubmit();
fixture.detectChanges();
}); });
it('should edit with name and description operations', () => { it('should edit with name and description operations', () => {
component.groupName.setValue('newGroupName');
component.onSubmit();
const operations = [{ const operations = [{
op: 'add', op: 'add',
path: '/metadata/dc.description', path: '/metadata/dc.description',
@@ -285,9 +310,8 @@ describe('GroupFormComponent', () => {
}); });
it('should edit with description operations', () => { it('should edit with description operations', () => {
component.groupName.value = null; component.groupName.setValue(null);
component.onSubmit(); component.onSubmit();
fixture.detectChanges();
const operations = [{ const operations = [{
op: 'add', op: 'add',
path: '/metadata/dc.description', path: '/metadata/dc.description',
@@ -297,9 +321,9 @@ describe('GroupFormComponent', () => {
}); });
it('should edit with name operations', () => { it('should edit with name operations', () => {
component.groupDescription.value = null; component.groupName.setValue('newGroupName');
component.groupDescription.setValue(null);
component.onSubmit(); component.onSubmit();
fixture.detectChanges();
const operations = [{ const operations = [{
op: 'replace', op: 'replace',
path: '/name', path: '/name',
@@ -308,12 +332,13 @@ describe('GroupFormComponent', () => {
expect(groupsDataServiceStub.patch).toHaveBeenCalledWith(expected, operations); expect(groupsDataServiceStub.patch).toHaveBeenCalledWith(expected, operations);
}); });
it('should emit the existing group using the correct new values', (async () => { it('should emit the existing group using the correct new values', () => {
await fixture.whenStable().then(() => { component.onSubmit();
expect(component.submitForm.emit).toHaveBeenCalledWith(expected2); expect(component.submitForm.emit).toHaveBeenCalledWith(expected2);
}); });
}));
it('should emit success notification', () => { it('should emit success notification', () => {
component.onSubmit();
expect(notificationService.success).toHaveBeenCalled(); expect(notificationService.success).toHaveBeenCalled();
}); });
}); });
@@ -328,11 +353,8 @@ describe('GroupFormComponent', () => {
describe('check form validation', () => { describe('check form validation', () => {
let groupCommunity;
beforeEach(() => { beforeEach(() => {
groupName = 'testName'; groupName = 'testName';
groupCommunity = 'testgroupCommunity';
groupDescription = 'testgroupDescription'; groupDescription = 'testgroupDescription';
expected = Object.assign(new Group(), { expected = Object.assign(new Group(), {
@@ -344,8 +366,17 @@ describe('GroupFormComponent', () => {
} }
], ],
}, },
_links: {
self: {
href: 'group-selflink',
},
object: {
href: 'group-objectlink',
},
},
}); });
spyOn(component.submitForm, 'emit'); spyOn(component.submitForm, 'emit');
spyOn(dsoDataServiceStub, 'findByHref').and.returnValue(observableOf(expected));
fixture.detectChanges(); fixture.detectChanges();
component.initialisePage(); component.initialisePage();
@@ -395,21 +426,20 @@ describe('GroupFormComponent', () => {
}); });
describe('delete', () => { describe('delete', () => {
let deleteButton; let deleteButton: HTMLButtonElement;
beforeEach(() => {
component.initialisePage();
beforeEach(async () => {
spyOn(groupsDataServiceStub, 'delete').and.callThrough();
component.activeGroup$ = observableOf({
id: 'active-group',
permanent: false,
} as Group);
component.canEdit$ = observableOf(true); component.canEdit$ = observableOf(true);
component.groupBeingEdited = {
permanent: false component.initialisePage();
} as Group;
fixture.detectChanges(); fixture.detectChanges();
deleteButton = fixture.debugElement.query(By.css('.delete-button')).nativeElement; 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', () => { describe('if confirmed via modal', () => {

View File

@@ -1,5 +1,5 @@
import { Component, EventEmitter, HostListener, OnDestroy, OnInit, Output, ChangeDetectorRef } from '@angular/core'; import { Component, EventEmitter, HostListener, OnDestroy, OnInit, Output, ChangeDetectorRef } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms'; import { UntypedFormGroup, AbstractControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { import {
@@ -12,10 +12,9 @@ import { TranslateService } from '@ngx-translate/core';
import { import {
combineLatest as observableCombineLatest, combineLatest as observableCombineLatest,
Observable, Observable,
of as observableOf,
Subscription, Subscription,
} from 'rxjs'; } from 'rxjs';
import { catchError, map, switchMap, take, filter, debounceTime } from 'rxjs/operators'; import { map, switchMap, take, debounceTime } from 'rxjs/operators';
import { getCollectionEditRolesRoute } from '../../../collection-page/collection-page-routing-paths'; import { getCollectionEditRolesRoute } from '../../../collection-page/collection-page-routing-paths';
import { getCommunityEditRolesRoute } from '../../../community-page/community-page-routing-paths'; import { getCommunityEditRolesRoute } from '../../../community-page/community-page-routing-paths';
import { DSpaceObjectDataService } from '../../../core/data/dspace-object-data.service'; import { DSpaceObjectDataService } from '../../../core/data/dspace-object-data.service';
@@ -24,17 +23,16 @@ import { FeatureID } from '../../../core/data/feature-authorization/feature-id';
import { PaginatedList } from '../../../core/data/paginated-list.model'; import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data'; import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service'; import { RequestService } from '../../../core/data/request.service';
import { EPersonDataService } from '../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../core/eperson/group-data.service'; import { GroupDataService } from '../../../core/eperson/group-data.service';
import { Group } from '../../../core/eperson/models/group.model'; import { Group } from '../../../core/eperson/models/group.model';
import { Collection } from '../../../core/shared/collection.model'; import { Collection } from '../../../core/shared/collection.model';
import { Community } from '../../../core/shared/community.model'; import { Community } from '../../../core/shared/community.model';
import { DSpaceObject } from '../../../core/shared/dspace-object.model'; import { DSpaceObject } from '../../../core/shared/dspace-object.model';
import { import {
getAllCompletedRemoteData,
getRemoteDataPayload, getRemoteDataPayload,
getFirstSucceededRemoteData, getFirstSucceededRemoteData,
getFirstCompletedRemoteData, getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload
} from '../../../core/shared/operators'; } from '../../../core/shared/operators';
import { AlertType } from '../../../shared/alert/alert-type'; import { AlertType } from '../../../shared/alert/alert-type';
import { ConfirmationModalComponent } from '../../../shared/confirmation-modal/confirmation-modal.component'; import { ConfirmationModalComponent } from '../../../shared/confirmation-modal/confirmation-modal.component';
@@ -68,9 +66,9 @@ export class GroupFormComponent implements OnInit, OnDestroy {
/** /**
* Dynamic models for the inputs of form * Dynamic models for the inputs of form
*/ */
groupName: DynamicInputModel; groupName: AbstractControl;
groupCommunity: DynamicInputModel; groupCommunity: AbstractControl;
groupDescription: DynamicTextAreaModel; groupDescription: AbstractControl;
/** /**
* A list of all dynamic input models * A list of all dynamic input models
@@ -113,21 +111,30 @@ export class GroupFormComponent implements OnInit, OnDestroy {
*/ */
subs: Subscription[] = []; 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 * 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>; canEdit$: Observable<boolean>;
/** /**
* The AlertType enumeration * The current {@link Group}
* @type {AlertType}
*/ */
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 * Subscription to email field value change
@@ -137,126 +144,121 @@ export class GroupFormComponent implements OnInit, OnDestroy {
constructor( constructor(
public groupDataService: GroupDataService, public groupDataService: GroupDataService,
private ePersonDataService: EPersonDataService, protected dSpaceObjectDataService: DSpaceObjectDataService,
private dSpaceObjectDataService: DSpaceObjectDataService, protected formBuilderService: FormBuilderService,
private formBuilderService: FormBuilderService, protected translateService: TranslateService,
private translateService: TranslateService, protected notificationsService: NotificationsService,
private notificationsService: NotificationsService, protected route: ActivatedRoute,
private route: ActivatedRoute,
protected router: Router, protected router: Router,
private authorizationService: AuthorizationDataService, protected authorizationService: AuthorizationDataService,
private modalService: NgbModal, protected modalService: NgbModal,
public requestService: RequestService, public requestService: RequestService,
protected changeDetectorRef: ChangeDetectorRef, protected changeDetectorRef: ChangeDetectorRef,
public dsoNameService: DSONameService, 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(); this.initialisePage();
} }
initialisePage() { initialisePage() {
this.subs.push(this.route.params.subscribe((params) => { const groupNameModel = new DynamicInputModel({
if (params.groupId !== 'newGroup') { id: 'groupName',
this.setActiveGroup(params.groupId); label: this.translateService.instant(`${this.messagePrefix}.groupName`),
} name: 'groupName',
})); validators: {
this.canEdit$ = this.groupDataService.getActiveGroup().pipe( required: null,
hasValueOperator(), },
switchMap((group: Group) => { required: true,
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({
id: 'groupName',
label: groupName,
name: 'groupName',
validators: {
required: null,
},
required: true,
});
this.groupCommunity = new DynamicInputModel({
id: 'groupCommunity',
label: groupCommunity,
name: 'groupCommunity',
required: false,
readOnly: true,
});
this.groupDescription = new DynamicTextAreaModel({
id: 'groupDescription',
label: groupDescription,
name: 'groupDescription',
required: false,
spellCheck: environment.form.spellCheck,
});
this.formModel = [
this.groupName,
this.groupDescription,
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
if (!!this.formGroup.controls.groupName) {
this.formGroup.controls.groupName.setAsyncValidators(ValidateGroupExists.createValidator(this.groupDataService));
this.groupNameValueChangeSubscribe = this.groupName.valueChanges.pipe(debounceTime(300)).subscribe(() => {
this.changeDetectorRef.detectChanges();
});
}
this.subs.push(
observableCombineLatest([
this.groupDataService.getActiveGroup(),
this.canEdit$,
this.groupDataService.getActiveGroup()
.pipe(filter((activeGroup) => hasValue(activeGroup)),switchMap((activeGroup) => this.getLinkedDSO(activeGroup).pipe(getFirstSucceededRemoteDataPayload())))
]).subscribe(([activeGroup, canEdit, linkedObject]) => {
if (activeGroup != null) {
// Disable group name exists validator
this.formGroup.controls.groupName.clearAsyncValidators();
this.groupBeingEdited = activeGroup;
if (linkedObject?.name) {
if (!this.formGroup.controls.groupCommunity) {
this.formBuilderService.insertFormGroupControl(1, this.formGroup, this.formModel, this.groupCommunity);
this.formGroup.patchValue({
groupName: activeGroup.name,
groupCommunity: linkedObject?.name ?? '',
groupDescription: activeGroup.firstMetadataValue('dc.description'),
});
}
} else {
this.formModel = [
this.groupName,
this.groupDescription,
];
this.formGroup.patchValue({
groupName: activeGroup.name,
groupDescription: activeGroup.firstMetadataValue('dc.description'),
});
}
setTimeout(() => {
if (!canEdit || activeGroup.permanent) {
this.formGroup.disable();
}
}, 200);
}
})
);
}); });
const groupCommunityModel = new DynamicInputModel({
id: 'groupCommunity',
label: this.translateService.instant(`${this.messagePrefix}.groupCommunity`),
name: 'groupCommunity',
required: false,
readOnly: true,
});
const groupDescriptionModel = new DynamicTextAreaModel({
id: 'groupDescription',
label: this.translateService.instant(`${this.messagePrefix}.groupDescription`),
name: 'groupDescription',
required: false,
spellCheck: environment.form.spellCheck,
});
this.formModel = [
groupNameModel,
groupDescriptionModel,
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.groupName = this.formGroup.get('groupName');
this.groupDescription = this.formGroup.get('groupDescription');
if (hasValue(this.groupName)) {
this.groupName.setAsyncValidators(ValidateGroupExists.createValidator(this.groupDataService));
this.groupNameValueChangeSubscribe = this.groupName.valueChanges.pipe(debounceTime(300)).subscribe(() => {
this.changeDetectorRef.detectChanges();
});
}
this.subs.push(
observableCombineLatest([
this.activeGroup$,
this.canEdit$,
this.activeGroupLinkedDSO$,
]).subscribe(([activeGroup, canEdit, linkedObject]) => {
if (activeGroup != null) {
// Disable group name exists validator
this.formGroup.controls.groupName.clearAsyncValidators();
if (isNotEmpty(linkedObject?.name)) {
if (!this.formGroup.controls.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 = [
groupNameModel,
groupDescriptionModel,
];
this.formGroup.patchValue({
groupName: activeGroup.name,
groupDescription: activeGroup.firstMetadataValue('dc.description'),
});
}
if (!canEdit || activeGroup.permanent) {
this.formGroup.disable();
} else {
this.formGroup.enable();
}
}
})
);
} }
/** /**
@@ -275,25 +277,22 @@ export class GroupFormComponent implements OnInit, OnDestroy {
* Emit the updated/created eperson using the EventEmitter submitForm * Emit the updated/created eperson using the EventEmitter submitForm
*/ */
onSubmit() { onSubmit() {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe( this.activeGroup$.pipe(take(1)).subscribe((group: Group) => {
(group: Group) => { if (group === null) {
const values = { this.createNewGroup({
name: this.groupName.value, name: this.groupName.value,
metadata: { metadata: {
'dc.description': [ 'dc.description': [
{ {
value: this.groupDescription.value value: this.groupDescription.value,
} },
] ],
}, },
}; });
if (group === null) { } else {
this.createNewGroup(values); this.editGroup(group);
} else {
this.editGroup(group);
}
} }
); });
} }
/** /**
@@ -399,7 +398,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
* @param groupSelfLink SelfLink of group to set as active * @param groupSelfLink SelfLink of group to set as active
*/ */
setActiveGroupWithLink(groupSelfLink: string) { setActiveGroupWithLink(groupSelfLink: string) {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => { this.activeGroup$.pipe(take(1)).subscribe((activeGroup: Group) => {
if (activeGroup === null) { if (activeGroup === null) {
this.groupDataService.cancelEditGroup(); this.groupDataService.cancelEditGroup();
this.groupDataService.findByHref(groupSelfLink, false, false, followLink('subgroups'), followLink('epersons'), followLink('object')) this.groupDataService.findByHref(groupSelfLink, false, false, followLink('subgroups'), followLink('epersons'), followLink('object'))
@@ -418,7 +417,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. * It'll either show a success or error message depending on whether the delete was successful or not.
*/ */
delete() { delete() {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((group: Group) => { this.activeGroup$.pipe(take(1)).subscribe((group: Group) => {
const modalRef = this.modalService.open(ConfirmationModalComponent); const modalRef = this.modalService.open(ConfirmationModalComponent);
modalRef.componentInstance.dso = group; modalRef.componentInstance.dso = group;
modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-group.modal.header'; modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-group.modal.header';
@@ -462,52 +461,38 @@ export class GroupFormComponent implements OnInit, OnDestroy {
} }
/** /**
* Check if group has a linked object (community or collection linked to a workflow group) * Get the active {@link Group}'s linked object if it has one ({@link Community} or {@link Collection} linked to a
* @param group * workflow group)
*/ */
hasLinkedDSO(group: Group): Observable<boolean> { getActiveGroupLinkedDSO(): Observable<DSpaceObject> {
if (hasValue(group) && hasValue(group._links.object.href)) { return this.activeGroup$.pipe(
return this.getLinkedDSO(group).pipe( hasValueOperator(),
map((rd: RemoteData<DSpaceObject>) => { switchMap((group: Group) => {
return hasValue(rd) && hasValue(rd.payload); if (group.object === undefined) {
}), return this.dSpaceObjectDataService.findByHref(group._links.object.href);
catchError(() => observableOf(false)), }
); return group.object;
} }),
getAllCompletedRemoteData(),
getRemoteDataPayload(),
);
} }
/** /**
* Get group's linked object if it has one (community or collection linked to a workflow group) * Get the route to the edit roles tab of the active {@link Group}'s linked object (community or collection linked
* @param group * to a workflow group) if it has one
*/ */
getLinkedDSO(group: Group): Observable<RemoteData<DSpaceObject>> { getLinkedEditRolesRoute(): Observable<string> {
if (hasValue(group) && hasValue(group._links.object.href)) { return this.activeGroupLinkedDSO$.pipe(
if (group.object === undefined) { hasValueOperator(),
return this.dSpaceObjectDataService.findByHref(group._links.object.href); map((dso: DSpaceObject) => {
} switch ((dso as any).type) {
return group.object; case Community.type.value:
} return getCommunityEditRolesRoute(dso.id);
} case Collection.type.value:
return getCollectionEditRolesRoute(dso.id);
/** }
* 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 );
*/
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;
switch ((dso as any).type) {
case Community.type.value:
return getCommunityEditRolesRoute(rd.payload.id);
case Collection.type.value:
return getCollectionEditRolesRoute(rd.payload.id);
}
}
})
);
}
} }
} }

View File

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

View File

@@ -16,8 +16,7 @@ import { NotificationsServiceStub } from '../../../shared/testing/notifications-
import { BitstreamFormat } from '../../../core/shared/bitstream-format.model'; import { BitstreamFormat } from '../../../core/shared/bitstream-format.model';
import { BitstreamFormatSupportLevel } from '../../../core/shared/bitstream-format-support-level'; import { BitstreamFormatSupportLevel } from '../../../core/shared/bitstream-format-support-level';
import { XSRFService } from '../../../core/xsrf/xsrf.service'; import { XSRFService } from '../../../core/xsrf/xsrf.service';
import { cold, getTestScheduler, hot } from 'jasmine-marbles'; import { hot } from 'jasmine-marbles';
import { TestScheduler } from 'rxjs/testing';
import { import {
createNoContentRemoteDataObject$, createNoContentRemoteDataObject$,
createSuccessfulRemoteDataObject, createSuccessfulRemoteDataObject,
@@ -32,7 +31,6 @@ describe('BitstreamFormatsComponent', () => {
let comp: BitstreamFormatsComponent; let comp: BitstreamFormatsComponent;
let fixture: ComponentFixture<BitstreamFormatsComponent>; let fixture: ComponentFixture<BitstreamFormatsComponent>;
let bitstreamFormatService; let bitstreamFormatService;
let scheduler: TestScheduler;
let notificationsServiceStub; let notificationsServiceStub;
let paginationService; let paginationService;
@@ -87,8 +85,6 @@ describe('BitstreamFormatsComponent', () => {
const initAsync = () => { const initAsync = () => {
notificationsServiceStub = new NotificationsServiceStub(); notificationsServiceStub = new NotificationsServiceStub();
scheduler = getTestScheduler();
bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', { bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', {
findAll: observableOf(mockFormatsRD), findAll: observableOf(mockFormatsRD),
find: createSuccessfulRemoteDataObject$(mockFormatsList[0]), find: createSuccessfulRemoteDataObject$(mockFormatsList[0]),
@@ -180,17 +176,17 @@ describe('BitstreamFormatsComponent', () => {
beforeEach(waitForAsync(initAsync)); beforeEach(waitForAsync(initAsync));
beforeEach(initBeforeEach); beforeEach(initBeforeEach);
it('should return an observable of true if the provided bistream is in the list returned by the service', () => { it('should return an observable of true if the provided bistream is in the list returned by the service', () => {
const result = comp.isSelected(bitstreamFormat1); comp.selectedBitstreamFormatIDs().subscribe((selectedBitstreamFormatIDs: string[]) => {
expect(selectedBitstreamFormatIDs).toContain(bitstreamFormat1.id);
expect(result).toBeObservable(cold('b', { b: true })); });
}); });
it('should return an observable of false if the provided bistream is not in the list returned by the service', () => { it('should return an observable of false if the provided bistream is not in the list returned by the service', () => {
const format = new BitstreamFormat(); const format = new BitstreamFormat();
format.uuid = 'new'; format.uuid = 'new';
const result = comp.isSelected(format); comp.selectedBitstreamFormatIDs().subscribe((selectedBitstreamFormatIDs: string[]) => {
expect(selectedBitstreamFormatIDs).not.toContain(format.id);
expect(result).toBeObservable(cold('b', { b: false })); });
}); });
}); });
@@ -216,8 +212,6 @@ describe('BitstreamFormatsComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
notificationsServiceStub = new NotificationsServiceStub(); notificationsServiceStub = new NotificationsServiceStub();
scheduler = getTestScheduler();
bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', { bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', {
findAll: observableOf(mockFormatsRD), findAll: observableOf(mockFormatsRD),
find: createSuccessfulRemoteDataObject$(mockFormatsList[0]), find: createSuccessfulRemoteDataObject$(mockFormatsList[0]),
@@ -265,8 +259,6 @@ describe('BitstreamFormatsComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
notificationsServiceStub = new NotificationsServiceStub(); notificationsServiceStub = new NotificationsServiceStub();
scheduler = getTestScheduler();
bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', { bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', {
findAll: observableOf(mockFormatsRD), findAll: observableOf(mockFormatsRD),
find: createSuccessfulRemoteDataObject$(mockFormatsList[0]), find: createSuccessfulRemoteDataObject$(mockFormatsList[0]),

View File

@@ -1,5 +1,5 @@
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Component, OnDestroy, OnInit } from '@angular/core';
import { combineLatest as observableCombineLatest, Observable} from 'rxjs'; import { Observable} from 'rxjs';
import { RemoteData } from '../../../core/data/remote-data'; import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list.model'; import { PaginatedList } from '../../../core/data/paginated-list.model';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
@@ -7,7 +7,6 @@ import { BitstreamFormat } from '../../../core/shared/bitstream-format.model';
import { BitstreamFormatDataService } from '../../../core/data/bitstream-format-data.service'; import { BitstreamFormatDataService } from '../../../core/data/bitstream-format-data.service';
import { map, mergeMap, switchMap, take, toArray } from 'rxjs/operators'; import { map, mergeMap, switchMap, take, toArray } from 'rxjs/operators';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { NoContent } from '../../../core/shared/NoContent.model'; import { NoContent } from '../../../core/shared/NoContent.model';
import { PaginationService } from '../../../core/pagination/pagination.service'; import { PaginationService } from '../../../core/pagination/pagination.service';
@@ -26,7 +25,12 @@ export class BitstreamFormatsComponent implements OnInit, OnDestroy {
/** /**
* A paginated list of bitstream formats to be shown on the page * 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 * The current pagination configuration for the page
@@ -39,7 +43,6 @@ export class BitstreamFormatsComponent implements OnInit, OnDestroy {
}); });
constructor(private notificationsService: NotificationsService, constructor(private notificationsService: NotificationsService,
private router: Router,
private translateService: TranslateService, private translateService: TranslateService,
private bitstreamFormatService: BitstreamFormatDataService, private bitstreamFormatService: BitstreamFormatDataService,
private paginationService: PaginationService, private paginationService: PaginationService,
@@ -94,14 +97,11 @@ export class BitstreamFormatsComponent implements OnInit, OnDestroy {
} }
/** /**
* Checks whether a given bitstream format is selected in the list (checkbox) * Returns the list of all the bitstream formats that are selected in the list (checkbox)
* @param bitstreamFormat
*/ */
isSelected(bitstreamFormat: BitstreamFormat): Observable<boolean> { selectedBitstreamFormatIDs(): Observable<string[]> {
return this.bitstreamFormatService.getSelectedBitstreamFormats().pipe( return this.bitstreamFormatService.getSelectedBitstreamFormats().pipe(
map((bitstreamFormats: BitstreamFormat[]) => { map((bitstreamFormats: BitstreamFormat[]) => bitstreamFormats.map((selectedFormat) => selectedFormat.id)),
return bitstreamFormats.find((selectedFormat) => selectedFormat.id === bitstreamFormat.id) != null;
})
); );
} }
@@ -125,27 +125,23 @@ export class BitstreamFormatsComponent implements OnInit, OnDestroy {
const prefix = 'admin.registries.bitstream-formats.delete'; const prefix = 'admin.registries.bitstream-formats.delete';
const suffix = success ? 'success' : 'failure'; const suffix = success ? 'success' : 'failure';
const messages = observableCombineLatest( const head: string = this.translateService.instant(`${prefix}.${suffix}.head`);
this.translateService.get(`${prefix}.${suffix}.head`), const content: string = this.translateService.instant(`${prefix}.${suffix}.amount`, { amount: amount });
this.translateService.get(`${prefix}.${suffix}.amount`, {amount: amount})
);
messages.subscribe(([head, content]) => {
if (success) { if (success) {
this.notificationsService.success(head, content); this.notificationsService.success(head, content);
} else { } else {
this.notificationsService.error(head, content); this.notificationsService.error(head, content);
} }
});
} }
ngOnInit(): void { 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) => { switchMap((findListOptions: FindListOptions) => {
return this.bitstreamFormatService.findAll(findListOptions); return this.bitstreamFormatService.findAll(findListOptions);
}) })
); );
this.selectedBitstreamFormatIDs$ = this.selectedBitstreamFormatIDs();
} }

View File

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

View File

@@ -1,7 +1,6 @@
import { MetadataRegistryComponent } from './metadata-registry.component'; import { MetadataRegistryComponent } from './metadata-registry.component';
import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing';
import { of as observableOf } from 'rxjs'; import { of as observableOf } from 'rxjs';
import { buildPaginatedList } from '../../../core/data/paginated-list.model';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@@ -15,18 +14,21 @@ import { HostWindowService } from '../../../shared/host-window.service';
import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { RestResponse } from '../../../core/cache/response.models';
import { MetadataSchema } from '../../../core/metadata/metadata-schema.model'; import { MetadataSchema } from '../../../core/metadata/metadata-schema.model';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { PaginationService } from '../../../core/pagination/pagination.service'; import { PaginationService } from '../../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub'; import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
import { RegistryServiceStub } from '../../../shared/testing/registry.service.stub';
import { createPaginatedList } from '../../../shared/testing/utils.test';
describe('MetadataRegistryComponent', () => { describe('MetadataRegistryComponent', () => {
let comp: MetadataRegistryComponent; let comp: MetadataRegistryComponent;
let fixture: ComponentFixture<MetadataRegistryComponent>; let fixture: ComponentFixture<MetadataRegistryComponent>;
let registryService: RegistryService;
let paginationService; let paginationService: PaginationServiceStub;
const mockSchemasList = [ let registryService: RegistryServiceStub;
const mockSchemasList: MetadataSchema[] = [
{ {
id: 1, id: 1,
_links: { _links: {
@@ -47,32 +49,18 @@ describe('MetadataRegistryComponent', () => {
prefix: 'mock', prefix: 'mock',
namespace: 'http://dspace.org/mockschema' namespace: 'http://dspace.org/mockschema'
} }
]; ] as MetadataSchema[];
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();
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
paginationService = new PaginationServiceStub();
registryService = new RegistryServiceStub();
spyOn(registryService, 'getMetadataSchemas').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(mockSchemasList)));
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [MetadataRegistryComponent, PaginationComponent, EnumKeysPipe], declarations: [MetadataRegistryComponent, PaginationComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: RegistryService, useValue: registryServiceStub }, { provide: RegistryService, useValue: registryService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: PaginationService, useValue: paginationService }, { provide: PaginationService, useValue: paginationService },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() } { provide: NotificationsService, useValue: new NotificationsServiceStub() }
@@ -123,7 +111,7 @@ describe('MetadataRegistryComponent', () => {
})); }));
it('should cancel editing the selected schema when clicked again', waitForAsync(() => { 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'); spyOn(registryService, 'cancelEditMetadataSchema');
row.click(); row.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -138,7 +126,7 @@ describe('MetadataRegistryComponent', () => {
beforeEach(() => { beforeEach(() => {
spyOn(registryService, 'deleteMetadataSchema').and.callThrough(); 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(); comp.deleteSchemas();
fixture.detectChanges(); fixture.detectChanges();
}); });

View File

@@ -1,13 +1,11 @@
import { Component } from '@angular/core'; import { Component, OnInit, OnDestroy } from '@angular/core';
import { RegistryService } from '../../../core/registry/registry.service'; import { RegistryService } from '../../../core/registry/registry.service';
import { BehaviorSubject, combineLatest as observableCombineLatest, Observable, zip } from 'rxjs'; import { BehaviorSubject, Observable, zip, Subscription } from 'rxjs';
import { RemoteData } from '../../../core/data/remote-data'; import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list.model'; import { PaginatedList } from '../../../core/data/paginated-list.model';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { filter, map, switchMap, take } from 'rxjs/operators'; import { filter, map, switchMap, take } from 'rxjs/operators';
import { hasValue } from '../../../shared/empty.util';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { MetadataSchema } from '../../../core/metadata/metadata-schema.model'; import { MetadataSchema } from '../../../core/metadata/metadata-schema.model';
import { toFindListOptions } from '../../../shared/pagination/pagination.utils'; import { toFindListOptions } from '../../../shared/pagination/pagination.utils';
@@ -24,13 +22,23 @@ import { PaginationService } from '../../../core/pagination/pagination.service';
* A component used for managing all existing metadata schemas within the repository. * A component used for managing all existing metadata schemas within the repository.
* The admin can create, edit or delete metadata schemas here. * The admin can create, edit or delete metadata schemas here.
*/ */
export class MetadataRegistryComponent { export class MetadataRegistryComponent implements OnDestroy, OnInit {
/** /**
* A list of all the current metadata schemas within the repository * A list of all the current metadata schemas within the repository
*/ */
metadataSchemas: Observable<RemoteData<PaginatedList<MetadataSchema>>>; 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 * Pagination config used to display the list of metadata schemas
*/ */
@@ -40,15 +48,25 @@ export class MetadataRegistryComponent {
}); });
/** /**
* 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); needsUpdate$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);
constructor(private registryService: RegistryService, subscriptions: Subscription[] = [];
private notificationsService: NotificationsService,
private router: Router, constructor(
private paginationService: PaginationService, protected registryService: RegistryService,
private translateService: TranslateService) { 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(); this.updateSchemas();
} }
@@ -77,30 +95,13 @@ export class MetadataRegistryComponent {
* @param schema * @param schema
*/ */
editSchema(schema: MetadataSchema) { editSchema(schema: MetadataSchema) {
this.getActiveSchema().pipe(take(1)).subscribe((activeSchema) => { this.subscriptions.push(this.activeMetadataSchema$.pipe(take(1)).subscribe((activeSchema: MetadataSchema) => {
if (schema === activeSchema) { if (schema === activeSchema) {
this.registryService.cancelEditMetadataSchema(); this.registryService.cancelEditMetadataSchema();
} else { } else {
this.registryService.editMetadataSchema(schema); 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();
} }
/** /**
@@ -114,42 +115,25 @@ export class MetadataRegistryComponent {
this.registryService.deselectMetadataSchema(schema); 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 * Delete all the selected metadata schemas
*/ */
deleteSchemas() { deleteSchemas() {
this.registryService.getSelectedMetadataSchemas().pipe(take(1)).subscribe( this.subscriptions.push(this.selectedMetadataSchemaIDs$.pipe(
(schemas) => { take(1),
const tasks$ = []; switchMap((schemaIDs: number[]) => zip(schemaIDs.map((schemaID: number) => this.registryService.deleteMetadataSchema(schemaID).pipe(getFirstCompletedRemoteData())))),
for (const schema of schemas) { ).subscribe((responses: RemoteData<NoContent>[]) => {
if (hasValue(schema.id)) { const successResponses: RemoteData<NoContent>[] = responses.filter((response: RemoteData<NoContent>) => response.hasSucceeded);
tasks$.push(this.registryService.deleteMetadataSchema(schema.id).pipe(getFirstCompletedRemoteData())); const failedResponses: RemoteData<NoContent>[] = responses.filter((response: RemoteData<NoContent>) => response.hasFailed);
} if (successResponses.length > 0) {
} this.showNotification(true, successResponses.length);
zip(...tasks$).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) {
this.showNotification(true, successResponses.length);
}
if (failedResponses.length > 0) {
this.showNotification(false, failedResponses.length);
}
this.registryService.deselectAllMetadataSchema();
this.registryService.cancelEditMetadataSchema();
});
} }
); if (failedResponses.length > 0) {
this.showNotification(false, failedResponses.length);
}
this.registryService.deselectAllMetadataSchema();
this.registryService.cancelEditMetadataSchema();
}));
} }
/** /**
@@ -160,20 +144,20 @@ export class MetadataRegistryComponent {
showNotification(success: boolean, amount: number) { showNotification(success: boolean, amount: number) {
const prefix = 'admin.registries.schema.notification'; const prefix = 'admin.registries.schema.notification';
const suffix = success ? 'success' : 'failure'; const suffix = success ? 'success' : 'failure';
const messages = observableCombineLatest(
this.translateService.get(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`), const head: string = this.translateService.instant(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`);
this.translateService.get(`${prefix}.deleted.${suffix}`, {amount: amount}) const content: string = this.translateService.instant(`${prefix}.deleted.${suffix}`, {amount: amount});
);
messages.subscribe(([head, content]) => { if (success) {
if (success) { this.notificationsService.success(head, content);
this.notificationsService.success(head, content); } else {
} else { this.notificationsService.error(head, content);
this.notificationsService.error(head, content); }
}
});
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.paginationService.clearPagination(this.config.id); 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> <ng-template #createHeader>
<h2>{{messagePrefix + '.create' | translate}}</h2> <h2>{{messagePrefix + '.create' | translate}}</h2>

View File

@@ -1,6 +1,6 @@
import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing';
import { MetadataSchemaFormComponent } from './metadata-schema-form.component'; import { MetadataSchemaFormComponent } from './metadata-schema-form.component';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing'; import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
@@ -10,41 +10,26 @@ import { RegistryService } from '../../../../core/registry/registry.service';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service'; import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { of as observableOf } from 'rxjs'; import { of as observableOf } from 'rxjs';
import { MetadataSchema } from '../../../../core/metadata/metadata-schema.model'; import { MetadataSchema } from '../../../../core/metadata/metadata-schema.model';
import { RegistryServiceStub } from '../../../../shared/testing/registry.service.stub';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
describe('MetadataSchemaFormComponent', () => { describe('MetadataSchemaFormComponent', () => {
let component: MetadataSchemaFormComponent; let component: MetadataSchemaFormComponent;
let fixture: ComponentFixture<MetadataSchemaFormComponent>; let fixture: ComponentFixture<MetadataSchemaFormComponent>;
let registryService: RegistryService;
/* eslint-disable no-empty,@typescript-eslint/no-empty-function */ let registryService: RegistryServiceStub;
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 */
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
registryService = new RegistryServiceStub();
return TestBed.configureTestingModule({ return TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [MetadataSchemaFormComponent, EnumKeysPipe], declarations: [MetadataSchemaFormComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: RegistryService, useValue: registryServiceStub }, { provide: RegistryService, useValue: registryService },
{ provide: FormBuilderService, useValue: formBuilderServiceStub } { provide: FormBuilderService, useValue: getMockFormBuilderService() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents(); }).compileComponents();
})); }));
@@ -75,7 +60,7 @@ describe('MetadataSchemaFormComponent', () => {
describe('without an active schema', () => { describe('without an active schema', () => {
beforeEach(() => { beforeEach(() => {
spyOn(registryService, 'getActiveMetadataSchema').and.returnValue(observableOf(undefined)); component.activeMetadataSchema$ = observableOf(undefined);
component.onSubmit(); component.onSubmit();
fixture.detectChanges(); fixture.detectChanges();
}); });
@@ -94,7 +79,7 @@ describe('MetadataSchemaFormComponent', () => {
} as MetadataSchema); } as MetadataSchema);
beforeEach(() => { beforeEach(() => {
spyOn(registryService, 'getActiveMetadataSchema').and.returnValue(observableOf(expectedWithId)); component.activeMetadataSchema$ = observableOf(expectedWithId);
component.onSubmit(); component.onSubmit();
fixture.detectChanges(); fixture.detectChanges();
}); });

View File

@@ -8,10 +8,10 @@ import {
import { UntypedFormGroup } from '@angular/forms'; import { UntypedFormGroup } from '@angular/forms';
import { RegistryService } from '../../../../core/registry/registry.service'; import { RegistryService } from '../../../../core/registry/registry.service';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service'; import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { switchMap, take, tap } from 'rxjs/operators'; import { map, switchMap, take } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { Observable, combineLatest } from 'rxjs';
import { MetadataSchema } from '../../../../core/metadata/metadata-schema.model'; import { MetadataSchema } from '../../../../core/metadata/metadata-schema.model';
import { Subscription, Observable } from 'rxjs';
@Component({ @Component({
selector: 'ds-metadata-schema-form', selector: 'ds-metadata-schema-form',
@@ -73,64 +73,71 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
*/ */
@Output() submitForm: EventEmitter<any> = new EventEmitter(); @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() { ngOnInit() {
combineLatest([ this.name = new DynamicInputModel({
this.translateService.get(`${this.messagePrefix}.name`), id: 'name',
this.translateService.get(`${this.messagePrefix}.namespace`) label: this.translateService.instant(`${this.messagePrefix}.name`),
]).subscribe(([name, namespace]) => { name: 'name',
this.name = new DynamicInputModel({ validators: {
id: 'name', required: null,
label: name, pattern: '^[^. ,]*$',
name: 'name', maxLength: 32,
validators: { },
required: null, required: true,
pattern: '^[^. ,]*$', errorMessages: {
maxLength: 32, pattern: 'error.validation.metadata.name.invalid-pattern',
}, maxLength: 'error.validation.metadata.name.max-length',
required: true, },
errorMessages: {
pattern: 'error.validation.metadata.name.invalid-pattern',
maxLength: 'error.validation.metadata.name.max-length',
},
});
this.namespace = new DynamicInputModel({
id: 'namespace',
label: namespace,
name: 'namespace',
validators: {
required: null,
maxLength: 256,
},
required: true,
errorMessages: {
maxLength: 'error.validation.metadata.namespace.max-length',
},
});
this.formModel = [
new DynamicFormGroupModel(
{
id: 'metadatadataschemagroup',
group:[this.namespace, this.name]
})
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.registryService.getActiveMetadataSchema().subscribe((schema: MetadataSchema) => {
if (schema == null) {
this.clearFields();
} else {
this.formGroup.patchValue({
metadatadataschemagroup: {
name: schema.prefix,
namespace: schema.namespace,
},
});
this.name.disabled = true;
}
}); });
}); this.namespace = new DynamicInputModel({
id: 'namespace',
label: this.translateService.instant(`${this.messagePrefix}.namespace`),
name: 'namespace',
validators: {
required: null,
maxLength: 256,
},
required: true,
errorMessages: {
maxLength: 'error.validation.metadata.namespace.max-length',
},
});
this.formModel = [
new DynamicFormGroupModel(
{
id: 'metadatadataschemagroup',
group:[this.namespace, this.name]
})
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.activeMetadataSchema$ = this.registryService.getActiveMetadataSchema();
this.subscriptions.push(this.activeMetadataSchema$.subscribe((schema: MetadataSchema) => {
if (schema == null) {
this.clearFields();
} else {
this.formGroup.patchValue({
metadatadataschemagroup: {
name: schema.prefix,
namespace: schema.namespace,
},
});
this.name.disabled = true;
}
}));
} }
/** /**
@@ -147,48 +154,29 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
* Emit the updated/created schema using the EventEmitter submitForm * Emit the updated/created schema using the EventEmitter submitForm
*/ */
onSubmit(): void { onSubmit(): void {
this.registryService this.activeMetadataSchema$.pipe(
.getActiveMetadataSchema() take(1),
.pipe( switchMap((schema: MetadataSchema) => {
take(1), const metadataValues = {
switchMap((schema: MetadataSchema) => { prefix: this.name.value,
const metadataValues = { namespace: this.namespace.value,
prefix: this.name.value, };
namespace: this.namespace.value, if (schema == null) {
}; return this.registryService.createOrUpdateMetadataSchema(Object.assign(new MetadataSchema(), metadataValues));
} else {
let createOrUpdate$: Observable<MetadataSchema>; return this.registryService.createOrUpdateMetadataSchema(Object.assign(new MetadataSchema(), schema, {
namespace: metadataValues.namespace,
if (schema == null) { }));
createOrUpdate$ = }
this.registryService.createOrUpdateMetadataSchema( }),
Object.assign(new MetadataSchema(), metadataValues) switchMap((updatedOrCreatedSchema: MetadataSchema) => this.registryService.clearMetadataSchemaRequests().pipe(
); map(() => updatedOrCreatedSchema),
} else { )),
const updatedSchema = Object.assign( ).subscribe((updatedOrCreatedSchema: MetadataSchema) => {
new MetadataSchema(), this.submitForm.emit(updatedOrCreatedSchema);
schema, this.clearFields();
{ this.registryService.cancelEditMetadataSchema();
namespace: metadataValues.namespace, });
}
);
createOrUpdate$ =
this.registryService.createOrUpdateMetadataSchema(
updatedSchema
);
}
return createOrUpdate$;
}),
tap(() => {
this.registryService.clearMetadataSchemaRequests().subscribe();
})
)
.subscribe((updatedOrCreatedSchema: MetadataSchema) => {
this.submitForm.emit(updatedOrCreatedSchema);
this.clearFields();
this.registryService.cancelEditMetadataSchema();
});
} }
/** /**
@@ -204,5 +192,6 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
*/ */
ngOnDestroy(): void { ngOnDestroy(): void {
this.onCancel(); this.onCancel();
this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe());
} }
} }

View File

@@ -9,14 +9,17 @@ import { TranslateModule } from '@ngx-translate/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { EnumKeysPipe } from '../../../../shared/utils/enum-keys-pipe'; import { EnumKeysPipe } from '../../../../shared/utils/enum-keys-pipe';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service'; import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { MetadataField } from '../../../../core/metadata/metadata-field.model'; import { MetadataField } from '../../../../core/metadata/metadata-field.model';
import { MetadataSchema } from '../../../../core/metadata/metadata-schema.model'; import { MetadataSchema } from '../../../../core/metadata/metadata-schema.model';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
import { RegistryServiceStub } from '../../../../shared/testing/registry.service.stub';
describe('MetadataFieldFormComponent', () => { describe('MetadataFieldFormComponent', () => {
let component: MetadataFieldFormComponent; let component: MetadataFieldFormComponent;
let fixture: ComponentFixture<MetadataFieldFormComponent>; let fixture: ComponentFixture<MetadataFieldFormComponent>;
let registryService: RegistryService;
let registryService: RegistryServiceStub;
const metadataSchema = Object.assign(new MetadataSchema(), { const metadataSchema = Object.assign(new MetadataSchema(), {
id: 1, id: 1,
@@ -24,38 +27,17 @@ describe('MetadataFieldFormComponent', () => {
prefix: 'fake' 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(() => { beforeEach(waitForAsync(() => {
registryService = new RegistryServiceStub();
return TestBed.configureTestingModule({ return TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [MetadataFieldFormComponent, EnumKeysPipe], declarations: [MetadataFieldFormComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: RegistryService, useValue: registryServiceStub }, { provide: RegistryService, useValue: registryService },
{ provide: FormBuilderService, useValue: formBuilderServiceStub } { provide: FormBuilderService, useValue: getMockFormBuilderService() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents(); }).compileComponents();
})); }));

View File

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

View File

@@ -4,7 +4,7 @@ import { of as observableOf } from 'rxjs';
import { buildPaginatedList } from '../../../core/data/paginated-list.model'; import { buildPaginatedList } from '../../../core/data/paginated-list.model';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { RegistryService } from '../../../core/registry/registry.service'; import { RegistryService } from '../../../core/registry/registry.service';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@@ -12,25 +12,28 @@ import { EnumKeysPipe } from '../../../shared/utils/enum-keys-pipe';
import { PaginationComponent } from '../../../shared/pagination/pagination.component'; import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { HostWindowServiceStub } from '../../../shared/testing/host-window-service.stub'; import { HostWindowServiceStub } from '../../../shared/testing/host-window-service.stub';
import { HostWindowService } from '../../../shared/host-window.service'; import { HostWindowService } from '../../../shared/host-window.service';
import { RouterStub } from '../../../shared/testing/router.stub';
import { RouterTestingModule } from '@angular/router/testing'; import { RouterTestingModule } from '@angular/router/testing';
import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub'; import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub'; import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { RestResponse } from '../../../core/cache/response.models';
import { MetadataSchema } from '../../../core/metadata/metadata-schema.model'; import { MetadataSchema } from '../../../core/metadata/metadata-schema.model';
import { MetadataField } from '../../../core/metadata/metadata-field.model'; import { MetadataField } from '../../../core/metadata/metadata-field.model';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { VarDirective } from '../../../shared/utils/var.directive'; import { VarDirective } from '../../../shared/utils/var.directive';
import { PaginationService } from '../../../core/pagination/pagination.service'; import { PaginationService } from '../../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub'; import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
import { RegistryServiceStub } from '../../../shared/testing/registry.service.stub';
describe('MetadataSchemaComponent', () => { describe('MetadataSchemaComponent', () => {
let comp: MetadataSchemaComponent; let comp: MetadataSchemaComponent;
let fixture: ComponentFixture<MetadataSchemaComponent>; let fixture: ComponentFixture<MetadataSchemaComponent>;
let registryService: RegistryService;
const mockSchemasList = [ let registryService: RegistryServiceStub;
let activatedRoute: ActivatedRouteStub;
let paginationService: PaginationServiceStub;
const mockSchemasList: MetadataSchema[] = [
{ {
id: 1, id: 1,
_links: { _links: {
@@ -51,8 +54,8 @@ describe('MetadataSchemaComponent', () => {
prefix: 'mock', prefix: 'mock',
namespace: 'http://dspace.org/mockschema' namespace: 'http://dspace.org/mockschema'
} }
]; ] as MetadataSchema[];
const mockFieldsList = [ const mockFieldsList: MetadataField[] = [
{ {
id: 1, id: 1,
_links: { _links: {
@@ -101,47 +104,29 @@ describe('MetadataSchemaComponent', () => {
scopeNote: null, scopeNote: null,
schema: createSuccessfulRemoteDataObject$(mockSchemasList[1]) schema: createSuccessfulRemoteDataObject$(mockSchemasList[1])
} }
]; ] as MetadataField[];
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 */
const schemaNameParam = 'mock'; const schemaNameParam = 'mock';
const activatedRouteStub = Object.assign(new ActivatedRouteStub(), {
params: observableOf({
schemaName: schemaNameParam
})
});
const paginationService = new PaginationServiceStub();
beforeEach(waitForAsync(() => { 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({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [MetadataSchemaComponent, PaginationComponent, EnumKeysPipe, VarDirective], declarations: [MetadataSchemaComponent, PaginationComponent, EnumKeysPipe, VarDirective],
providers: [ providers: [
{ provide: RegistryService, useValue: registryServiceStub }, { provide: RegistryService, useValue: registryService },
{ provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: ActivatedRoute, useValue: activatedRoute },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: Router, useValue: new RouterStub() },
{ provide: PaginationService, useValue: paginationService }, { provide: PaginationService, useValue: paginationService },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() } { provide: NotificationsService, useValue: new NotificationsServiceStub() }
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents(); }).compileComponents();
})); }));
@@ -190,7 +175,7 @@ describe('MetadataSchemaComponent', () => {
})); }));
it('should cancel editing the selected field when clicked again', waitForAsync(() => { 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'); spyOn(registryService, 'cancelEditMetadataField');
row.click(); row.click();
fixture.detectChanges(); fixture.detectChanges();
@@ -205,7 +190,7 @@ describe('MetadataSchemaComponent', () => {
beforeEach(() => { beforeEach(() => {
spyOn(registryService, 'deleteMetadataField').and.callThrough(); 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(); comp.deleteFields();
fixture.detectChanges(); fixture.detectChanges();
}); });

View File

@@ -3,17 +3,16 @@ import { RegistryService } from '../../../core/registry/registry.service';
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { import {
BehaviorSubject, BehaviorSubject,
combineLatest as observableCombineLatest,
combineLatest, combineLatest,
Observable, Observable,
of as observableOf, of as observableOf,
zip zip,
Subscription,
} from 'rxjs'; } from 'rxjs';
import { RemoteData } from '../../../core/data/remote-data'; import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list.model'; import { PaginatedList } from '../../../core/data/paginated-list.model';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { map, switchMap, take } from 'rxjs/operators'; import { map, switchMap, take } from 'rxjs/operators';
import { hasValue } from '../../../shared/empty.util';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { MetadataField } from '../../../core/metadata/metadata-field.model'; import { MetadataField } from '../../../core/metadata/metadata-field.model';
@@ -32,7 +31,7 @@ import { PaginationService } from '../../../core/pagination/pagination.service';
* A component used for managing all existing metadata fields within the current metadata schema. * A component used for managing all existing metadata fields within the current metadata schema.
* The admin can create, edit or delete metadata fields here. * 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 * The metadata schema
*/ */
@@ -57,26 +56,33 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
*/ */
needsUpdate$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true); needsUpdate$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);
constructor(private registryService: RegistryService, /**
private route: ActivatedRoute, * The current {@link MetadataField} that is being edited
private notificationsService: NotificationsService, */
private paginationService: PaginationService, activeField$: Observable<MetadataField>;
private translateService: TranslateService) {
/**
* 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 { ngOnInit(): void {
this.route.params.subscribe((params) => { this.metadataSchema$ = this.registryService.getMetadataSchemaByPrefix(this.route.snapshot.params.schemaName).pipe(getFirstSucceededRemoteDataPayload());
this.initialize(params); this.activeField$ = this.registryService.getActiveMetadataField();
}); this.selectedMetadataFieldIDs$ = this.registryService.getSelectedMetadataFields().pipe(
} map((metadataFields: MetadataField[]) => metadataFields.map((metadataField: MetadataField) => metadataField.id)),
);
/**
* Initialize the component using the params within the url (schemaName)
* @param params
*/
initialize(params) {
this.metadataSchema$ = this.registryService.getMetadataSchemaByPrefix(params.schemaName).pipe(getFirstSucceededRemoteDataPayload());
this.updateFields(); this.updateFields();
} }
@@ -109,30 +115,13 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
* @param field * @param field
*/ */
editField(field: MetadataField) { editField(field: MetadataField) {
this.getActiveField().pipe(take(1)).subscribe((activeField) => { this.subscriptions.push(this.activeField$.pipe(take(1)).subscribe((activeField) => {
if (field === activeField) { if (field === activeField) {
this.registryService.cancelEditMetadataField(); this.registryService.cancelEditMetadataField();
} else { } else {
this.registryService.editMetadataField(field); 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();
} }
/** /**
@@ -146,42 +135,25 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
this.registryService.deselectMetadataField(field); 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 * Delete all the selected metadata fields
*/ */
deleteFields() { deleteFields() {
this.registryService.getSelectedMetadataFields().pipe(take(1)).subscribe( this.subscriptions.push(this.selectedMetadataFieldIDs$.pipe(
(fields) => { take(1),
const tasks$ = []; switchMap((fieldIDs) => zip(fieldIDs.map((fieldID) => this.registryService.deleteMetadataField(fieldID).pipe(getFirstCompletedRemoteData())))),
for (const field of fields) { ).subscribe((responses: RemoteData<NoContent>[]) => {
if (hasValue(field.id)) { const successResponses = responses.filter((response: RemoteData<NoContent>) => response.hasSucceeded);
tasks$.push(this.registryService.deleteMetadataField(field.id).pipe(getFirstCompletedRemoteData())); const failedResponses = responses.filter((response: RemoteData<NoContent>) => response.hasFailed);
} if (successResponses.length > 0) {
} this.showNotification(true, successResponses.length);
zip(...tasks$).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) {
this.showNotification(true, successResponses.length);
}
if (failedResponses.length > 0) {
this.showNotification(false, failedResponses.length);
}
this.registryService.deselectAllMetadataField();
this.registryService.cancelEditMetadataField();
});
} }
); if (failedResponses.length > 0) {
this.showNotification(false, failedResponses.length);
}
this.registryService.deselectAllMetadataField();
this.registryService.cancelEditMetadataField();
}));
} }
/** /**
@@ -192,21 +164,19 @@ export class MetadataSchemaComponent implements OnInit, OnDestroy {
showNotification(success: boolean, amount: number) { showNotification(success: boolean, amount: number) {
const prefix = 'admin.registries.schema.notification'; const prefix = 'admin.registries.schema.notification';
const suffix = success ? 'success' : 'failure'; const suffix = success ? 'success' : 'failure';
const messages = observableCombineLatest([ const head = this.translateService.instant(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`);
this.translateService.get(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`), const content = this.translateService.instant(`${prefix}.field.deleted.${suffix}`, { amount: amount });
this.translateService.get(`${prefix}.field.deleted.${suffix}`, { amount: amount }) if (success) {
]); this.notificationsService.success(head, content);
messages.subscribe(([head, content]) => { } else {
if (success) { this.notificationsService.error(head, content);
this.notificationsService.success(head, content); }
} else {
this.notificationsService.error(head, content);
}
});
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.paginationService.clearPagination(this.config.id); this.paginationService.clearPagination(this.config.id);
this.registryService.deselectAllMetadataField(); this.registryService.deselectAllMetadataField();
this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe());
} }
} }

View File

@@ -8,11 +8,11 @@ import { RemoteData } from '../../core/data/remote-data';
import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { DSpaceObject } from '../../core/shared/dspace-object.model';
@Component({ @Component({
selector: 'ds-collection-authorizations', selector: 'ds-bitstream-authorizations',
templateUrl: './bitstream-authorizations.component.html', templateUrl: './bitstream-authorizations.component.html',
}) })
/** /**
* Component that handles the Collection Authorizations * Component that handles the Bitstream Authorizations
*/ */
export class BitstreamAuthorizationsComponent<TDomain extends DSpaceObject> implements OnInit { export class BitstreamAuthorizationsComponent<TDomain extends DSpaceObject> implements OnInit {

View File

@@ -1,8 +1,7 @@
import { ChangeDetectorRef, Component, Inject } from '@angular/core'; import { ChangeDetectorRef, Component, Inject } from '@angular/core';
import { import {
BrowseByMetadataPageComponent, BrowseByMetadataPageComponent,
browseParamsToOptions, browseParamsToOptions
getBrowseSearchOptions
} from '../browse-by-metadata-page/browse-by-metadata-page.component'; } from '../browse-by-metadata-page/browse-by-metadata-page.component';
import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { combineLatest as observableCombineLatest, Observable } from 'rxjs';
import { hasValue, isNotEmpty } from '../../shared/empty.util'; import { hasValue, isNotEmpty } from '../../shared/empty.util';
@@ -11,7 +10,7 @@ import { BrowseService } from '../../core/browse/browse.service';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { StartsWithType } from '../../shared/starts-with/starts-with-decorator'; import { StartsWithType } from '../../shared/starts-with/starts-with-decorator';
import { PaginationService } from '../../core/pagination/pagination.service'; import { PaginationService } from '../../core/pagination/pagination.service';
import { map } from 'rxjs/operators'; import { map, take } from 'rxjs/operators';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { isValidDate } from '../../shared/date.util'; import { isValidDate } from '../../shared/date.util';
@@ -52,15 +51,16 @@ export class BrowseByDatePageComponent extends BrowseByMetadataPageComponent {
ngOnInit(): void { ngOnInit(): void {
const sortConfig = new SortOptions('default', SortDirection.ASC); const sortConfig = new SortOptions('default', SortDirection.ASC);
this.startsWithType = StartsWithType.date; 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.currentPagination$ = this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig);
this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig); this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig);
this.subs.push( this.subs.push(
observableCombineLatest([this.route.params, this.route.queryParams, this.route.data, observableCombineLatest(
this.currentPagination$, this.currentSort$]).pipe( [ this.route.params.pipe(take(1)),
map(([routeParams, queryParams, data, currentPage, currentSort]) => { this.route.queryParams,
return [Object.assign({}, routeParams, queryParams, data), currentPage, currentSort]; this.currentPagination$,
this.currentSort$]).pipe(
map(([routeParams, queryParams, currentPage, currentSort]) => {
return [Object.assign({}, routeParams, queryParams), currentPage, currentSort];
}) })
).subscribe(([params, currentPage, currentSort]: [Params, PaginationComponentOptions, SortOptions]) => { ).subscribe(([params, currentPage, currentSort]: [Params, PaginationComponentOptions, SortOptions]) => {
const metadataKeys = params.browseDefinition ? params.browseDefinition.metadataKeys : this.defaultMetadataKeys; const metadataKeys = params.browseDefinition ? params.browseDefinition.metadataKeys : this.defaultMetadataKeys;

View File

@@ -15,7 +15,7 @@ import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.serv
import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { StartsWithType } from '../../shared/starts-with/starts-with-decorator'; import { StartsWithType } from '../../shared/starts-with/starts-with-decorator';
import { PaginationService } from '../../core/pagination/pagination.service'; import { PaginationService } from '../../core/pagination/pagination.service';
import { filter, map, mergeMap } from 'rxjs/operators'; import { filter, map, mergeMap, take } from 'rxjs/operators';
import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { Bitstream } from '../../core/shared/bitstream.model'; import { Bitstream } from '../../core/shared/bitstream.model';
import { Collection } from '../../core/shared/collection.model'; import { Collection } from '../../core/shared/collection.model';
@@ -152,7 +152,11 @@ export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
this.currentPagination$ = this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig); this.currentPagination$ = this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig);
this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig); this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig);
this.subs.push( this.subs.push(
observableCombineLatest([this.route.params, this.route.queryParams, this.currentPagination$, this.currentSort$]).pipe( observableCombineLatest(
[ this.route.params.pipe(take(1)),
this.route.queryParams,
this.currentPagination$,
this.currentSort$]).pipe(
map(([routeParams, queryParams, currentPage, currentSort]) => { map(([routeParams, queryParams, currentPage, currentSort]) => {
return [Object.assign({}, routeParams, queryParams),currentPage,currentSort]; return [Object.assign({}, routeParams, queryParams),currentPage,currentSort];
}) })

View File

@@ -4,13 +4,13 @@ import { ActivatedRoute, Params, Router } from '@angular/router';
import { hasValue } from '../../shared/empty.util'; import { hasValue } from '../../shared/empty.util';
import { import {
BrowseByMetadataPageComponent, BrowseByMetadataPageComponent,
browseParamsToOptions, getBrowseSearchOptions browseParamsToOptions
} from '../browse-by-metadata-page/browse-by-metadata-page.component'; } from '../browse-by-metadata-page/browse-by-metadata-page.component';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { BrowseService } from '../../core/browse/browse.service'; import { BrowseService } from '../../core/browse/browse.service';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { PaginationService } from '../../core/pagination/pagination.service'; import { PaginationService } from '../../core/pagination/pagination.service';
import { map } from 'rxjs/operators'; import { map, take } from 'rxjs/operators';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { AppConfig, APP_CONFIG } from '../../../config/app-config.interface'; import { AppConfig, APP_CONFIG } from '../../../config/app-config.interface';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
@@ -38,12 +38,10 @@ export class BrowseByTitlePageComponent extends BrowseByMetadataPageComponent {
ngOnInit(): void { ngOnInit(): void {
const sortConfig = new SortOptions('dc.title', SortDirection.ASC); 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.currentPagination$ = this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig);
this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig); this.currentSort$ = this.paginationService.getCurrentSort(this.paginationConfig.id, sortConfig);
this.subs.push( this.subs.push(
observableCombineLatest([this.route.params, this.route.queryParams, this.currentPagination$, this.currentSort$]).pipe( observableCombineLatest([this.route.params.pipe(take(1)), this.route.queryParams, this.currentPagination$, this.currentSort$]).pipe(
map(([routeParams, queryParams, currentPage, currentSort]) => { map(([routeParams, queryParams, currentPage, currentSort]) => {
return [Object.assign({}, routeParams, queryParams),currentPage,currentSort]; return [Object.assign({}, routeParams, queryParams),currentPage,currentSort];
}) })

View File

@@ -55,7 +55,6 @@ import { CommunityBreadcrumbResolver } from '../core/breadcrumbs/community-bread
resolve: { resolve: {
dso: CollectionPageResolver, dso: CollectionPageResolver,
breadcrumb: CollectionBreadcrumbResolver, breadcrumb: CollectionBreadcrumbResolver,
menu: DSOEditMenuResolver
}, },
runGuardsAndResolvers: 'always', runGuardsAndResolvers: 'always',
children: [ children: [
@@ -85,6 +84,9 @@ import { CommunityBreadcrumbResolver } from '../core/breadcrumbs/community-bread
path: '', path: '',
component: ThemedCollectionPageComponent, component: ThemedCollectionPageComponent,
pathMatch: 'full', pathMatch: 'full',
resolve: {
menu: DSOEditMenuResolver,
},
} }
], ],
data: { data: {

View File

@@ -28,7 +28,7 @@ import { AuthorizationDataService } from '../core/data/feature-authorization/aut
import { FeatureID } from '../core/data/feature-authorization/feature-id'; import { FeatureID } from '../core/data/feature-authorization/feature-id';
import { getCollectionPageRoute } from './collection-page-routing-paths'; import { getCollectionPageRoute } from './collection-page-routing-paths';
import { redirectOn4xx } from '../core/shared/authorized.operators'; import { redirectOn4xx } from '../core/shared/authorized.operators';
import { BROWSE_LINKS_TO_FOLLOW } from '../core/browse/browse.service'; import { getBrowseLinksToFollow } from '../core/browse/browse.service';
import { DSONameService } from '../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../core/breadcrumbs/dso-name.service';
import { APP_CONFIG, AppConfig } from '../../../src/config/app-config.interface'; import { APP_CONFIG, AppConfig } from '../../../src/config/app-config.interface';
@@ -115,7 +115,7 @@ export class CollectionPageComponent implements OnInit {
pagination: currentPagination, pagination: currentPagination,
sort: currentSort, sort: currentSort,
dsoTypes: [DSpaceObjectType.ITEM] dsoTypes: [DSpaceObjectType.ITEM]
}), null, true, true, ...BROWSE_LINKS_TO_FOLLOW) }), null, true, true, ...getBrowseLinksToFollow())
.pipe(toDSpaceObjectListRD()) as Observable<RemoteData<PaginatedList<Item>>>; .pipe(toDSpaceObjectListRD()) as Observable<RemoteData<PaginatedList<Item>>>;
}), }),
startWith(undefined) // Make sure switching pages shows loading component startWith(undefined) // Make sure switching pages shows loading component

View File

@@ -1,7 +1,7 @@
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-12 pb-4"> <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>
</div> </div>
<ds-collection-form (submitForm)="onSubmit($event)" <ds-collection-form (submitForm)="onSubmit($event)"

View File

@@ -48,7 +48,6 @@ import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.reso
resolve: { resolve: {
dso: CommunityPageResolver, dso: CommunityPageResolver,
breadcrumb: CommunityBreadcrumbResolver, breadcrumb: CommunityBreadcrumbResolver,
menu: DSOEditMenuResolver
}, },
runGuardsAndResolvers: 'always', runGuardsAndResolvers: 'always',
children: [ children: [
@@ -68,6 +67,9 @@ import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.reso
path: '', path: '',
component: ThemedCommunityPageComponent, component: ThemedCommunityPageComponent,
pathMatch: 'full', pathMatch: 'full',
resolve: {
menu: DSOEditMenuResolver,
},
} }
], ],
data: { data: {

View File

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

View File

@@ -4,7 +4,7 @@ import { ItemDataService } from '../data/item-data.service';
import { Item } from '../shared/item.model'; import { Item } from '../shared/item.model';
import { DSOBreadcrumbResolver } from './dso-breadcrumb.resolver'; import { DSOBreadcrumbResolver } from './dso-breadcrumb.resolver';
import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { ITEM_PAGE_LINKS_TO_FOLLOW } from '../../item-page/item.resolver'; import { getItemPageLinksToFollow } from '../../item-page/item.resolver';
/** /**
* The class that resolves the BreadcrumbConfig object for an Item * The class that resolves the BreadcrumbConfig object for an Item
@@ -23,6 +23,6 @@ export class ItemBreadcrumbResolver extends DSOBreadcrumbResolver<Item> {
* Requesting them as embeds will limit the number of requests * Requesting them as embeds will limit the number of requests
*/ */
get followLinks(): FollowLinkConfig<Item>[] { get followLinks(): FollowLinkConfig<Item>[] {
return ITEM_PAGE_LINKS_TO_FOLLOW; return getItemPageLinksToFollow();
} }
} }

View File

@@ -1,10 +1,8 @@
import { cold, getTestScheduler, hot } from 'jasmine-marbles'; import { cold, getTestScheduler, hot } from 'jasmine-marbles';
import { of as observableOf } from 'rxjs'; import { of as observableOf } from 'rxjs';
import { TestScheduler } from 'rxjs/testing'; import { TestScheduler } from 'rxjs/testing';
import { getMockRemoteDataBuildService } from '../../shared/mocks/remote-data-build.service.mock';
import { getMockRequestService } from '../../shared/mocks/request.service.mock'; import { getMockRequestService } from '../../shared/mocks/request.service.mock';
import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub'; import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
import { RequestService } from '../data/request.service'; import { RequestService } from '../data/request.service';
import { BrowseEntrySearchOptions } from './browse-entry-search-options.model'; import { BrowseEntrySearchOptions } from './browse-entry-search-options.model';
import { BrowseService } from './browse.service'; import { BrowseService } from './browse.service';
@@ -20,7 +18,6 @@ describe('BrowseService', () => {
let scheduler: TestScheduler; let scheduler: TestScheduler;
let service: BrowseService; let service: BrowseService;
let requestService: RequestService; let requestService: RequestService;
let rdbService: RemoteDataBuildService;
const browsesEndpointURL = 'https://rest.api/browses'; const browsesEndpointURL = 'https://rest.api/browses';
const halService: any = new HALEndpointServiceStub(browsesEndpointURL); const halService: any = new HALEndpointServiceStub(browsesEndpointURL);
@@ -118,7 +115,6 @@ describe('BrowseService', () => {
halService, halService,
browseDefinitionDataService, browseDefinitionDataService,
hrefOnlyDataService, hrefOnlyDataService,
rdbService
); );
} }
@@ -130,11 +126,9 @@ describe('BrowseService', () => {
beforeEach(() => { beforeEach(() => {
requestService = getMockRequestService(getRequestEntry$(true)); requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService(); service = initTestService();
spyOn(halService, 'getEndpoint').and spyOn(halService, 'getEndpoint').and
.returnValue(hot('--a-', { a: browsesEndpointURL })); .returnValue(hot('--a-', { a: browsesEndpointURL }));
spyOn(rdbService, 'buildList').and.callThrough();
}); });
it('should call BrowseDefinitionDataService to create the RemoteData Observable', () => { it('should call BrowseDefinitionDataService to create the RemoteData Observable', () => {
@@ -151,9 +145,7 @@ describe('BrowseService', () => {
beforeEach(() => { beforeEach(() => {
requestService = getMockRequestService(getRequestEntry$(true)); requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService(); service = initTestService();
spyOn(rdbService, 'buildList').and.callThrough();
}); });
describe('when getBrowseEntriesFor is called with a valid browse definition id', () => { describe('when getBrowseEntriesFor is called with a valid browse definition id', () => {
@@ -204,7 +196,6 @@ describe('BrowseService', () => {
describe('if getBrowseDefinitions fires', () => { describe('if getBrowseDefinitions fires', () => {
beforeEach(() => { beforeEach(() => {
requestService = getMockRequestService(getRequestEntry$(true)); requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService(); service = initTestService();
spyOn(service, 'getBrowseDefinitions').and spyOn(service, 'getBrowseDefinitions').and
.returnValue(hot('--a-', { .returnValue(hot('--a-', {
@@ -259,7 +250,6 @@ describe('BrowseService', () => {
describe('if getBrowseDefinitions doesn\'t fire', () => { describe('if getBrowseDefinitions doesn\'t fire', () => {
it('should return undefined', () => { it('should return undefined', () => {
requestService = getMockRequestService(getRequestEntry$(true)); requestService = getMockRequestService(getRequestEntry$(true));
rdbService = getMockRemoteDataBuildService();
service = initTestService(); service = initTestService();
spyOn(service, 'getBrowseDefinitions').and spyOn(service, 'getBrowseDefinitions').and
.returnValue(hot('----')); .returnValue(hot('----'));
@@ -277,9 +267,7 @@ describe('BrowseService', () => {
describe('getFirstItemFor', () => { describe('getFirstItemFor', () => {
beforeEach(() => { beforeEach(() => {
requestService = getMockRequestService(); requestService = getMockRequestService();
rdbService = getMockRemoteDataBuildService();
service = initTestService(); service = initTestService();
spyOn(rdbService, 'buildList').and.callThrough();
}); });
describe('when getFirstItemFor is called with a valid browse definition id', () => { describe('when getFirstItemFor is called with a valid browse definition id', () => {

View File

@@ -2,7 +2,6 @@ import { Injectable } from '@angular/core';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { distinctUntilChanged, map, startWith } from 'rxjs/operators'; import { distinctUntilChanged, map, startWith } from 'rxjs/operators';
import { hasValue, hasValueOperator, isEmpty, isNotEmpty } from '../../shared/empty.util'; import { hasValue, hasValueOperator, isEmpty, isNotEmpty } from '../../shared/empty.util';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
import { PaginatedList } from '../data/paginated-list.model'; import { PaginatedList } from '../data/paginated-list.model';
import { RemoteData } from '../data/remote-data'; import { RemoteData } from '../data/remote-data';
import { RequestService } from '../data/request.service'; import { RequestService } from '../data/request.service';
@@ -24,11 +23,18 @@ import { HrefOnlyDataService } from '../data/href-only-data.service';
import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { BrowseDefinitionDataService } from './browse-definition-data.service'; import { BrowseDefinitionDataService } from './browse-definition-data.service';
import { SortDirection } from '../cache/models/sort-options.model'; import { SortDirection } from '../cache/models/sort-options.model';
import { environment } from '../../../environments/environment';
export const BROWSE_LINKS_TO_FOLLOW: FollowLinkConfig<BrowseEntry | Item>[] = [ export function getBrowseLinksToFollow(): FollowLinkConfig<BrowseEntry | Item>[] {
followLink('thumbnail') const followLinks = [
]; followLink('thumbnail'),
];
if (environment.item.showAccessStatuses) {
followLinks.push(followLink('accessStatus'));
}
return followLinks;
}
/** /**
* The service handling all browse requests * The service handling all browse requests
@@ -55,7 +61,6 @@ export class BrowseService {
protected halService: HALEndpointService, protected halService: HALEndpointService,
private browseDefinitionDataService: BrowseDefinitionDataService, private browseDefinitionDataService: BrowseDefinitionDataService,
private hrefOnlyDataService: HrefOnlyDataService, private hrefOnlyDataService: HrefOnlyDataService,
private rdb: RemoteDataBuildService,
) { ) {
} }
@@ -105,7 +110,7 @@ export class BrowseService {
}) })
); );
if (options.fetchThumbnail ) { 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$); return this.hrefOnlyDataService.findListByHref<BrowseEntry>(href$);
} }
@@ -153,7 +158,7 @@ export class BrowseService {
}), }),
); );
if (options.fetchThumbnail) { 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$); return this.hrefOnlyDataService.findListByHref<Item>(href$);
} }

View File

@@ -166,20 +166,25 @@ export function objectCacheReducer(state = initialState, action: ObjectCacheActi
* the new state, with the object added, or overwritten. * the new state, with the object added, or overwritten.
*/ */
function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheAction): ObjectCacheState { 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] : []; const newAltLinks = hasValue(action.payload.alternativeLink) ? [action.payload.alternativeLink] : [];
return Object.assign({}, state, { if (hasValue(cacheLink)) {
[action.payload.objectToCache._links.self.href]: { return Object.assign({}, state, {
data: action.payload.objectToCache, [cacheLink]: {
timeCompleted: action.payload.timeCompleted, data: action.payload.objectToCache,
msToLive: action.payload.msToLive, timeCompleted: action.payload.timeCompleted,
requestUUIDs: [action.payload.requestUUID, ...(existing.requestUUIDs || [])], msToLive: action.payload.msToLive,
dependentRequestUUIDs: existing.dependentRequestUUIDs || [], requestUUIDs: [action.payload.requestUUID, ...(existing.requestUUIDs || [])],
isDirty: isNotEmpty(existing.patches), dependentRequestUUIDs: existing.dependentRequestUUIDs || [],
patches: existing.patches || [], isDirty: isNotEmpty(existing.patches),
alternativeLinks: [...(existing.alternativeLinks || []), ...newAltLinks] patches: existing.patches || [],
} as ObjectCacheEntry alternativeLinks: [...(existing.alternativeLinks || []), ...newAltLinks]
}); } as ObjectCacheEntry
});
} else {
return state;
}
} }
/** /**

View File

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

View File

@@ -50,6 +50,7 @@ describe('BaseDataService', () => {
let selfLink; let selfLink;
let linksToFollow; let linksToFollow;
let testScheduler; let testScheduler;
let remoteDataTimestamp: number;
let remoteDataMocks; let remoteDataMocks;
function initTestService(): TestService { function initTestService(): TestService {
@@ -86,20 +87,22 @@ describe('BaseDataService', () => {
expect(actual).toEqual(expected); 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 msToLive = 15 * 60 * 1000;
const payload = { foo: 'bar' }; const payload = { foo: 'bar' };
const statusCodeSuccess = 200; const statusCodeSuccess = 200;
const statusCodeError = 404; const statusCodeError = 404;
const errorMessage = 'not found'; const errorMessage = 'not found';
remoteDataMocks = { remoteDataMocks = {
RequestPending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.RequestPending, undefined, undefined, undefined), RequestPending: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.RequestPending, undefined, undefined, undefined),
ResponsePending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.ResponsePending, undefined, undefined, undefined), ResponsePending: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.ResponsePending, undefined, undefined, undefined),
ResponsePendingStale: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.ResponsePendingStale, undefined, undefined, undefined), ResponsePendingStale: new RemoteData(undefined, msToLive, remoteDataTimestamp, RequestEntryState.ResponsePendingStale, undefined, undefined, undefined),
Success: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Success, undefined, payload, statusCodeSuccess), Success: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.Success, undefined, payload, statusCodeSuccess),
SuccessStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.SuccessStale, undefined, payload, statusCodeSuccess), SuccessStale: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.SuccessStale, undefined, payload, statusCodeSuccess),
Error: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Error, errorMessage, undefined, statusCodeError), Error: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.Error, errorMessage, undefined, statusCodeError),
ErrorStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.ErrorStale, errorMessage, undefined, statusCodeError), ErrorStale: new RemoteData(remoteDataTimestamp, msToLive, remoteDataTimestamp, RequestEntryState.ErrorStale, errorMessage, undefined, statusCodeError),
}; };
return new TestService( return new TestService(
@@ -333,11 +336,15 @@ describe('BaseDataService', () => {
spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source); spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source);
}); });
it('should not emit a cached completed RemoteData', () => {
it(`should not emit a cached completed RemoteData, but only start emitting after the state first changes to RequestPending`, () => { // Old cached value from 1 minute before the test started
const oldCachedSucceededData: RemoteData<any> = Object.assign({}, remoteDataMocks.Success, {
timeCompleted: remoteDataTimestamp - 2 * 60 * 1000,
lastUpdated: remoteDataTimestamp - 2 * 60 * 1000,
} as RemoteData<any>);
testScheduler.run(({ cold, expectObservable }) => { testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e', { spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e', {
a: remoteDataMocks.Success, a: oldCachedSucceededData,
b: remoteDataMocks.RequestPending, b: remoteDataMocks.RequestPending,
c: remoteDataMocks.ResponsePending, c: remoteDataMocks.ResponsePending,
d: remoteDataMocks.Success, d: remoteDataMocks.Success,
@@ -355,6 +362,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`, () => { it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => {
testScheduler.run(({ cold, expectObservable }) => { testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e-f-g', { spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e-f-g', {
@@ -521,11 +544,15 @@ describe('BaseDataService', () => {
spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source); spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source);
}); });
it('should not emit a cached completed RemoteData', () => {
it(`should not emit a cached completed RemoteData, but only start emitting after the state first changes to RequestPending`, () => {
testScheduler.run(({ cold, expectObservable }) => { testScheduler.run(({ cold, expectObservable }) => {
// Old cached value from 1 minute before the test started
const oldCachedSucceededData: RemoteData<any> = Object.assign({}, remoteDataMocks.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', { spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e', {
a: remoteDataMocks.Success, a: oldCachedSucceededData,
b: remoteDataMocks.RequestPending, b: remoteDataMocks.RequestPending,
c: remoteDataMocks.ResponsePending, c: remoteDataMocks.ResponsePending,
d: remoteDataMocks.Success, d: remoteDataMocks.Success,
@@ -543,6 +570,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: remoteDataMocks.Success,
b: remoteDataMocks.SuccessStale,
}));
const expected = 'a-b';
const values = {
a: remoteDataMocks.Success,
b: remoteDataMocks.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`, () => { it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => {
testScheduler.run(({ cold, expectObservable }) => { testScheduler.run(({ cold, expectObservable }) => {
spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e-f-g', { spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e-f-g', {

View File

@@ -266,6 +266,7 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
map((href: string) => this.buildHrefFromFindOptions(href, {}, [], ...linksToFollow)), map((href: string) => this.buildHrefFromFindOptions(href, {}, [], ...linksToFollow)),
); );
const startTime: number = new Date().getTime();
this.createAndSendGetRequest(requestHref$, useCachedVersionIfAvailable); this.createAndSendGetRequest(requestHref$, useCachedVersionIfAvailable);
return this.rdbService.buildSingle<T>(requestHref$, ...linksToFollow).pipe( return this.rdbService.buildSingle<T>(requestHref$, ...linksToFollow).pipe(
@@ -273,7 +274,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 // 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 // is created. If useCachedVersionIfAvailable is false it also ensures you don't get a
// cached completed object // 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.reRequestStaleRemoteData(reRequestOnStale, () =>
this.findByHref(href$, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)), this.findByHref(href$, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)),
); );
@@ -300,6 +301,7 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
map((href: string) => this.buildHrefFromFindOptions(href, options, [], ...linksToFollow)), map((href: string) => this.buildHrefFromFindOptions(href, options, [], ...linksToFollow)),
); );
const startTime: number = new Date().getTime();
this.createAndSendGetRequest(requestHref$, useCachedVersionIfAvailable); this.createAndSendGetRequest(requestHref$, useCachedVersionIfAvailable);
return this.rdbService.buildList<T>(requestHref$, ...linksToFollow).pipe( return this.rdbService.buildList<T>(requestHref$, ...linksToFollow).pipe(
@@ -307,7 +309,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 // 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 // is created. If useCachedVersionIfAvailable is false it also ensures you don't get a
// cached completed object // 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.reRequestStaleRemoteData(reRequestOnStale, () =>
this.findListByHref(href$, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)), this.findListByHref(href$, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)),
); );

View File

@@ -109,6 +109,13 @@ export class DspaceRestResponseParsingService implements ResponseParsingService
if (hasValue(match)) { if (hasValue(match)) {
embedAltUrl = new URLCombiner(embedAltUrl, `?size=${match.size}`).toString(); 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); this.process<ObjectDomain>(data._embedded[property], request, embedAltUrl);
}); });
} }
@@ -226,7 +233,7 @@ export class DspaceRestResponseParsingService implements ResponseParsingService
* @param alternativeURL an alternative url that can be used to retrieve the object * @param alternativeURL an alternative url that can be used to retrieve the object
*/ */
addToObjectCache(co: CacheableObject, request: RestRequest, data: any, alternativeURL?: string): void { 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'; const type = hasValue(data) && hasValue(data.type) ? data.type : 'object';
let dataJSON: string; let dataJSON: string;
if (hasValue(data._embedded)) { if (hasValue(data._embedded)) {
@@ -240,7 +247,7 @@ export class DspaceRestResponseParsingService implements ResponseParsingService
return; return;
} }
if (alternativeURL === co._links.self.href) { if (hasValue(co) && alternativeURL === co._links.self.href) {
alternativeURL = undefined; 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

@@ -23,6 +23,7 @@ import { FindListOptions } from './find-list-options.model';
import { testSearchDataImplementation } from './base/search-data.spec'; import { testSearchDataImplementation } from './base/search-data.spec';
import { MetadataValue } from '../shared/metadata.models'; import { MetadataValue } from '../shared/metadata.models';
import { MetadataRepresentationType } from '../shared/metadata-representation/metadata-representation.model'; import { MetadataRepresentationType } from '../shared/metadata-representation/metadata-representation.model';
import { environment } from '../../../environments/environment.test';
describe('RelationshipDataService', () => { describe('RelationshipDataService', () => {
let service: RelationshipDataService; let service: RelationshipDataService;
@@ -138,6 +139,7 @@ describe('RelationshipDataService', () => {
itemService, itemService,
null, null,
jasmine.createSpy('paginatedRelationsToItems').and.returnValue((v) => v), jasmine.createSpy('paginatedRelationsToItems').and.returnValue((v) => v),
environment,
); );
} }
@@ -153,7 +155,7 @@ describe('RelationshipDataService', () => {
}); });
describe('composition', () => { describe('composition', () => {
const initService = () => new RelationshipDataService(null, null, null, null, null, null, null); const initService = () => new RelationshipDataService(null, null, null, null, null, null, null, environment);
testSearchDataImplementation(initService); testSearchDataImplementation(initService);
}); });

View File

@@ -51,6 +51,7 @@ import { MetadataRepresentation } from '../shared/metadata-representation/metada
import { MetadatumRepresentation } from '../shared/metadata-representation/metadatum/metadatum-representation.model'; import { MetadatumRepresentation } from '../shared/metadata-representation/metadatum/metadatum-representation.model';
import { ItemMetadataRepresentation } from '../shared/metadata-representation/item/item-metadata-representation.model'; import { ItemMetadataRepresentation } from '../shared/metadata-representation/item/item-metadata-representation.model';
import { DSpaceObject } from '../shared/dspace-object.model'; import { DSpaceObject } from '../shared/dspace-object.model';
import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface';
const relationshipListsStateSelector = (state: AppState) => state.relationshipLists; const relationshipListsStateSelector = (state: AppState) => state.relationshipLists;
@@ -92,6 +93,7 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
protected itemService: ItemDataService, protected itemService: ItemDataService,
protected appStore: Store<AppState>, protected appStore: Store<AppState>,
@Inject(PAGINATED_RELATIONS_TO_ITEMS_OPERATOR) private paginatedRelationsToItems: (thisId: string) => (source: Observable<RemoteData<PaginatedList<Relationship>>>) => Observable<RemoteData<PaginatedList<Item>>>, @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); super('relationships', requestService, rdbService, objectCache, halService, 15 * 60 * 1000);
@@ -278,7 +280,7 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
* @param options * @param options
*/ */
getRelatedItemsByLabel(item: Item, label: string, options?: FindListOptions): Observable<RemoteData<PaginatedList<Item>>> { getRelatedItemsByLabel(item: Item, label: string, options?: FindListOptions): Observable<RemoteData<PaginatedList<Item>>> {
let linksToFollow: FollowLinkConfig<Relationship>[] = itemLinksToFollow(options.fetchThumbnail); let linksToFollow: FollowLinkConfig<Relationship>[] = itemLinksToFollow(options.fetchThumbnail, this.appConfig.item.showAccessStatuses);
linksToFollow.push(followLink('relationshipType')); linksToFollow.push(followLink('relationshipType'));
return this.getItemRelationshipsByLabel(item, label, options, true, true, ...linksToFollow).pipe(this.paginatedRelationsToItems(item.uuid)); return this.getItemRelationshipsByLabel(item, label, options, true, true, ...linksToFollow).pipe(this.paginatedRelationsToItems(item.uuid));

View File

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

View File

@@ -27,7 +27,7 @@ export class UUIDIndexEffects {
addObject$ = createEffect(() => this.actions$ addObject$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(ObjectCacheActionTypes.ADD), 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) => { map((action: AddToObjectCacheAction) => {
return new AddToIndexAction( return new AddToIndexAction(
IndexName.OBJECT, IndexName.OBJECT,
@@ -46,7 +46,7 @@ export class UUIDIndexEffects {
ofType(ObjectCacheActionTypes.ADD), ofType(ObjectCacheActionTypes.ADD),
map((action: AddToObjectCacheAction) => { map((action: AddToObjectCacheAction) => {
const alternativeLink = action.payload.alternativeLink; 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) { if (hasValue(alternativeLink) && alternativeLink !== selfLink) {
return new AddToIndexAction( return new AddToIndexAction(
IndexName.ALTERNATIVE_OBJECT_LINK, IndexName.ALTERNATIVE_OBJECT_LINK,

View File

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

View File

@@ -1,4 +1,4 @@
import { autoserialize, autoserializeAs, deserialize, inheritSerialization } from 'cerialize'; import { autoserialize, deserialize, inheritSerialization } from 'cerialize';
import { typedObject } from '../cache/builders/build-decorators'; import { typedObject } from '../cache/builders/build-decorators';
import { excludeFromEquals } from '../utilities/equals.decorators'; import { excludeFromEquals } from '../utilities/equals.decorators';
import { HIERARCHICAL_BROWSE_DEFINITION } from './hierarchical-browse-definition.resource-type'; import { HIERARCHICAL_BROWSE_DEFINITION } from './hierarchical-browse-definition.resource-type';
@@ -26,9 +26,6 @@ export class HierarchicalBrowseDefinition extends BrowseDefinition {
@autoserialize @autoserialize
vocabulary: string; vocabulary: string;
@autoserializeAs('metadata')
metadataKeys: string[];
get self(): string { get self(): string {
return this._links.self.href; return this._links.self.href;
} }

View File

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

View File

@@ -6,13 +6,30 @@
[formControl]="input" [formControl]="input"
(focusin)="query$.next(mdField)" (focusin)="query$.next(mdField)"
(dsClickOutside)="query$.next(null)" (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="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 class="dropdown-list">
<div *ngFor="let mdFieldOption of (mdFieldOptions$ | async)"> <div
<button class="d-block dropdown-item" (click)="select(mdFieldOption)"> infiniteScroll
<span [innerHTML]="mdFieldOption"></span> [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> </button>
</div> </div>
</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

@@ -28,7 +28,8 @@ describe('MetadataFieldSelectorComponent', () => {
metadataSchema = Object.assign(new MetadataSchema(), { metadataSchema = Object.assign(new MetadataSchema(), {
id: 0, id: 0,
prefix: 'dc', prefix: 'dc',
namespace: 'http://dublincore.org/documents/dcmi-terms/', namespace: 'https://schema.org/CreativeWork',
field: '.',
}); });
metadataFields = [ metadataFields = [
Object.assign(new MetadataField(), { Object.assign(new MetadataField(), {
@@ -68,10 +69,10 @@ describe('MetadataFieldSelectorComponent', () => {
}); });
describe('when a query is entered', () => { describe('when a query is entered', () => {
const query = 'test query'; const query = 'dc.d';
beforeEach(() => { beforeEach(() => {
component.showInvalid = true; component.showInvalid = false;
component.query$.next(query); component.query$.next(query);
}); });
@@ -80,7 +81,7 @@ describe('MetadataFieldSelectorComponent', () => {
}); });
it('should query the registry service for metadata fields and include the schema', () => { 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

@@ -9,20 +9,23 @@ import {
Output, Output,
ViewChild ViewChild
} from '@angular/core'; } from '@angular/core';
import { debounceTime, distinctUntilChanged, map, switchMap, take, tap } from 'rxjs/operators'; import { debounceTime, map, startWith, switchMap, take, tap } from 'rxjs/operators';
import { followLink } from '../../../shared/utils/follow-link-config.model'; import { followLink } from '../../../shared/utils/follow-link-config.model';
import { import {
getAllSucceededRemoteData, getAllSucceededRemoteData,
getFirstCompletedRemoteData, getFirstCompletedRemoteData,
metadataFieldsToString metadataFieldsToString
} from '../../../core/shared/operators'; } from '../../../core/shared/operators';
import { Observable } from 'rxjs/internal/Observable'; import {
BehaviorSubject,
combineLatest as observableCombineLatest,
Observable,
of,
Subscription,
} from 'rxjs';
import { RegistryService } from '../../../core/registry/registry.service'; import { RegistryService } from '../../../core/registry/registry.service';
import { UntypedFormControl } from '@angular/forms'; import { UntypedFormControl } from '@angular/forms';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { hasValue } from '../../../shared/empty.util'; import { hasValue } from '../../../shared/empty.util';
import { Subscription } from 'rxjs/internal/Subscription';
import { of } from 'rxjs/internal/observable/of';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model'; import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model';
@@ -30,7 +33,7 @@ import { SortDirection, SortOptions } from '../../../core/cache/models/sort-opti
@Component({ @Component({
selector: 'ds-metadata-field-selector', selector: 'ds-metadata-field-selector',
styleUrls: ['./metadata-field-selector.component.scss'], styleUrls: ['./metadata-field-selector.component.scss'],
templateUrl: './metadata-field-selector.component.html' templateUrl: './metadata-field-selector.component.html',
}) })
/** /**
* Component displaying a searchable input for metadata-fields * Component displaying a searchable input for metadata-fields
@@ -67,7 +70,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 * 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 * Shows up in a dropdown below the input
*/ */
mdFieldOptions$: Observable<string[]>; mdFieldOptions$: BehaviorSubject<string[]> = new BehaviorSubject<string[]>([]);
/** /**
* FormControl for the input * FormControl for the input
@@ -102,6 +105,30 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV
*/ */
subs: Subscription[] = []; 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, constructor(protected registryService: RegistryService,
protected notificationsService: NotificationsService, protected notificationsService: NotificationsService,
protected translate: TranslateService) { protected translate: TranslateService) {
@@ -112,32 +139,33 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV
* Update the mdFieldOptions$ depending on the query$ fired by querying the server * Update the mdFieldOptions$ depending on the query$ fired by querying the server
*/ */
ngOnInit(): void { ngOnInit(): void {
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.mdField = valueChange;
this.mdFieldChange.emit(this.mdField);
}));
this.subs.push( this.subs.push(
this.input.valueChanges.pipe( observableCombineLatest(
debounceTime(this.debounceTime), this.query$,
).subscribe((valueChange) => { this.currentPage$,
if (!this.selectedValueLoading) { )
this.query$.next(valueChange); .pipe(
} switchMap(([query, page]: [string, number]) => {
this.selectedValueLoading = false; this.loading = true;
this.mdField = valueChange; if (page === 1) {
this.mdFieldChange.emit(this.mdField); this.mdFieldOptions$.next([]);
}), }
); return this.search(query as string, page as number);
this.mdFieldOptions$ = this.query$.pipe( }),
distinctUntilChanged(), ).subscribe((rd ) => {
switchMap((query: string) => { if (!this.selectedValueLoading) {this.updateList(rd);}
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 [[]];
}
}),
);
} }
/** /**
@@ -181,6 +209,41 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV
this.input.setValue(mdFieldOption); 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 * Unsubscribe from any open subscriptions
*/ */

View File

@@ -22,21 +22,21 @@
class="lead item-list-title dont-break-out" class="lead item-list-title dont-break-out"
[innerHTML]="dsoTitle"></span> [innerHTML]="dsoTitle"></span>
<span class="text-muted"> <span class="text-muted">
<ds-truncatable-part [id]="dso.id" [minLines]="1"> <ds-truncatable-part [id]="dso.id" [minLines]="1">
<span *ngIf="dso.allMetadata(['publicationvolume.volumeNumber']).length > 0" <span *ngIf="dso.allMetadata(['publicationvolume.volumeNumber']).length > 0"
class="item-list-journal-issues"> class="item-list-journal-issues">
<span *ngFor="let value of allMetadataValues(['publicationvolume.volumeNumber']); let last=last;"> <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>
</span>
</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 first=first; let last=last;">
<span *ngIf="first"> - </span><span [innerHTML]="value"></span><span *ngIf="!last">; </span>
</span>
</span>
</span>
</ds-truncatable-part> </ds-truncatable-part>
</span> </span>
</ds-truncatable> </ds-truncatable>
</div> </div>
</div> </div>

View File

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

View File

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

View File

@@ -39,6 +39,8 @@ import {
BrowseDefinitionDataServiceStub BrowseDefinitionDataServiceStub
} from '../../../../shared/testing/browse-definition-data-service.stub'; } from '../../../../shared/testing/browse-definition-data-service.stub';
import { BrowseDefinitionDataService } from '../../../../core/browse/browse-definition-data.service'; import { BrowseDefinitionDataService } from '../../../../core/browse/browse-definition-data.service';
import { BrowseService } from '../../../../core/browse/browse.service';
import { BrowseServiceStub } from '../../../../shared/testing/browse-service.stub';
let comp: JournalComponent; let comp: JournalComponent;
let fixture: ComponentFixture<JournalComponent>; let fixture: ComponentFixture<JournalComponent>;
@@ -105,7 +107,8 @@ describe('JournalComponent', () => {
{ provide: WorkspaceitemDataService, useValue: {} }, { provide: WorkspaceitemDataService, useValue: {} },
{ provide: SearchService, useValue: {} }, { provide: SearchService, useValue: {} },
{ provide: RouteService, useValue: mockRouteService }, { provide: RouteService, useValue: mockRouteService },
{ provide: BrowseDefinitionDataService, useValue: BrowseDefinitionDataServiceStub } { provide: BrowseDefinitionDataService, useValue: BrowseDefinitionDataServiceStub },
{ provide: BrowseService, useValue: BrowseServiceStub },
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]

View File

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

View File

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

View File

@@ -11,11 +11,11 @@
<span class="text-muted"> <span class="text-muted">
<span *ngIf="dso.allMetadata('organization.address.addressLocality').length > 0" <span *ngIf="dso.allMetadata('organization.address.addressLocality').length > 0"
class="item-list-address-locality"> 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>
<span *ngIf="dso.allMetadata('organization.address.addressCountry').length > 0" <span *ngIf="dso.allMetadata('organization.address.addressCountry').length > 0"
class="item-list-address-country"> 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>
</span> </span>
</div> </div>

View File

@@ -22,7 +22,7 @@ import { APP_CONFIG, AppConfig } from '../../../../../../config/app-config.inter
@listableObjectComponent('OrgUnitSearchResult', ViewMode.ListElement, Context.EntitySearchModal) @listableObjectComponent('OrgUnitSearchResult', ViewMode.ListElement, Context.EntitySearchModal)
@listableObjectComponent('OrgUnitSearchResult', ViewMode.ListElement, Context.EntitySearchModalWithNameVariants) @listableObjectComponent('OrgUnitSearchResult', ViewMode.ListElement, Context.EntitySearchModalWithNameVariants)
@Component({ @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'], styleUrls: ['./org-unit-search-result-list-submission-element.component.scss'],
templateUrl: './org-unit-search-result-list-submission-element.component.html' templateUrl: './org-unit-search-result-list-submission-element.component.html'
}) })

View File

@@ -23,13 +23,13 @@
(clickSuggestion)="select($event)" (clickSuggestion)="select($event)"
(submitSuggestion)="selectCustom($event)"></ds-person-input-suggestions> (submitSuggestion)="selectCustom($event)"></ds-person-input-suggestions>
<span class="text-muted"> <span class="text-muted">
<span *ngIf="dso.allMetadata(['person.jobTitle']).length > 0" <span *ngIf="dso.allMetadata(['person.jobTitle']).length > 0"
class="item-list-job-title"> class="item-list-job-title">
<span *ngFor="let value of allMetadataValues(['person.jobTitle']); let last=last;"> <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>
</span> </span>
</span>
</div> </div>
</div> </div>
</div> </div>

View File

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

View File

@@ -6,14 +6,14 @@ import { ObjectUpdatesService } from '../../../core/data/object-updates/object-u
import { ActivatedRoute, Router, Data } from '@angular/router'; import { ActivatedRoute, Router, Data } from '@angular/router';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { first, map, switchMap, tap } from 'rxjs/operators'; import { take, map, switchMap, tap } from 'rxjs/operators';
import { RemoteData } from '../../../core/data/remote-data'; import { RemoteData } from '../../../core/data/remote-data';
import { AbstractTrackableComponent } from '../../../shared/trackable/abstract-trackable.component'; import { AbstractTrackableComponent } from '../../../shared/trackable/abstract-trackable.component';
import { environment } from '../../../../environments/environment'; import { environment } from '../../../../environments/environment';
import { getItemPageRoute } from '../../item-page-routing-paths'; import { getItemPageRoute } from '../../item-page-routing-paths';
import { getAllSucceededRemoteData } from '../../../core/shared/operators'; import { getAllSucceededRemoteData } from '../../../core/shared/operators';
import { hasValue } from '../../../shared/empty.util'; import { hasValue } from '../../../shared/empty.util';
import { ITEM_PAGE_LINKS_TO_FOLLOW } from '../../item.resolver'; import { getItemPageLinksToFollow } from '../../item.resolver';
import { FieldUpdate } from '../../../core/data/object-updates/field-update.model'; import { FieldUpdate } from '../../../core/data/object-updates/field-update.model';
import { FieldUpdates } from '../../../core/data/object-updates/field-updates.model'; import { FieldUpdates } from '../../../core/data/object-updates/field-updates.model';
@@ -72,7 +72,7 @@ export class AbstractItemUpdateComponent extends AbstractTrackableComponent impl
this.item = rd.payload; this.item = rd.payload;
}), }),
switchMap((rd: RemoteData<Item>) => { 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() getAllSucceededRemoteData()
).subscribe((rd: RemoteData<Item>) => { ).subscribe((rd: RemoteData<Item>) => {
@@ -82,7 +82,7 @@ export class AbstractItemUpdateComponent extends AbstractTrackableComponent impl
super.ngOnInit(); super.ngOnInit();
this.discardTimeOut = environment.item.edit.undoTimeout; this.discardTimeOut = environment.item.edit.undoTimeout;
this.hasChanges().pipe(first()).subscribe((hasChanges) => { this.hasChanges().pipe(take(1)).subscribe((hasChanges) => {
if (!hasChanges) { if (!hasChanges) {
this.initializeOriginalFields(); this.initializeOriginalFields();
} else { } else {
@@ -167,7 +167,7 @@ export class AbstractItemUpdateComponent extends AbstractTrackableComponent impl
*/ */
private checkLastModified() { private checkLastModified() {
const currentVersion = this.item.lastModified; const currentVersion = this.item.lastModified;
this.objectUpdatesService.getLastModified(this.url).pipe(first()).subscribe( this.objectUpdatesService.getLastModified(this.url).pipe(take(1)).subscribe(
(updateVersion: Date) => { (updateVersion: Date) => {
if (updateVersion.getDate() !== currentVersion.getDate()) { if (updateVersion.getDate() !== currentVersion.getDate()) {
this.notificationsService.warning(this.getNotificationTitle('outdated'), this.getNotificationContent('outdated')); this.notificationsService.warning(this.getNotificationTitle('outdated'), this.getNotificationContent('outdated'));

View File

@@ -15,7 +15,6 @@ import { ItemPrivateComponent } from './item-private/item-private.component';
import { ItemPublicComponent } from './item-public/item-public.component'; import { ItemPublicComponent } from './item-public/item-public.component';
import { ItemDeleteComponent } from './item-delete/item-delete.component'; import { ItemDeleteComponent } from './item-delete/item-delete.component';
import { ItemBitstreamsComponent } from './item-bitstreams/item-bitstreams.component'; import { ItemBitstreamsComponent } from './item-bitstreams/item-bitstreams.component';
import { ItemEditBitstreamComponent } from './item-bitstreams/item-edit-bitstream/item-edit-bitstream.component';
import { SearchPageModule } from '../../search-page/search-page.module'; import { SearchPageModule } from '../../search-page/search-page.module';
import { ItemCollectionMapperComponent } from './item-collection-mapper/item-collection-mapper.component'; import { ItemCollectionMapperComponent } from './item-collection-mapper/item-collection-mapper.component';
import { ItemRelationshipsComponent } from './item-relationships/item-relationships.component'; import { ItemRelationshipsComponent } from './item-relationships/item-relationships.component';
@@ -26,8 +25,6 @@ import { ItemMoveComponent } from './item-move/item-move.component';
import { ItemEditBitstreamBundleComponent } from './item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component'; import { ItemEditBitstreamBundleComponent } from './item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component';
import { BundleDataService } from '../../core/data/bundle-data.service'; import { BundleDataService } from '../../core/data/bundle-data.service';
import { DragDropModule } from '@angular/cdk/drag-drop'; import { DragDropModule } from '@angular/cdk/drag-drop';
import { ItemEditBitstreamDragHandleComponent } from './item-bitstreams/item-edit-bitstream-drag-handle/item-edit-bitstream-drag-handle.component';
import { PaginatedDragAndDropBitstreamListComponent } from './item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component';
import { VirtualMetadataComponent } from './virtual-metadata/virtual-metadata.component'; import { VirtualMetadataComponent } from './virtual-metadata/virtual-metadata.component';
import { ItemVersionHistoryComponent } from './item-version-history/item-version-history.component'; import { ItemVersionHistoryComponent } from './item-version-history/item-version-history.component';
import { ItemAuthorizationsComponent } from './item-authorizations/item-authorizations.component'; import { ItemAuthorizationsComponent } from './item-authorizations/item-authorizations.component';
@@ -83,14 +80,11 @@ import {
ItemRelationshipsComponent, ItemRelationshipsComponent,
ItemBitstreamsComponent, ItemBitstreamsComponent,
ItemVersionHistoryComponent, ItemVersionHistoryComponent,
ItemEditBitstreamComponent,
ItemEditBitstreamBundleComponent, ItemEditBitstreamBundleComponent,
PaginatedDragAndDropBitstreamListComponent,
EditRelationshipComponent, EditRelationshipComponent,
EditRelationshipListComponent, EditRelationshipListComponent,
ItemCollectionMapperComponent, ItemCollectionMapperComponent,
ItemMoveComponent, ItemMoveComponent,
ItemEditBitstreamDragHandleComponent,
VirtualMetadataComponent, VirtualMetadataComponent,
ItemAuthorizationsComponent, ItemAuthorizationsComponent,
IdentifierDataComponent, IdentifierDataComponent,

View File

@@ -1,4 +1,8 @@
<div class="item-bitstreams" *ngVar="(bundles$ | async) as bundles"> <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"> <div class="button-row top d-flex mt-2 space-children-mr">
<button class="mr-auto btn btn-success" <button class="mr-auto btn btn-success"
[attr.aria-label]="'item.edit.bitstreams.upload-button' | translate" [attr.aria-label]="'item.edit.bitstreams.upload-button' | translate"
@@ -27,21 +31,13 @@
</button> </button>
</div> </div>
<div *ngIf="item && bundles?.length > 0" class="container table-bordered mt-4"> <div *ngIf="item && bundles?.length > 0" class="mt-4 table-border scrollable-table" [ngClass]="{'disabled-overlay': (isProcessingMoveRequest | async)}">
<div class="row header-row font-weight-bold"> <ds-item-edit-bitstream-bundle *ngFor="let bundle of bundles; first as isFirst"
<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"
[bundle]="bundle" [bundle]="bundle"
[item]="item" [item]="item"
[columnSizes]="columnSizes" [columnSizes]="columnSizes"
(dropObject)="dropBitstream(bundle, $event)"> [isFirstTable]="isFirst"
aria-describedby="reorder-description">
</ds-item-edit-bitstream-bundle> </ds-item-edit-bitstream-bundle>
</div> </div>
<div *ngIf="bundles?.length === 0" <div *ngIf="bundles?.length === 0"
@@ -74,3 +70,5 @@
</div> </div>
</div> </div>
</div> </div>
<ds-themed-loading *ngIf="isProcessingMoveRequest | async" class="loading-overlay"></ds-themed-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 { .drag-handle {
visibility: hidden;
&:hover { &:hover {
cursor: move; cursor: move;
} }
@@ -27,10 +8,6 @@
cursor: move; 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 { .cdk-drag-preview {
margin-left: 0; margin-left: 0;
box-sizing: border-box; box-sizing: border-box;
@@ -54,3 +31,25 @@
:host ::ng-deep .larger-tooltip .tooltip-inner { :host ::ng-deep .larger-tooltip .tooltip-inner {
max-width: 500px; 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

@@ -18,7 +18,6 @@ import { ObjectValuesPipe } from '../../../shared/utils/object-values-pipe';
import { VarDirective } from '../../../shared/utils/var.directive'; import { VarDirective } from '../../../shared/utils/var.directive';
import { BundleDataService } from '../../../core/data/bundle-data.service'; import { BundleDataService } from '../../../core/data/bundle-data.service';
import { Bundle } from '../../../core/shared/bundle.model'; import { Bundle } from '../../../core/shared/bundle.model';
import { RestResponse } from '../../../core/cache/response.models';
import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service';
import { RouterStub } from '../../../shared/testing/router.stub'; import { RouterStub } from '../../../shared/testing/router.stub';
import { getMockRequestService } from '../../../shared/mocks/request.service.mock'; import { getMockRequestService } from '../../../shared/mocks/request.service.mock';
@@ -26,6 +25,8 @@ import { createSuccessfulRemoteDataObject, createSuccessfulRemoteDataObject$ } f
import { createPaginatedList } from '../../../shared/testing/utils.test'; import { createPaginatedList } from '../../../shared/testing/utils.test';
import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model'; import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model';
import { BitstreamDataServiceStub } from '../../../shared/testing/bitstream-data-service.stub'; import { BitstreamDataServiceStub } from '../../../shared/testing/bitstream-data-service.stub';
import { ItemBitstreamsService } from './item-bitstreams.service';
import { getItemBitstreamsServiceStub, ItemBitstreamsServiceStub } from './item-bitstreams.service.stub';
let comp: ItemBitstreamsComponent; let comp: ItemBitstreamsComponent;
let fixture: ComponentFixture<ItemBitstreamsComponent>; let fixture: ComponentFixture<ItemBitstreamsComponent>;
@@ -77,6 +78,7 @@ let objectCache: ObjectCacheService;
let requestService: RequestService; let requestService: RequestService;
let searchConfig: SearchConfigurationService; let searchConfig: SearchConfigurationService;
let bundleService: BundleDataService; let bundleService: BundleDataService;
let itemBitstreamsService: ItemBitstreamsServiceStub;
describe('ItemBitstreamsComponent', () => { describe('ItemBitstreamsComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
@@ -145,9 +147,11 @@ describe('ItemBitstreamsComponent', () => {
url: url url: url
}); });
bundleService = jasmine.createSpyObj('bundleService', { bundleService = jasmine.createSpyObj('bundleService', {
patch: observableOf(new RestResponse(true, 200, 'OK')) patch: createSuccessfulRemoteDataObject$({}),
}); });
itemBitstreamsService = getItemBitstreamsServiceStub();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()], imports: [TranslateModule.forRoot()],
declarations: [ItemBitstreamsComponent, ObjectValuesPipe, VarDirective], declarations: [ItemBitstreamsComponent, ObjectValuesPipe, VarDirective],
@@ -162,6 +166,7 @@ describe('ItemBitstreamsComponent', () => {
{ provide: RequestService, useValue: requestService }, { provide: RequestService, useValue: requestService },
{ provide: SearchConfigurationService, useValue: searchConfig }, { provide: SearchConfigurationService, useValue: searchConfig },
{ provide: BundleDataService, useValue: bundleService }, { provide: BundleDataService, useValue: bundleService },
{ provide: ItemBitstreamsService, useValue: itemBitstreamsService },
ChangeDetectorRef ChangeDetectorRef
], schemas: [ ], schemas: [
NO_ERRORS_SCHEMA NO_ERRORS_SCHEMA
@@ -182,42 +187,8 @@ describe('ItemBitstreamsComponent', () => {
comp.submit(); comp.submit();
}); });
it('should call removeMultiple on the bitstreamService for the marked field', () => { it('should call removeMarkedBitstreams on the itemBitstreamsService', () => {
expect(bitstreamService.removeMultiple).toHaveBeenCalledWith([bitstream2]); expect(itemBitstreamsService.removeMarkedBitstreams).toHaveBeenCalled();
});
it('should not call removeMultiple on the bitstreamService for the unmarked field', () => {
expect(bitstreamService.removeMultiple).not.toHaveBeenCalledWith([bitstream1]);
});
});
describe('when dropBitstream is called', () => {
const event = {
fromIndex: 0,
toIndex: 50,
// eslint-disable-next-line no-empty,@typescript-eslint/no-empty-function
finish: () => {
}
};
beforeEach(() => {
comp.dropBitstream(bundle, event);
});
});
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();
}); });
}); });
@@ -234,4 +205,114 @@ describe('ItemBitstreamsComponent', () => {
expect(objectUpdatesService.reinstateFieldUpdates).toHaveBeenCalledWith(bundle.self); 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,30 +1,28 @@
import { ChangeDetectorRef, Component, NgZone, OnDestroy } from '@angular/core'; import { ChangeDetectorRef, Component, NgZone, OnDestroy, HostListener } from '@angular/core';
import { AbstractItemUpdateComponent } from '../abstract-item-update/abstract-item-update.component'; import { AbstractItemUpdateComponent } from '../abstract-item-update/abstract-item-update.component';
import { filter, map, switchMap, take } from 'rxjs/operators'; import { map, switchMap, take } from 'rxjs/operators';
import { Observable, Subscription, zip as observableZip, combineLatest } from 'rxjs'; import { Observable, Subscription, combineLatest } from 'rxjs';
import { ItemDataService } from '../../../core/data/item-data.service'; import { ItemDataService } from '../../../core/data/item-data.service';
import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service'; import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service'; import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { hasValue, isNotEmpty } from '../../../shared/empty.util';
import { ObjectCacheService } from '../../../core/cache/object-cache.service'; import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import { RequestService } from '../../../core/data/request.service'; import { RequestService } from '../../../core/data/request.service';
import { getFirstSucceededRemoteData, getRemoteDataPayload } from '../../../core/shared/operators'; import {
getFirstSucceededRemoteData,
getRemoteDataPayload,
} from '../../../core/shared/operators';
import { RemoteData } from '../../../core/data/remote-data'; import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list.model'; import { PaginatedList } from '../../../core/data/paginated-list.model';
import { Bundle } from '../../../core/shared/bundle.model'; import { Bundle } from '../../../core/shared/bundle.model';
import { Bitstream } from '../../../core/shared/bitstream.model';
import { BundleDataService } from '../../../core/data/bundle-data.service'; import { BundleDataService } from '../../../core/data/bundle-data.service';
import { PaginatedSearchOptions } from '../../../shared/search/models/paginated-search-options.model'; import { PaginatedSearchOptions } from '../../../shared/search/models/paginated-search-options.model';
import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes'; import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes';
import { NoContent } from '../../../core/shared/NoContent.model'; import { NoContent } from '../../../core/shared/NoContent.model';
import { Operation } from 'fast-json-patch'; import { ItemBitstreamsService } from './item-bitstreams.service';
import { FieldUpdate } from '../../../core/data/object-updates/field-update.model'; import { AlertType } from '../../../shared/alert/alert-type';
import { FieldUpdates } from '../../../core/data/object-updates/field-updates.model';
import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model';
@Component({ @Component({
selector: 'ds-item-bitstreams', selector: 'ds-item-bitstreams',
@@ -36,33 +34,18 @@ import { FieldChangeType } from '../../../core/data/object-updates/field-change-
*/ */
export class ItemBitstreamsComponent extends AbstractItemUpdateComponent implements OnDestroy { export class ItemBitstreamsComponent extends AbstractItemUpdateComponent implements OnDestroy {
// Declared for use in template
protected readonly AlertType = AlertType;
/** /**
* The currently listed bundles * The currently listed bundles
*/ */
bundles$: Observable<Bundle[]>; 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 * The bootstrap sizes used for the columns within this table
*/ */
columnSizes = new ResponsiveTableSizes([ columnSizes: 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)
]);
/** /**
* Are we currently submitting the changes? * Are we currently submitting the changes?
@@ -76,6 +59,11 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
*/ */
itemUpdateSubscription: Subscription; itemUpdateSubscription: Subscription;
/**
* An observable which emits a boolean which represents whether the service is currently handling a 'move' request
*/
isProcessingMoveRequest: Observable<boolean>;
constructor( constructor(
public itemService: ItemDataService, public itemService: ItemDataService,
public objectUpdatesService: ObjectUpdatesService, public objectUpdatesService: ObjectUpdatesService,
@@ -88,22 +76,83 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
public requestService: RequestService, public requestService: RequestService,
public cdRef: ChangeDetectorRef, public cdRef: ChangeDetectorRef,
public bundleService: BundleDataService, public bundleService: BundleDataService,
public zone: NgZone public zone: NgZone,
public itemBitstreamsService: ItemBitstreamsService,
) { ) {
super(itemService, objectUpdatesService, router, notificationsService, translateService, route); super(itemService, objectUpdatesService, router, notificationsService, translateService, route);
this.columnSizes = this.itemBitstreamsService.getColumnSizes();
} }
/** /**
* Actions to perform after the item has been initialized * Actions to perform after the item has been initialized
*/ */
postItemInit(): void { 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(), getFirstSucceededRemoteData(),
getRemoteDataPayload(), getRemoteDataPayload(),
map((bundlePage: PaginatedList<Bundle>) => bundlePage.page) 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 * Initialize the notification messages prefix
*/ */
@@ -119,84 +168,16 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
*/ */
submit() { submit() {
this.submitting = true; this.submitting = true;
const bundlesOnce$ = this.bundles$.pipe(take(1));
// Fetch all removed bitstreams from the object update service const removedResponses$ = this.itemBitstreamsService.removeMarkedBitstreams(this.bundles$);
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);
})
);
// Perform the setup actions from above in order and display notifications // Perform the setup actions from above in order and display notifications
removedResponses$.subscribe((responses: RemoteData<NoContent>) => { 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; 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 * 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 * Shows a notification to remind the user that they can undo this

View File

@@ -0,0 +1,705 @@
import { ItemBitstreamsService, SelectedBitstreamTableEntry } from './item-bitstreams.service';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { getMockTranslateService } from '../../../shared/mocks/translate.service.mock';
import { ObjectUpdatesServiceStub } from '../../../core/data/object-updates/object-updates.service.stub';
import { BitstreamDataServiceStub } from '../../../shared/testing/bitstream-data-service.stub';
import { DSONameServiceMock } from '../../../shared/mocks/dso-name.service.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service';
import { TranslateService } from '@ngx-translate/core';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { Bitstream } from '../../../core/shared/bitstream.model';
import { BitstreamFormat } from '../../../core/shared/bitstream-format.model';
import {
createSuccessfulRemoteDataObject$,
createFailedRemoteDataObject,
createSuccessfulRemoteDataObject
} from '../../../shared/remote-data.utils';
import { BundleDataService } from '../../../core/data/bundle-data.service';
import { RequestService } from '../../../core/data/request.service';
import { LiveRegionService } from '../../../shared/live-region/live-region.service';
import { Bundle } from '../../../core/shared/bundle.model';
import { of } from 'rxjs';
import { getLiveRegionServiceStub } from '../../../shared/live-region/live-region.service.stub';
import { fakeAsync, tick } from '@angular/core/testing';
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,78 @@
import { of } from 'rxjs';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes';
import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
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,552 @@
import { Injectable } from '@angular/core';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { ResponsiveTableSizes } from '../../../shared/responsive-table-sizes/responsive-table-sizes';
import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes';
import { RemoteData } from '../../../core/data/remote-data';
import { hasValue, hasNoValue } from '../../../shared/empty.util';
import { Bundle } from '../../../core/shared/bundle.model';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core';
import { Observable, zip as observableZip, BehaviorSubject } from 'rxjs';
import { NoContent } from '../../../core/shared/NoContent.model';
import { take, switchMap, map, tap } from 'rxjs/operators';
import { FieldUpdates } from '../../../core/data/object-updates/field-updates.model';
import { FieldUpdate } from '../../../core/data/object-updates/field-update.model';
import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model';
import { Bitstream } from '../../../core/shared/bitstream.model';
import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service';
import { BitstreamDataService } from '../../../core/data/bitstream-data.service';
import { getFirstSucceededRemoteDataPayload, getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { getBitstreamDownloadRoute } from '../../../app-routing-paths';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { BitstreamFormat } from '../../../core/shared/bitstream-format.model';
import { MoveOperation } from 'fast-json-patch';
import { BundleDataService } from '../../../core/data/bundle-data.service';
import { RequestService } from '../../../core/data/request.service';
import { LiveRegionService } from '../../../shared/live-region/live-region.service';
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,22 +1,140 @@
<ng-template #bundleView> <ng-template #bundleView>
<div class="row bundle-row">
<div class="{{bundleNameColumn.buildClasses()}} font-weight-bold row-element d-flex"> <ds-pagination *ngIf="(bitstreamsRD$ | async)?.payload as bitstreamsList"
<ds-item-edit-bitstream-drag-handle></ds-item-edit-bitstream-drag-handle> [hideGear]="true"
<div class="float-left d-flex align-items-center"> [hidePagerWhenSinglePage]="true"
{{'item.edit.bitstreams.bundle.name' | translate:{ name: dsoNameService.getName(bundle) } }} [hidePaginationDetail]="true"
</div> [paginationOptions]="paginationOptions"
</div> [collectionSize]="bitstreamsList.totalElements"
<div class="{{columnSizes.columns[3].buildClasses()}} text-center row-element"> [retainScrollPosition]="true"
<div class="btn-group bundle-action-buttons"> [ngbTooltip]="'item.edit.bitstreams.bundle.tooltip' | translate" placement="bottom"
<button [routerLink]="[itemPageRoute, 'bitstreams', 'new']" [autoClose]="false" triggers="manual" #dragTooltip="ngbTooltip">
[queryParams]="{bundle: bundle.id}" <ng-container *ngIf="(updates$ | async) as updates">
[attr.aria-label]="'item.edit.bitstreams.bundle.edit.buttons.upload' | translate"
class="btn btn-outline-success btn-sm" <table class="table" [class.mt-n1]="!isFirstTable"
title="{{'item.edit.bitstreams.bundle.edit.buttons.upload' | translate}}"> [attr.aria-label]="'item.edit.bitstreams.bundle.table.aria-label' | translate: { bundle: bundleName } ">
<i class="fas fa-upload fa-fw"></i> <thead [class.visually-hidden]="!isFirstTable">
</button> <tr class="header-row font-weight-bold">
</div> <th id="name" scope="col" class="{{ columnSizes.columns[0].buildClasses() }}">
</div> {{'item.edit.bitstreams.headers.name' | translate}}
</div> </th>
<ds-paginated-drag-and-drop-bitstream-list [bundle]="bundle" [columnSizes]="columnSizes" (dropObject)="dropObject.emit($event)"></ds-paginated-drag-and-drop-bitstream-list> <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"
class="btn btn-outline-success btn-sm"
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>
{{ 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> </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

@@ -6,6 +6,20 @@ import { Item } from '../../../../core/shared/item.model';
import { Bundle } from '../../../../core/shared/bundle.model'; import { Bundle } from '../../../../core/shared/bundle.model';
import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes'; import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes'; import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes';
import { BundleDataService } from '../../../../core/data/bundle-data.service';
import { of as observableOf, of, Subject } from 'rxjs';
import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service';
import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub';
import { RequestService } from '../../../../core/data/request.service';
import { getMockRequestService } from '../../../../shared/mocks/request.service.mock';
import { ItemBitstreamsService, BitstreamTableEntry, SelectedBitstreamTableEntry } from '../item-bitstreams.service';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { getItemBitstreamsServiceStub, ItemBitstreamsServiceStub } from '../item-bitstreams.service.stub';
import { FieldUpdate } from '../../../../core/data/object-updates/field-update.model';
import { FieldChangeType } from '../../../../core/data/object-updates/field-change-type.model';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { createPaginatedList } from '../../../../shared/testing/utils.test';
import { CdkDragDrop } from '@angular/cdk/drag-drop';
describe('ItemEditBitstreamBundleComponent', () => { describe('ItemEditBitstreamBundleComponent', () => {
let comp: ItemEditBitstreamBundleComponent; let comp: ItemEditBitstreamBundleComponent;
@@ -31,10 +45,33 @@ 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(() => { beforeEach(waitForAsync(() => {
objectUpdatesService = jasmine.createSpyObj('objectUpdatesService', {
initialize: undefined,
getFieldUpdatesExclusive: of(null),
});
itemBitstreamsService = getItemBitstreamsServiceStub();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()], imports: [TranslateModule.forRoot()],
declarations: [ItemEditBitstreamBundleComponent], declarations: [ItemEditBitstreamBundleComponent],
providers: [
{ provide: BundleDataService, useValue: bundleService },
{ provide: ObjectUpdatesService, useValue: objectUpdatesService },
{ provide: PaginationService, useValue: new PaginationServiceStub() },
{ provide: RequestService, useValue: getMockRequestService() },
{ provide: ItemBitstreamsService, useValue: itemBitstreamsService },
],
schemas: [ schemas: [
NO_ERRORS_SCHEMA NO_ERRORS_SCHEMA
] ]
@@ -55,4 +92,251 @@ describe('ItemEditBitstreamBundleComponent', () => {
it('should create an embedded view of the component', () => { it('should create an embedded view of the component', () => {
expect(viewContainerRef.createEmbeddedView).toHaveBeenCalled(); 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,14 +1,48 @@
import { Component, EventEmitter, Input, OnInit, Output, ViewChild, ViewContainerRef } from '@angular/core'; import {
Component,
Input,
OnInit,
ViewChild,
ViewContainerRef, OnDestroy,
} from '@angular/core';
import { Bundle } from '../../../../core/shared/bundle.model'; import { Bundle } from '../../../../core/shared/bundle.model';
import { Item } from '../../../../core/shared/item.model'; import { Item } from '../../../../core/shared/item.model';
import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes'; import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes';
import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes'; import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { getItemPageRoute } from '../../../item-page-routing-paths'; import { getItemPageRoute } from '../../../item-page-routing-paths';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { RemoteData } from 'src/app/core/data/remote-data';
import { PaginatedList } from 'src/app/core/data/paginated-list.model';
import { Bitstream } from 'src/app/core/shared/bitstream.model';
import { Observable, BehaviorSubject, switchMap, shareReplay, Subscription } from 'rxjs';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { FieldUpdates } from '../../../../core/data/object-updates/field-updates.model';
import { PaginatedSearchOptions } from '../../../../shared/search/models/paginated-search-options.model';
import { BundleDataService } from '../../../../core/data/bundle-data.service';
import { followLink } from '../../../../shared/utils/follow-link-config.model';
import {
getAllSucceededRemoteData,
paginatedListToArray,
} from '../../../../core/shared/operators';
import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service';
import { map, take, filter, tap } from 'rxjs/operators';
import { FieldChangeType } from '../../../../core/data/object-updates/field-change-type.model';
import { FieldUpdate } from '../../../../core/data/object-updates/field-update.model';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { PaginationComponent } from '../../../../shared/pagination/pagination.component';
import { RequestService } from '../../../../core/data/request.service';
import {
ItemBitstreamsService,
BitstreamTableEntry,
SelectedBitstreamTableEntry,
MOVE_KEY, SelectionAction
} from '../item-bitstreams.service';
import { CdkDragDrop } from '@angular/cdk/drag-drop';
import { hasValue, hasNoValue } from '../../../../shared/empty.util';
@Component({ @Component({
selector: 'ds-item-edit-bitstream-bundle', 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', templateUrl: './item-edit-bitstream-bundle.component.html',
}) })
/** /**
@@ -16,13 +50,24 @@ import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
* Creates an embedded view of the contents. This is to ensure the table structure won't break. * Creates an embedded view of the contents. This is to ensure the table structure won't break.
* (which means it'll be added to the parents html without a wrapping ds-item-edit-bitstream-bundle element) * (which means it'll be added to the parents html without a wrapping ds-item-edit-bitstream-bundle element)
*/ */
export class ItemEditBitstreamBundleComponent implements OnInit { export class ItemEditBitstreamBundleComponent implements OnInit, OnDestroy {
protected readonly FieldChangeType = FieldChangeType;
/** /**
* The view on the bundle information and bitstreams * The view on the bundle information and bitstreams
*/ */
@ViewChild('bundleView', {static: true}) bundleView; @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 * The bundle to display bitstreams for
*/ */
@@ -39,11 +84,9 @@ export class ItemEditBitstreamBundleComponent implements OnInit {
@Input() columnSizes: ResponsiveTableSizes; @Input() columnSizes: ResponsiveTableSizes;
/** /**
* Send an event when the user drops an object on the pagination * Whether this is the first in a series of bundle tables
* 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)
*/ */
@Output() dropObject: EventEmitter<any> = new EventEmitter<any>(); @Input() isFirstTable = false;
/** /**
* The bootstrap sizes used for the Bundle Name column * The bootstrap sizes used for the Bundle Name column
@@ -56,9 +99,65 @@ export class ItemEditBitstreamBundleComponent implements OnInit {
*/ */
itemPageRoute: string; 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( constructor(
protected viewContainerRef: ViewContainerRef, protected viewContainerRef: ViewContainerRef,
public dsoNameService: DSONameService, public dsoNameService: DSONameService,
protected bundleService: BundleDataService,
protected objectUpdatesService: ObjectUpdatesService,
protected paginationService: PaginationService,
protected requestService: RequestService,
protected itemBitstreamsService: ItemBitstreamsService,
) { ) {
} }
@@ -66,5 +165,383 @@ export class ItemEditBitstreamBundleComponent implements OnInit {
this.bundleNameColumn = this.columnSizes.combineColumns(0, 2); this.bundleNameColumn = this.columnSizes.combineColumns(0, 2);
this.viewContainerRef.createEmbeddedView(this.bundleView); this.viewContainerRef.createEmbeddedView(this.bundleView);
this.itemPageRoute = getItemPageRoute(this.item); this.itemPageRoute = getItemPageRoute(this.item);
this.bundleName = this.dsoNameService.getName(this.bundle);
this.bundleUrl = this.bundle.self;
this.initializePagination();
this.initializeBitstreams();
this.initializeSelectionActions();
}
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(1),
);
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 >= 0;
}
/**
* 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);
} }
} }

View File

@@ -1,32 +0,0 @@
<ds-pagination *ngIf="(objectsRD$ | async)?.payload"
[hideGear]="true"
[hidePagerWhenSinglePage]="true"
[hidePaginationDetail]="true"
[paginationOptions]="options"
[collectionSize]="(objectsRD$ | async)?.payload?.totalElements">
<ng-container *ngIf="!(loading$ | async)">
<div [id]="bundle.id" class="bundle-bitstreams-list"
[ngClass]="{'mb-3': (objectsRD$ | async)?.payload?.totalElements > pageSize}"
*ngVar="(updates$ | async) as updates" cdkDropList (cdkDropListDropped)="drop($event)">
<ng-container *ngIf="updates">
<div class="row bitstream-row" *ngFor="let uuid of customOrder" cdkDrag
[id]="uuid"
[ngClass]="{
'table-warning': updates[uuid].changeType === 0,
'table-danger': updates[uuid].changeType === 2,
'table-success': updates[uuid].changeType === 1,
'bg-white': updates[uuid].changeType === undefined
}">
<ds-item-edit-bitstream [fieldUpdate]="updates[uuid]"
[bundleUrl]="bundle.self"
[columnSizes]="columnSizes">
<div class="d-flex align-items-center bitstream-row-drag-handle" slot="drag-handle" cdkDragHandle tabindex="0">
<ds-item-edit-bitstream-drag-handle></ds-item-edit-bitstream-drag-handle>
</div>
</ds-item-edit-bitstream>
</div>
</ng-container>
</div>
</ng-container>
<ds-themed-loading *ngIf="(loading$ | async)" [message]="'loading.bitstreams' | translate"></ds-themed-loading>
</ds-pagination>

View File

@@ -1,150 +0,0 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Bundle } from '../../../../../core/shared/bundle.model';
import { TranslateModule } from '@ngx-translate/core';
import { PaginatedDragAndDropBitstreamListComponent } from './paginated-drag-and-drop-bitstream-list.component';
import { VarDirective } from '../../../../../shared/utils/var.directive';
import { ObjectValuesPipe } from '../../../../../shared/utils/object-values-pipe';
import { ObjectUpdatesService } from '../../../../../core/data/object-updates/object-updates.service';
import { BundleDataService } from '../../../../../core/data/bundle-data.service';
import { Bitstream } from '../../../../../core/shared/bitstream.model';
import { BitstreamFormat } from '../../../../../core/shared/bitstream-format.model';
import { of as observableOf } from 'rxjs';
import { take } from 'rxjs/operators';
import { ResponsiveTableSizes } from '../../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { ResponsiveColumnSizes } from '../../../../../shared/responsive-table-sizes/responsive-column-sizes';
import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote-data.utils';
import { createPaginatedList } from '../../../../../shared/testing/utils.test';
import { RequestService } from '../../../../../core/data/request.service';
import { PaginationService } from '../../../../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../../../../shared/testing/pagination-service.stub';
describe('PaginatedDragAndDropBitstreamListComponent', () => {
let comp: PaginatedDragAndDropBitstreamListComponent;
let fixture: ComponentFixture<PaginatedDragAndDropBitstreamListComponent>;
let objectUpdatesService: ObjectUpdatesService;
let bundleService: BundleDataService;
let objectValuesPipe: ObjectValuesPipe;
let requestService: RequestService;
let paginationService;
const columnSizes = 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)
]);
const bundle = Object.assign(new Bundle(), {
id: 'bundle-1',
uuid: 'bundle-1',
_links: {
self: { href: 'bundle-1-selflink' }
}
});
const date = new Date();
const format = Object.assign(new BitstreamFormat(), {
shortDescription: 'PDF'
});
const bitstream1 = Object.assign(new Bitstream(), {
uuid: 'bitstreamUUID1',
name: 'Fake Bitstream 1',
bundleName: 'ORIGINAL',
description: 'Description',
format: createSuccessfulRemoteDataObject$(format)
});
const fieldUpdate1 = {
field: bitstream1,
changeType: undefined
};
const bitstream2 = Object.assign(new Bitstream(), {
uuid: 'bitstreamUUID2',
name: 'Fake Bitstream 2',
bundleName: 'ORIGINAL',
description: 'Description',
format: createSuccessfulRemoteDataObject$(format)
});
const fieldUpdate2 = {
field: bitstream2,
changeType: undefined
};
beforeEach(waitForAsync(() => {
objectUpdatesService = jasmine.createSpyObj('objectUpdatesService',
{
getFieldUpdates: observableOf({
[bitstream1.uuid]: fieldUpdate1,
[bitstream2.uuid]: fieldUpdate2,
}),
getFieldUpdatesExclusive: observableOf({
[bitstream1.uuid]: fieldUpdate1,
[bitstream2.uuid]: fieldUpdate2,
}),
getFieldUpdatesByCustomOrder: observableOf({
[bitstream1.uuid]: fieldUpdate1,
[bitstream2.uuid]: fieldUpdate2,
}),
saveMoveFieldUpdate: {},
saveRemoveFieldUpdate: {},
removeSingleFieldUpdate: {},
saveAddFieldUpdate: {},
discardFieldUpdates: {},
reinstateFieldUpdates: observableOf(true),
initialize: {},
getUpdatedFields: observableOf([bitstream1, bitstream2]),
getLastModified: observableOf(date),
hasUpdates: observableOf(true),
isReinstatable: observableOf(false),
isValidPage: observableOf(true),
initializeWithCustomOrder: {},
addPageToCustomOrder: {}
}
);
bundleService = jasmine.createSpyObj('bundleService', {
getBitstreams: createSuccessfulRemoteDataObject$(createPaginatedList([bitstream1, bitstream2])),
getBitstreamsEndpoint: observableOf('')
});
objectValuesPipe = new ObjectValuesPipe();
requestService = jasmine.createSpyObj('requestService', {
hasByHref$: observableOf(true)
});
paginationService = new PaginationServiceStub();
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()],
declarations: [PaginatedDragAndDropBitstreamListComponent, VarDirective],
providers: [
{ provide: ObjectUpdatesService, useValue: objectUpdatesService },
{ provide: BundleDataService, useValue: bundleService },
{ provide: ObjectValuesPipe, useValue: objectValuesPipe },
{ provide: RequestService, useValue: requestService },
{ provide: PaginationService, useValue: paginationService }
], schemas: [
NO_ERRORS_SCHEMA
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PaginatedDragAndDropBitstreamListComponent);
comp = fixture.componentInstance;
comp.bundle = bundle;
comp.columnSizes = columnSizes;
fixture.detectChanges();
});
it('should initialize the objectsRD$', (done) => {
comp.objectsRD$.pipe(take(1)).subscribe((objects) => {
expect(objects.payload.page).toEqual([bitstream1, bitstream2]);
done();
});
});
it('should initialize the URL', () => {
expect(comp.url).toEqual(bundle.self);
});
});

View File

@@ -1,76 +0,0 @@
import { AbstractPaginatedDragAndDropListComponent } from '../../../../../shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component';
import { Component, ElementRef, Input, OnInit } from '@angular/core';
import { Bundle } from '../../../../../core/shared/bundle.model';
import { Bitstream } from '../../../../../core/shared/bitstream.model';
import { ObjectUpdatesService } from '../../../../../core/data/object-updates/object-updates.service';
import { BundleDataService } from '../../../../../core/data/bundle-data.service';
import { switchMap } from 'rxjs/operators';
import { PaginatedSearchOptions } from '../../../../../shared/search/models/paginated-search-options.model';
import { ResponsiveTableSizes } from '../../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { followLink } from '../../../../../shared/utils/follow-link-config.model';
import { ObjectValuesPipe } from '../../../../../shared/utils/object-values-pipe';
import { RequestService } from '../../../../../core/data/request.service';
import { PaginationService } from '../../../../../core/pagination/pagination.service';
import { PaginationComponentOptions } from '../../../../../shared/pagination/pagination-component-options.model';
@Component({
selector: 'ds-paginated-drag-and-drop-bitstream-list',
styleUrls: ['../../item-bitstreams.component.scss'],
templateUrl: './paginated-drag-and-drop-bitstream-list.component.html',
})
/**
* A component listing edit-bitstream rows for each bitstream within the given bundle.
* This component makes use of the AbstractPaginatedDragAndDropListComponent, allowing for users to drag and drop
* bitstreams within the paginated list. To drag and drop a bitstream between two pages, drag the row on top of the
* page number you want the bitstream to end up at. Doing so will add the bitstream to the top of that page.
*/
export class PaginatedDragAndDropBitstreamListComponent extends AbstractPaginatedDragAndDropListComponent<Bitstream> implements OnInit {
/**
* The bundle to display bitstreams for
*/
@Input() bundle: Bundle;
/**
* The bootstrap sizes used for the columns within this table
*/
@Input() columnSizes: ResponsiveTableSizes;
constructor(protected objectUpdatesService: ObjectUpdatesService,
protected elRef: ElementRef,
protected objectValuesPipe: ObjectValuesPipe,
protected bundleService: BundleDataService,
protected paginationService: PaginationService,
protected requestService: RequestService) {
super(objectUpdatesService, elRef, objectValuesPipe, paginationService);
}
ngOnInit() {
super.ngOnInit();
}
/**
* Initialize the bitstreams observable depending on currentPage$
*/
initializeObjectsRD(): void {
this.objectsRD$ = this.currentPage$.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')
))
);
})
);
}
/**
* Initialize the URL used for the field-update store, in this case the bundle's self-link
*/
initializeURL(): void {
this.url = this.bundle.self;
}
}

View File

@@ -1,5 +0,0 @@
<ng-template #handleView>
<div class="drag-handle text-muted float-left p-1 mr-2" tabindex="0">
<i class="fas fa-grip-vertical fa-fw" [title]="'item.edit.bitstreams.edit.buttons.drag' | translate"></i>
</div>
</ng-template>

View File

@@ -1,26 +0,0 @@
import { Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
selector: 'ds-item-edit-bitstream-drag-handle',
styleUrls: ['../item-bitstreams.component.scss'],
templateUrl: './item-edit-bitstream-drag-handle.component.html',
})
/**
* Component displaying a drag handle for the item-edit-bitstream page
* Creates an embedded view of the contents
* (which means it'll be added to the parents html without a wrapping ds-item-edit-bitstream-drag-handle element)
*/
export class ItemEditBitstreamDragHandleComponent implements OnInit {
/**
* The view on the drag-handle
*/
@ViewChild('handleView', {static: true}) handleView;
constructor(private viewContainerRef: ViewContainerRef) {
}
ngOnInit(): void {
this.viewContainerRef.createEmbeddedView(this.handleView);
}
}

View File

@@ -1,55 +0,0 @@
<ng-template #bitstreamView>
<div class="{{columnSizes.columns[0].buildClasses()}} row-element d-flex">
<ng-content select="[slot=drag-handle]"></ng-content>
<div class="float-left d-flex align-items-center overflow-hidden">
<span class="text-truncate">
{{ bitstreamName }}
</span>
</div>
</div>
<div class="{{columnSizes.columns[1].buildClasses()}} row-element d-flex align-items-center">
<div class="w-100">
<div class="text-truncate" [tooltipClass]="'larger-tooltip'" placement="bottom"
[ngbTooltip]="bitstream?.firstMetadataValue('dc.description')">
{{ bitstream?.firstMetadataValue('dc.description') }}
</div>
</div>
</div>
<div class="{{columnSizes.columns[2].buildClasses()}} row-element d-flex align-items-center">
<div class="text-center w-100">
<span class="text-truncate">
{{ (format$ | async)?.shortDescription }}
</span>
</div>
</div>
<div class="{{columnSizes.columns[3].buildClasses()}} row-element d-flex align-items-center">
<div class="text-center w-100">
<div class="btn-group relationship-action-buttons">
<a *ngIf="bitstreamDownloadUrl != null" [routerLink]="bitstreamDownloadUrl"
[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/', bitstream.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()" (click)="remove()"
[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()" (click)="undo()"
[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>
</div>
</ng-template>

View File

@@ -1,149 +0,0 @@
import { ItemEditBitstreamComponent } from './item-edit-bitstream.component';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service';
import { of as observableOf } from 'rxjs';
import { Bitstream } from '../../../../core/shared/bitstream.model';
import { TranslateModule } from '@ngx-translate/core';
import { VarDirective } from '../../../../shared/utils/var.directive';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { BitstreamFormat } from '../../../../core/shared/bitstream-format.model';
import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { getBitstreamDownloadRoute } from '../../../../app-routing-paths';
import { By } from '@angular/platform-browser';
import { BrowserOnlyMockPipe } from '../../../../shared/testing/browser-only-mock.pipe';
import { RouterTestingModule } from '@angular/router/testing';
let comp: ItemEditBitstreamComponent;
let fixture: ComponentFixture<ItemEditBitstreamComponent>;
const columnSizes = 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)
]);
const format = Object.assign(new BitstreamFormat(), {
shortDescription: 'PDF'
});
const bitstream = Object.assign(new Bitstream(), {
uuid: 'bitstreamUUID',
name: 'Fake Bitstream',
bundleName: 'ORIGINAL',
description: 'Description',
_links: {
content: { href: 'content-link' }
},
format: createSuccessfulRemoteDataObject$(format)
});
const fieldUpdate = {
field: bitstream,
changeType: undefined
};
const date = new Date();
const url = 'thisUrl';
let objectUpdatesService: ObjectUpdatesService;
describe('ItemEditBitstreamComponent', () => {
beforeEach(waitForAsync(() => {
objectUpdatesService = jasmine.createSpyObj('objectUpdatesService',
{
getFieldUpdates: observableOf({
[bitstream.uuid]: fieldUpdate,
}),
getFieldUpdatesExclusive: observableOf({
[bitstream.uuid]: fieldUpdate,
}),
saveRemoveFieldUpdate: {},
removeSingleFieldUpdate: {},
saveAddFieldUpdate: {},
discardFieldUpdates: {},
reinstateFieldUpdates: observableOf(true),
initialize: {},
getUpdatedFields: observableOf([bitstream]),
getLastModified: observableOf(date),
hasUpdates: observableOf(true),
isReinstatable: observableOf(false),
isValidPage: observableOf(true)
}
);
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
TranslateModule.forRoot(),
],
declarations: [
ItemEditBitstreamComponent,
VarDirective,
BrowserOnlyMockPipe,
],
providers: [
{ provide: ObjectUpdatesService, useValue: objectUpdatesService }
], schemas: [
NO_ERRORS_SCHEMA
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ItemEditBitstreamComponent);
comp = fixture.componentInstance;
comp.fieldUpdate = fieldUpdate;
comp.bundleUrl = url;
comp.columnSizes = columnSizes;
comp.ngOnChanges(undefined);
fixture.detectChanges();
});
describe('when remove is called', () => {
beforeEach(() => {
comp.remove();
});
it('should call saveRemoveFieldUpdate on objectUpdatesService', () => {
expect(objectUpdatesService.saveRemoveFieldUpdate).toHaveBeenCalledWith(url, bitstream);
});
});
describe('when undo is called', () => {
beforeEach(() => {
comp.undo();
});
it('should call removeSingleFieldUpdate on objectUpdatesService', () => {
expect(objectUpdatesService.removeSingleFieldUpdate).toHaveBeenCalledWith(url, bitstream.uuid);
});
});
describe('when canRemove is called', () => {
it('should return true', () => {
expect(comp.canRemove()).toEqual(true);
});
});
describe('when canUndo is called', () => {
it('should return false', () => {
expect(comp.canUndo()).toEqual(false);
});
});
describe('when the component loads', () => {
it('should contain download button with a valid link to the bitstreams download page', () => {
fixture.detectChanges();
const downloadBtnHref = fixture.debugElement.query(By.css('[data-test="download-button"]')).nativeElement.getAttribute('href');
expect(downloadBtnHref).toEqual(comp.bitstreamDownloadUrl);
});
});
describe('when the bitstreamDownloadUrl property gets populated', () => {
it('should contain the bitstream download page route', () => {
expect(comp.bitstreamDownloadUrl).not.toEqual(bitstream._links.content.href);
expect(comp.bitstreamDownloadUrl).toEqual(getBitstreamDownloadRoute(bitstream));
});
});
});

View File

@@ -1,117 +0,0 @@
import { Component, Input, OnChanges, OnInit, SimpleChanges, ViewChild, ViewContainerRef } from '@angular/core';
import { Bitstream } from '../../../../core/shared/bitstream.model';
import cloneDeep from 'lodash/cloneDeep';
import { ObjectUpdatesService } from '../../../../core/data/object-updates/object-updates.service';
import { Observable } from 'rxjs';
import { BitstreamFormat } from '../../../../core/shared/bitstream-format.model';
import { getRemoteDataPayload, getFirstSucceededRemoteData } from '../../../../core/shared/operators';
import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { FieldUpdate } from '../../../../core/data/object-updates/field-update.model';
import { FieldChangeType } from '../../../../core/data/object-updates/field-change-type.model';
import { getBitstreamDownloadRoute } from '../../../../app-routing-paths';
@Component({
selector: 'ds-item-edit-bitstream',
styleUrls: ['../item-bitstreams.component.scss'],
templateUrl: './item-edit-bitstream.component.html',
})
/**
* Component that displays a single bitstream of an item on the edit page
* Creates an embedded view of the contents
* (which means it'll be added to the parents html without a wrapping ds-item-edit-bitstream element)
*/
export class ItemEditBitstreamComponent implements OnChanges, OnInit {
/**
* The view on the bitstream
*/
@ViewChild('bitstreamView', {static: true}) bitstreamView;
/**
* The current field, value and state of the bitstream
*/
@Input() fieldUpdate: FieldUpdate;
/**
* The url of the bundle
*/
@Input() bundleUrl: string;
/**
* The bootstrap sizes used for the columns within this table
*/
@Input() columnSizes: ResponsiveTableSizes;
/**
* The bitstream of this field
*/
bitstream: Bitstream;
/**
* The bitstream's name
*/
bitstreamName: string;
/**
* The bitstream's download url
*/
bitstreamDownloadUrl: string;
/**
* The format of the bitstream
*/
format$: Observable<BitstreamFormat>;
constructor(private objectUpdatesService: ObjectUpdatesService,
private dsoNameService: DSONameService,
private viewContainerRef: ViewContainerRef) {
}
ngOnInit(): void {
this.viewContainerRef.createEmbeddedView(this.bitstreamView);
}
/**
* Update the current bitstream and its format on changes
* @param changes
*/
ngOnChanges(changes: SimpleChanges): void {
this.bitstream = cloneDeep(this.fieldUpdate.field) as Bitstream;
this.bitstreamName = this.dsoNameService.getName(this.bitstream);
this.bitstreamDownloadUrl = getBitstreamDownloadRoute(this.bitstream);
this.format$ = this.bitstream.format.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload()
);
}
/**
* Sends a new remove update for this field to the object updates service
*/
remove(): void {
this.objectUpdatesService.saveRemoveFieldUpdate(this.bundleUrl, this.bitstream);
}
/**
* Cancels the current update for this field in the object updates service
*/
undo(): void {
this.objectUpdatesService.removeSingleFieldUpdate(this.bundleUrl, this.bitstream.uuid);
}
/**
* Check if a user should be allowed to remove this field
*/
canRemove(): boolean {
return this.fieldUpdate.changeType !== FieldChangeType.REMOVE;
}
/**
* Check if a user should be allowed to cancel the update to this field
*/
canUndo(): boolean {
return this.fieldUpdate.changeType >= 0;
}
}

View File

@@ -278,8 +278,8 @@ export class ItemDeleteComponent
this.linkService.resolveLinks( this.linkService.resolveLinks(
relationship, relationship,
followLink('relationshipType'), followLink('relationshipType'),
followLink('leftItem'), followLink('leftItem', undefined, followLink<Item>('accessStatus')),
followLink('rightItem'), followLink('rightItem', undefined, followLink<Item>('accessStatus')),
); );
return relationship.relationshipType.pipe( return relationship.relationshipType.pipe(
getFirstSucceededRemoteData(), getFirstSucceededRemoteData(),

View File

@@ -36,6 +36,7 @@ import { APP_CONFIG } from '../../../../../config/app-config.interface';
import { EditItemRelationshipsServiceStub } from '../../../../shared/testing/edit-item-relationships.service.stub'; import { EditItemRelationshipsServiceStub } from '../../../../shared/testing/edit-item-relationships.service.stub';
import { EditItemRelationshipsService } from '../edit-item-relationships.service'; import { EditItemRelationshipsService } from '../edit-item-relationships.service';
import { cold } from 'jasmine-marbles'; import { cold } from 'jasmine-marbles';
import { environment } from '../../../../../environments/environment.test';
describe('EditRelationshipListComponent', () => { describe('EditRelationshipListComponent', () => {
@@ -79,7 +80,7 @@ describe('EditRelationshipListComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}; };
function init(leftType: string, rightType: string): void { function init(leftType: string, rightType: string, leftMaxCardinality?: number, rightMaxCardinality?: number): void {
entityTypeLeft = Object.assign(new ItemType(), { entityTypeLeft = Object.assign(new ItemType(), {
id: leftType, id: leftType,
uuid: leftType, uuid: leftType,
@@ -99,6 +100,8 @@ describe('EditRelationshipListComponent', () => {
rightType: createSuccessfulRemoteDataObject$(entityTypeRight), rightType: createSuccessfulRemoteDataObject$(entityTypeRight),
leftwardType: `is${rightType}Of${leftType}`, leftwardType: `is${rightType}Of${leftType}`,
rightwardType: `is${leftType}Of${rightType}`, rightwardType: `is${leftType}Of${rightType}`,
leftMaxCardinality: leftMaxCardinality,
rightMaxCardinality: rightMaxCardinality,
}); });
paginationOptions = Object.assign(new PaginationComponentOptions(), { paginationOptions = Object.assign(new PaginationComponentOptions(), {
@@ -213,11 +216,11 @@ describe('EditRelationshipListComponent', () => {
editItemRelationshipsService = new EditItemRelationshipsServiceStub(); editItemRelationshipsService = new EditItemRelationshipsServiceStub();
const environmentUseThumbs = { const environmentUseThumbs = Object.assign({}, environment, {
browseBy: { browseBy: {
showThumbnails: true showThumbnails: true
} }
}; });
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [SharedModule, TranslateModule.forRoot()], imports: [SharedModule, TranslateModule.forRoot()],
@@ -369,4 +372,31 @@ describe('EditRelationshipListComponent', () => {
})); }));
}); });
}); });
describe('Is repeatable relationship', () => {
beforeEach(waitForAsync(() => {
currentItemIsLeftItem$ = new BehaviorSubject<boolean>(true);
}));
describe('when max cardinality is 1', () => {
beforeEach(waitForAsync(() => init('Publication', 'OrgUnit', 1, undefined)));
it('should return false', () => {
const result = (comp as any).isRepeatable();
expect(result).toBeFalse();
});
});
describe('when max cardinality is 2', () => {
beforeEach(waitForAsync(() => init('Publication', 'OrgUnit', 2, undefined)));
it('should return true', () => {
const result = (comp as any).isRepeatable();
expect(result).toBeTrue();
});
});
describe('when max cardinality is undefined', () => {
beforeEach(waitForAsync(() => init('Publication', 'OrgUnit', undefined, undefined)));
it('should return true', () => {
const result = (comp as any).isRepeatable();
expect(result).toBeTrue();
});
});
});
}); });

View File

@@ -233,6 +233,22 @@ export class EditRelationshipListComponent implements OnInit, OnDestroy {
return update && update.field ? update.field.uuid : undefined; return update && update.field ? update.field.uuid : undefined;
} }
/**
* Check whether the current entity can have multiple relationships of this type
* This is based on the max cardinality of the relationship
* @private
*/
private isRepeatable(): boolean {
const isLeft = this.currentItemIsLeftItem$.getValue();
if (isLeft) {
const leftMaxCardinality = this.relationshipType.leftMaxCardinality;
return hasNoValue(leftMaxCardinality) || leftMaxCardinality > 1;
} else {
const rightMaxCardinality = this.relationshipType.rightMaxCardinality;
return hasNoValue(rightMaxCardinality) || rightMaxCardinality > 1;
}
}
/** /**
* Open the dynamic lookup modal to search for items to add as relationships * Open the dynamic lookup modal to search for items to add as relationships
*/ */
@@ -250,6 +266,7 @@ export class EditRelationshipListComponent implements OnInit, OnDestroy {
modalComp.toAdd = []; modalComp.toAdd = [];
modalComp.toRemove = []; modalComp.toRemove = [];
modalComp.isPending = false; modalComp.isPending = false;
modalComp.repeatable = this.isRepeatable();
modalComp.hiddenQuery = '-search.resourceid:' + this.item.uuid; modalComp.hiddenQuery = '-search.resourceid:' + this.item.uuid;
this.item.owningCollection.pipe( this.item.owningCollection.pipe(
@@ -447,7 +464,7 @@ export class EditRelationshipListComponent implements OnInit, OnDestroy {
); );
// this adds thumbnail images when required by configuration // this adds thumbnail images when required by configuration
let linksToFollow: FollowLinkConfig<Relationship>[] = itemLinksToFollow(this.fetchThumbnail); let linksToFollow: FollowLinkConfig<Relationship>[] = itemLinksToFollow(this.fetchThumbnail, this.appConfig.item.showAccessStatuses);
this.subs.push( this.subs.push(
observableCombineLatest([ observableCombineLatest([

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