Merge remote-tracking branch 'github/main' into main_CST-12825

# Conflicts:
#	src/assets/i18n/en.json5
#	src/styles/_custom_variables.scss
This commit is contained in:
Vincenzo Mecca
2024-02-13 11:20:26 +01:00
315 changed files with 11088 additions and 1674 deletions

View File

@@ -33,6 +33,8 @@ jobs:
#CHROME_VERSION: "90.0.4430.212-1" #CHROME_VERSION: "90.0.4430.212-1"
# Bump Node heap size (OOM in CI after upgrading to Angular 15) # Bump Node heap size (OOM in CI after upgrading to Angular 15)
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
COMPOSE_PROJECT_NAME: 'ci'
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:

View File

@@ -9,8 +9,9 @@ export default defineConfig({
openMode: 0, openMode: 0,
}, },
env: { env: {
// Global constants used in DSpace e2e tests (see also ./cypress/support/e2e.ts) // Global DSpace environment variables used in all our Cypress e2e tests
// May be overridden in our cypress.json config file using specified environment variables. // May be modified in this config, or overridden in a variety of ways.
// See Cypress environment variable docs: https://docs.cypress.io/guides/guides/environment-variables
// Default values listed here are all valid for the Demo Entities Data set available at // Default values listed here are all valid for the Demo Entities Data set available at
// https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data // https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data
// (This is the data set used in our CI environment) // (This is the data set used in our CI environment)
@@ -21,12 +22,14 @@ export default defineConfig({
// Community/collection/publication used for view/edit tests // Community/collection/publication used for view/edit tests
DSPACE_TEST_COMMUNITY: '0958c910-2037-42a9-81c7-dca80e3892b4', DSPACE_TEST_COMMUNITY: '0958c910-2037-42a9-81c7-dca80e3892b4',
DSPACE_TEST_COLLECTION: '282164f5-d325-4740-8dd1-fa4d6d3e7200', DSPACE_TEST_COLLECTION: '282164f5-d325-4740-8dd1-fa4d6d3e7200',
DSPACE_TEST_ENTITY_PUBLICATION: 'e98b0f27-5c19-49a0-960d-eb6ad5287067', DSPACE_TEST_ENTITY_PUBLICATION: '6160810f-1e53-40db-81ef-f6621a727398',
// Search term (should return results) used in search tests // Search term (should return results) used in search tests
DSPACE_TEST_SEARCH_TERM: 'test', DSPACE_TEST_SEARCH_TERM: 'test',
// Collection used for submission tests // Main Collection used for submission tests. Should be able to accept normal Item objects
DSPACE_TEST_SUBMIT_COLLECTION_NAME: 'Sample Collection', DSPACE_TEST_SUBMIT_COLLECTION_NAME: 'Sample Collection',
DSPACE_TEST_SUBMIT_COLLECTION_UUID: '9d8334e9-25d3-4a67-9cea-3dffdef80144', DSPACE_TEST_SUBMIT_COLLECTION_UUID: '9d8334e9-25d3-4a67-9cea-3dffdef80144',
// Collection used for Person entity submission tests. MUST be configured with EntityType=Person.
DSPACE_TEST_SUBMIT_PERSON_COLLECTION_NAME: 'People',
// Account used to test basic submission process // Account used to test basic submission process
DSPACE_TEST_SUBMIT_USER: 'dspacedemo+submit@gmail.com', DSPACE_TEST_SUBMIT_USER: 'dspacedemo+submit@gmail.com',
DSPACE_TEST_SUBMIT_USER_PASSWORD: 'dspace', DSPACE_TEST_SUBMIT_USER_PASSWORD: 'dspace',

View File

@@ -0,0 +1,28 @@
import { Options } from 'cypress-axe';
import { testA11y } from 'cypress/support/utils';
describe('Admin Sidebar', () => {
beforeEach(() => {
// Must login as an Admin for sidebar to appear
cy.visit('/login');
cy.loginViaForm(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
});
it('should be pinnable and pass accessibility tests', () => {
// Pin the sidebar open
cy.get('#sidebar-collapse-toggle').click();
// Click on every expandable section to open all menus
cy.get('ds-expandable-admin-sidebar-section').click({multiple: true});
// Analyze <ds-admin-sidebar> for accessibility
testA11y('ds-admin-sidebar',
{
rules: {
// Currently all expandable sections have nested interactive elements
// See https://github.com/DSpace/dspace-angular/issues/2178
'nested-interactive': { enabled: false },
}
} as Options);
});
});

View File

@@ -1,10 +1,9 @@
import { TEST_ENTITY_PUBLICATION } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Breadcrumbs', () => { describe('Breadcrumbs', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
// Visit an Item, as those have more breadcrumbs // Visit an Item, as those have more breadcrumbs
cy.visit('/entities/publication/'.concat(TEST_ENTITY_PUBLICATION)); cy.visit('/entities/publication/'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION')));
// Wait for breadcrumbs to be visible // Wait for breadcrumbs to be visible
cy.get('ds-breadcrumbs').should('be.visible'); cy.get('ds-breadcrumbs').should('be.visible');

View File

@@ -0,0 +1,128 @@
import { testA11y } from 'cypress/support/utils';
const COLLECTION_EDIT_PAGE = '/collections/'.concat(Cypress.env('DSPACE_TEST_COLLECTION')).concat('/edit');
beforeEach(() => {
// All tests start with visiting the Edit Collection Page
cy.visit(COLLECTION_EDIT_PAGE);
// This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
});
describe('Edit Collection > Edit Metadata tab', () => {
it('should pass accessibility tests', () => {
// <ds-edit-collection> tag must be loaded
cy.get('ds-edit-collection').should('be.visible');
// Analyze <ds-edit-collection> for accessibility issues
testA11y('ds-edit-collection');
});
});
describe('Edit Collection > Assign Roles tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="roles"]').click();
// <ds-collection-roles> tag must be loaded
cy.get('ds-collection-roles').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-collection-roles');
});
});
describe('Edit Collection > Content Source tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="source"]').click();
// <ds-collection-source> tag must be loaded
cy.get('ds-collection-source').should('be.visible');
// Check the external source checkbox (to display all fields on the page)
cy.get('#externalSourceCheck').check();
// Wait for the source controls to appear
cy.get('ds-collection-source-controls').should('be.visible');
// Analyze entire page for accessibility issues
testA11y('ds-collection-source');
});
});
describe('Edit Collection > Curate tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="curate"]').click();
// <ds-collection-curate> tag must be loaded
cy.get('ds-collection-curate').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-collection-curate');
});
});
describe('Edit Collection > Access Control tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="access-control"]').click();
// <ds-collection-access-control> tag must be loaded
cy.get('ds-collection-access-control').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-collection-access-control');
});
});
describe('Edit Collection > Authorizations tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="authorizations"]').click();
// <ds-collection-authorizations> tag must be loaded
cy.get('ds-collection-authorizations').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-collection-authorizations');
});
});
describe('Edit Collection > Item Mapper tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="mapper"]').click();
// <ds-collection-item-mapper> tag must be loaded
cy.get('ds-collection-item-mapper').should('be.visible');
// Analyze entire page for accessibility issues
testA11y('ds-collection-item-mapper');
// Click on the "Map new Items" tab
cy.get('li[data-test="mapTab"] a').click();
// Make sure search form is now visible
cy.get('ds-search-form').should('be.visible');
// Analyze entire page (again) for accessibility issues
testA11y('ds-collection-item-mapper');
});
});
describe('Edit Collection > Delete page', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="delete-button"]').click();
// <ds-delete-collection> tag must be loaded
cy.get('ds-delete-collection').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-delete-collection');
});
});

View File

@@ -1,10 +1,9 @@
import { TEST_COLLECTION } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Collection Page', () => { describe('Collection Page', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.visit('/collections/'.concat(TEST_COLLECTION)); cy.visit('/collections/'.concat(Cypress.env('DSPACE_TEST_COLLECTION')));
// <ds-collection-page> tag must be loaded // <ds-collection-page> tag must be loaded
cy.get('ds-collection-page').should('be.visible'); cy.get('ds-collection-page').should('be.visible');

View File

@@ -1,11 +1,11 @@
import { REGEX_MATCH_NON_EMPTY_TEXT, TEST_COLLECTION } from 'cypress/support/e2e'; import { REGEX_MATCH_NON_EMPTY_TEXT } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Collection Statistics Page', () => { describe('Collection Statistics Page', () => {
const COLLECTIONSTATISTICSPAGE = '/statistics/collections/'.concat(TEST_COLLECTION); const COLLECTIONSTATISTICSPAGE = '/statistics/collections/'.concat(Cypress.env('DSPACE_TEST_COLLECTION'));
it('should load if you click on "Statistics" from a Collection page', () => { it('should load if you click on "Statistics" from a Collection page', () => {
cy.visit('/collections/'.concat(TEST_COLLECTION)); cy.visit('/collections/'.concat(Cypress.env('DSPACE_TEST_COLLECTION')));
cy.get('ds-navbar ds-link-menu-item a[title="Statistics"]').click(); cy.get('ds-navbar ds-link-menu-item a[title="Statistics"]').click();
cy.location('pathname').should('eq', COLLECTIONSTATISTICSPAGE); cy.location('pathname').should('eq', COLLECTIONSTATISTICSPAGE);
}); });
@@ -18,7 +18,7 @@ describe('Collection Statistics Page', () => {
it('should contain a "Total visits per month" section', () => { it('should contain a "Total visits per month" section', () => {
cy.visit(COLLECTIONSTATISTICSPAGE); cy.visit(COLLECTIONSTATISTICSPAGE);
// Check just for existence because this table is empty in CI environment as it's historical data // Check just for existence because this table is empty in CI environment as it's historical data
cy.get('.'.concat(TEST_COLLECTION).concat('_TotalVisitsPerMonth')).should('exist'); cy.get('.'.concat(Cypress.env('DSPACE_TEST_COLLECTION')).concat('_TotalVisitsPerMonth')).should('exist');
}); });
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {

View File

@@ -0,0 +1,86 @@
import { testA11y } from 'cypress/support/utils';
const COMMUNITY_EDIT_PAGE = '/communities/'.concat(Cypress.env('DSPACE_TEST_COMMUNITY')).concat('/edit');
beforeEach(() => {
// All tests start with visiting the Edit Community Page
cy.visit(COMMUNITY_EDIT_PAGE);
// This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
});
describe('Edit Community > Edit Metadata tab', () => {
it('should pass accessibility tests', () => {
// <ds-edit-community> tag must be loaded
cy.get('ds-edit-community').should('be.visible');
// Analyze <ds-edit-community> for accessibility issues
testA11y('ds-edit-community');
});
});
describe('Edit Community > Assign Roles tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="roles"]').click();
// <ds-community-roles> tag must be loaded
cy.get('ds-community-roles').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-community-roles');
});
});
describe('Edit Community > Curate tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="curate"]').click();
// <ds-community-curate> tag must be loaded
cy.get('ds-community-curate').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-community-curate');
});
});
describe('Edit Community > Access Control tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="access-control"]').click();
// <ds-community-access-control> tag must be loaded
cy.get('ds-community-access-control').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-community-access-control');
});
});
describe('Edit Community > Authorizations tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="authorizations"]').click();
// <ds-community-authorizations> tag must be loaded
cy.get('ds-community-authorizations').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-community-authorizations');
});
});
describe('Edit Community > Delete page', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="delete-button"]').click();
// <ds-delete-community> tag must be loaded
cy.get('ds-delete-community').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-delete-community');
});
});

View File

@@ -1,15 +1,14 @@
import { TEST_COMMUNITY } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Community Page', () => { describe('Community Page', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
cy.visit('/communities/'.concat(TEST_COMMUNITY)); cy.visit('/communities/'.concat(Cypress.env('DSPACE_TEST_COMMUNITY')));
// <ds-community-page> tag must be loaded // <ds-community-page> tag must be loaded
cy.get('ds-community-page').should('be.visible'); cy.get('ds-community-page').should('be.visible');
// Analyze <ds-community-page> for accessibility issues // Analyze <ds-community-page> for accessibility issues
testA11y('ds-community-page',); testA11y('ds-community-page');
}); });
}); });

View File

@@ -1,11 +1,11 @@
import { REGEX_MATCH_NON_EMPTY_TEXT, TEST_COMMUNITY } from 'cypress/support/e2e'; import { REGEX_MATCH_NON_EMPTY_TEXT } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Community Statistics Page', () => { describe('Community Statistics Page', () => {
const COMMUNITYSTATISTICSPAGE = '/statistics/communities/'.concat(TEST_COMMUNITY); const COMMUNITYSTATISTICSPAGE = '/statistics/communities/'.concat(Cypress.env('DSPACE_TEST_COMMUNITY'));
it('should load if you click on "Statistics" from a Community page', () => { it('should load if you click on "Statistics" from a Community page', () => {
cy.visit('/communities/'.concat(TEST_COMMUNITY)); cy.visit('/communities/'.concat(Cypress.env('DSPACE_TEST_COMMUNITY')));
cy.get('ds-navbar ds-link-menu-item a[title="Statistics"]').click(); cy.get('ds-navbar ds-link-menu-item a[title="Statistics"]').click();
cy.location('pathname').should('eq', COMMUNITYSTATISTICSPAGE); cy.location('pathname').should('eq', COMMUNITYSTATISTICSPAGE);
}); });
@@ -18,7 +18,7 @@ describe('Community Statistics Page', () => {
it('should contain a "Total visits per month" section', () => { it('should contain a "Total visits per month" section', () => {
cy.visit(COMMUNITYSTATISTICSPAGE); cy.visit(COMMUNITYSTATISTICSPAGE);
// Check just for existence because this table is empty in CI environment as it's historical data // Check just for existence because this table is empty in CI environment as it's historical data
cy.get('.'.concat(TEST_COMMUNITY).concat('_TotalVisitsPerMonth')).should('exist'); cy.get('.'.concat(Cypress.env('DSPACE_TEST_COMMUNITY')).concat('_TotalVisitsPerMonth')).should('exist');
}); });
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {

View File

@@ -1,4 +1,4 @@
import { REGEX_MATCH_NON_EMPTY_TEXT, TEST_ENTITY_PUBLICATION } from 'cypress/support/e2e'; import { REGEX_MATCH_NON_EMPTY_TEXT } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
import '../support/commands'; import '../support/commands';
@@ -11,8 +11,8 @@ describe('Site Statistics Page', () => {
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {
// generate 2 view events on an Item's page // generate 2 view events on an Item's page
cy.generateViewEvent(TEST_ENTITY_PUBLICATION, 'item'); cy.generateViewEvent(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION'), 'item');
cy.generateViewEvent(TEST_ENTITY_PUBLICATION, 'item'); cy.generateViewEvent(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION'), 'item');
cy.visit('/statistics'); cy.visit('/statistics');

135
cypress/e2e/item-edit.cy.ts Normal file
View File

@@ -0,0 +1,135 @@
import { Options } from 'cypress-axe';
import { testA11y } from 'cypress/support/utils';
const ITEM_EDIT_PAGE = '/items/'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION')).concat('/edit');
beforeEach(() => {
// All tests start with visiting the Edit Item Page
cy.visit(ITEM_EDIT_PAGE);
// This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
});
describe('Edit Item > Edit Metadata tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="metadata"]').click();
// <ds-edit-item-page> tag must be loaded
cy.get('ds-edit-item-page').should('be.visible');
// Analyze <ds-edit-item-page> for accessibility issues
testA11y('ds-edit-item-page');
});
});
describe('Edit Item > Status tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="status"]').click();
// <ds-item-status> tag must be loaded
cy.get('ds-item-status').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-item-status');
});
});
describe('Edit Item > Bitstreams tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="bitstreams"]').click();
// <ds-item-bitstreams> tag must be loaded
cy.get('ds-item-bitstreams').should('be.visible');
// Table of item bitstreams must also be loaded
cy.get('div.item-bitstreams').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-item-bitstreams',
{
rules: {
// Currently Bitstreams page loads a pagination component per Bundle
// and they all use the same 'id="p-dad"'.
'duplicate-id': { enabled: false },
}
} as Options
);
});
});
describe('Edit Item > Curate tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="curate"]').click();
// <ds-item-curate> tag must be loaded
cy.get('ds-item-curate').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-item-curate');
});
});
describe('Edit Item > Relationships tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="relationships"]').click();
// <ds-item-relationships> tag must be loaded
cy.get('ds-item-relationships').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-item-relationships');
});
});
describe('Edit Item > Version History tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="versionhistory"]').click();
// <ds-item-version-history> tag must be loaded
cy.get('ds-item-version-history').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-item-version-history');
});
});
describe('Edit Item > Access Control tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="access-control"]').click();
// <ds-item-access-control> tag must be loaded
cy.get('ds-item-access-control').should('be.visible');
// Analyze for accessibility issues
testA11y('ds-item-access-control');
});
});
describe('Edit Item > Collection Mapper tab', () => {
it('should pass accessibility tests', () => {
cy.get('a[data-test="mapper"]').click();
// <ds-item-collection-mapper> tag must be loaded
cy.get('ds-item-collection-mapper').should('be.visible');
// Analyze entire page for accessibility issues
testA11y('ds-item-collection-mapper');
// Click on the "Map new collections" tab
cy.get('li[data-test="mapTab"] a').click();
// Make sure search form is now visible
cy.get('ds-search-form').should('be.visible');
// Analyze entire page (again) for accessibility issues
testA11y('ds-item-collection-mapper');
});
});

View File

@@ -1,9 +1,8 @@
import { TEST_ENTITY_PUBLICATION } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Item Page', () => { describe('Item Page', () => {
const ITEMPAGE = '/items/'.concat(TEST_ENTITY_PUBLICATION); const ITEMPAGE = '/items/'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION'));
const ENTITYPAGE = '/entities/publication/'.concat(TEST_ENTITY_PUBLICATION); const ENTITYPAGE = '/entities/publication/'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION'));
// Test that entities will redirect to /entities/[type]/[uuid] when accessed via /items/[uuid] // Test that entities will redirect to /entities/[type]/[uuid] when accessed via /items/[uuid]
it('should redirect to the entity page when navigating to an item page', () => { it('should redirect to the entity page when navigating to an item page', () => {

View File

@@ -1,11 +1,11 @@
import { REGEX_MATCH_NON_EMPTY_TEXT, TEST_ENTITY_PUBLICATION } from 'cypress/support/e2e'; import { REGEX_MATCH_NON_EMPTY_TEXT } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Item Statistics Page', () => { describe('Item Statistics Page', () => {
const ITEMSTATISTICSPAGE = '/statistics/items/'.concat(TEST_ENTITY_PUBLICATION); const ITEMSTATISTICSPAGE = '/statistics/items/'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION'));
it('should load if you click on "Statistics" from an Item/Entity page', () => { it('should load if you click on "Statistics" from an Item/Entity page', () => {
cy.visit('/entities/publication/'.concat(TEST_ENTITY_PUBLICATION)); cy.visit('/entities/publication/'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION')));
cy.get('ds-navbar ds-link-menu-item a[title="Statistics"]').click(); cy.get('ds-navbar ds-link-menu-item a[title="Statistics"]').click();
cy.location('pathname').should('eq', ITEMSTATISTICSPAGE); cy.location('pathname').should('eq', ITEMSTATISTICSPAGE);
}); });
@@ -24,7 +24,7 @@ describe('Item Statistics Page', () => {
it('should contain a "Total visits per month" section', () => { it('should contain a "Total visits per month" section', () => {
cy.visit(ITEMSTATISTICSPAGE); cy.visit(ITEMSTATISTICSPAGE);
// Check just for existence because this table is empty in CI environment as it's historical data // Check just for existence because this table is empty in CI environment as it's historical data
cy.get('.'.concat(TEST_ENTITY_PUBLICATION).concat('_TotalVisitsPerMonth')).should('exist'); cy.get('.'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION')).concat('_TotalVisitsPerMonth')).should('exist');
}); });
it('should pass accessibility tests', () => { it('should pass accessibility tests', () => {

View File

@@ -1,4 +1,3 @@
import { TEST_ADMIN_PASSWORD, TEST_ADMIN_USER, TEST_ENTITY_PUBLICATION } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
const page = { const page = {
@@ -37,7 +36,7 @@ const page = {
describe('Login Modal', () => { describe('Login Modal', () => {
it('should login when clicking button & stay on same page', () => { it('should login when clicking button & stay on same page', () => {
const ENTITYPAGE = '/entities/publication/'.concat(TEST_ENTITY_PUBLICATION); const ENTITYPAGE = '/entities/publication/'.concat(Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION'));
cy.visit(ENTITYPAGE); cy.visit(ENTITYPAGE);
// Login menu should exist // Login menu should exist
@@ -47,7 +46,7 @@ describe('Login Modal', () => {
page.openLoginMenu(); page.openLoginMenu();
cy.get('.form-login').should('be.visible'); cy.get('.form-login').should('be.visible');
page.submitLoginAndPasswordByPressingButton(TEST_ADMIN_USER, TEST_ADMIN_PASSWORD); page.submitLoginAndPasswordByPressingButton(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
cy.get('ds-log-in').should('not.exist'); cy.get('ds-log-in').should('not.exist');
// Verify we are still on the same page // Verify we are still on the same page
@@ -67,7 +66,7 @@ describe('Login Modal', () => {
cy.get('.form-login').should('be.visible'); cy.get('.form-login').should('be.visible');
// Login, and the <ds-log-in> tag should no longer exist // Login, and the <ds-log-in> tag should no longer exist
page.submitLoginAndPasswordByPressingEnter(TEST_ADMIN_USER, TEST_ADMIN_PASSWORD); page.submitLoginAndPasswordByPressingEnter(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
cy.get('.form-login').should('not.exist'); cy.get('.form-login').should('not.exist');
// Verify we are still on homepage // Verify we are still on homepage
@@ -81,7 +80,7 @@ describe('Login Modal', () => {
it('should support logout', () => { it('should support logout', () => {
// First authenticate & access homepage // First authenticate & access homepage
cy.login(TEST_ADMIN_USER, TEST_ADMIN_PASSWORD); cy.login(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
cy.visit('/'); cy.visit('/');
// Verify ds-log-in tag doesn't exist, but ds-log-out tag does exist // Verify ds-log-in tag doesn't exist, but ds-log-out tag does exist
@@ -109,6 +108,9 @@ describe('Login Modal', () => {
cy.get('ds-themed-navbar [data-test="register"]').click(); cy.get('ds-themed-navbar [data-test="register"]').click();
cy.location('pathname').should('eq', '/register'); cy.location('pathname').should('eq', '/register');
cy.get('ds-register-email').should('exist'); cy.get('ds-register-email').should('exist');
// Test accessibility of this page
testA11y('ds-register-email');
}); });
it('should allow forgot password', () => { it('should allow forgot password', () => {
@@ -123,16 +125,26 @@ describe('Login Modal', () => {
cy.get('ds-themed-navbar [data-test="forgot"]').click(); cy.get('ds-themed-navbar [data-test="forgot"]').click();
cy.location('pathname').should('eq', '/forgot'); cy.location('pathname').should('eq', '/forgot');
cy.get('ds-forgot-email').should('exist'); cy.get('ds-forgot-email').should('exist');
// Test accessibility of this page
testA11y('ds-forgot-email');
}); });
it('should pass accessibility tests', () => { it('should pass accessibility tests in menus', () => {
cy.visit('/'); cy.visit('/');
// Open login menu & verify accessibility
page.openLoginMenu(); page.openLoginMenu();
cy.get('ds-log-in').should('exist'); cy.get('ds-log-in').should('exist');
// Analyze <ds-log-in> for accessibility issues
testA11y('ds-log-in'); testA11y('ds-log-in');
// Now login
page.submitLoginAndPasswordByPressingButton(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
cy.get('ds-log-in').should('not.exist');
// Open user menu, verify user menu accesibility
page.openUserMenu();
cy.get('ds-user-menu').should('be.visible');
testA11y('ds-user-menu');
}); });
}); });

View File

@@ -1,5 +1,3 @@
import { Options } from 'cypress-axe';
import { TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD, TEST_SUBMIT_COLLECTION_NAME } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('My DSpace page', () => { describe('My DSpace page', () => {
@@ -7,7 +5,7 @@ describe('My DSpace page', () => {
cy.visit('/mydspace'); cy.visit('/mydspace');
// This page is restricted, so we will be shown the login form. Fill it out & submit. // This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD); cy.loginViaForm(Cypress.env('DSPACE_TEST_SUBMIT_USER'), Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD'));
cy.get('ds-my-dspace-page').should('be.visible'); cy.get('ds-my-dspace-page').should('be.visible');
@@ -26,7 +24,7 @@ describe('My DSpace page', () => {
cy.visit('/mydspace'); cy.visit('/mydspace');
// This page is restricted, so we will be shown the login form. Fill it out & submit. // This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD); cy.loginViaForm(Cypress.env('DSPACE_TEST_SUBMIT_USER'), Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD'));
cy.get('ds-my-dspace-page').should('be.visible'); cy.get('ds-my-dspace-page').should('be.visible');
@@ -35,16 +33,8 @@ describe('My DSpace page', () => {
cy.get('ds-object-detail').should('be.visible'); cy.get('ds-object-detail').should('be.visible');
// Analyze <ds-search-page> for accessibility issues // Analyze <ds-my-dspace-page> for accessibility issues
testA11y('ds-my-dspace-page', testA11y('ds-my-dspace-page');
{
rules: {
// Search filters fail these two "moderate" impact rules
'heading-order': { enabled: false },
'landmark-unique': { enabled: false }
}
} as Options
);
}); });
// NOTE: Deleting existing submissions is exercised by submission.spec.ts // NOTE: Deleting existing submissions is exercised by submission.spec.ts
@@ -52,7 +42,7 @@ describe('My DSpace page', () => {
cy.visit('/mydspace'); cy.visit('/mydspace');
// This page is restricted, so we will be shown the login form. Fill it out & submit. // This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD); cy.loginViaForm(Cypress.env('DSPACE_TEST_SUBMIT_USER'), Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD'));
// Open the New Submission dropdown // Open the New Submission dropdown
cy.get('button[data-test="submission-dropdown"]').click(); cy.get('button[data-test="submission-dropdown"]').click();
@@ -63,10 +53,10 @@ describe('My DSpace page', () => {
cy.get('ds-create-item-parent-selector').should('be.visible'); cy.get('ds-create-item-parent-selector').should('be.visible');
// Type in a known Collection name in the search box // Type in a known Collection name in the search box
cy.get('ds-authorized-collection-selector input[type="search"]').type(TEST_SUBMIT_COLLECTION_NAME); cy.get('ds-authorized-collection-selector input[type="search"]').type(Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_NAME'));
// Click on the button matching that known Collection name // Click on the button matching that known Collection name
cy.get('ds-authorized-collection-selector button[title="'.concat(TEST_SUBMIT_COLLECTION_NAME).concat('"]')).click(); cy.get('ds-authorized-collection-selector button[title="'.concat(Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_NAME')).concat('"]')).click();
// New URL should include /workspaceitems, as we've started a new submission // New URL should include /workspaceitems, as we've started a new submission
cy.url().should('include', '/workspaceitems'); cy.url().should('include', '/workspaceitems');
@@ -75,7 +65,7 @@ describe('My DSpace page', () => {
cy.get('ds-submission-edit').should('be.visible'); cy.get('ds-submission-edit').should('be.visible');
// A Collection menu button should exist & its value should be the selected collection // A Collection menu button should exist & its value should be the selected collection
cy.get('#collectionControlsMenuButton span').should('have.text', TEST_SUBMIT_COLLECTION_NAME); cy.get('#collectionControlsMenuButton span').should('have.text', Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_NAME'));
// Now that we've created a submission, we'll test that we can go back and Edit it. // Now that we've created a submission, we'll test that we can go back and Edit it.
// Get our Submission URL, to parse out the ID of this new submission // Get our Submission URL, to parse out the ID of this new submission
@@ -124,7 +114,7 @@ describe('My DSpace page', () => {
cy.visit('/mydspace'); cy.visit('/mydspace');
// This page is restricted, so we will be shown the login form. Fill it out & submit. // This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD); cy.loginViaForm(Cypress.env('DSPACE_TEST_SUBMIT_USER'), Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD'));
// Open the New Import dropdown // Open the New Import dropdown
cy.get('button[data-test="import-dropdown"]').click(); cy.get('button[data-test="import-dropdown"]').click();
@@ -136,6 +126,9 @@ describe('My DSpace page', () => {
// The external import searchbox should be visible // The external import searchbox should be visible
cy.get('ds-submission-import-external-searchbar').should('be.visible'); cy.get('ds-submission-import-external-searchbar').should('be.visible');
// Test for accessibility issues
testA11y('ds-submission-import-external');
}); });
}); });

View File

@@ -1,5 +1,3 @@
import { TEST_SEARCH_TERM } from 'cypress/support/e2e';
const page = { const page = {
fillOutQueryInNavBar(query) { fillOutQueryInNavBar(query) {
// Click the magnifying glass // Click the magnifying glass
@@ -17,7 +15,7 @@ const page = {
describe('Search from Navigation Bar', () => { describe('Search from Navigation Bar', () => {
// NOTE: these tests currently assume this query will return results! // NOTE: these tests currently assume this query will return results!
const query = TEST_SEARCH_TERM; const query = Cypress.env('DSPACE_TEST_SEARCH_TERM');
it('should go to search page with correct query if submitted (from home)', () => { it('should go to search page with correct query if submitted (from home)', () => {
cy.visit('/'); cy.visit('/');

View File

@@ -1,8 +1,10 @@
import { Options } from 'cypress-axe'; import { Options } from 'cypress-axe';
import { TEST_SEARCH_TERM } from 'cypress/support/e2e';
import { testA11y } from 'cypress/support/utils'; import { testA11y } from 'cypress/support/utils';
describe('Search Page', () => { describe('Search Page', () => {
// NOTE: these tests currently assume this query will return results!
const query = Cypress.env('DSPACE_TEST_SEARCH_TERM');
it('should redirect to the correct url when query was set and submit button was triggered', () => { it('should redirect to the correct url when query was set and submit button was triggered', () => {
const queryString = 'Another interesting query string'; const queryString = 'Another interesting query string';
cy.visit('/search'); cy.visit('/search');
@@ -13,8 +15,8 @@ describe('Search Page', () => {
}); });
it('should load results and pass accessibility tests', () => { it('should load results and pass accessibility tests', () => {
cy.visit('/search?query='.concat(TEST_SEARCH_TERM)); cy.visit('/search?query='.concat(query));
cy.get('[data-test="search-box"]').should('have.value', TEST_SEARCH_TERM); cy.get('[data-test="search-box"]').should('have.value', query);
// <ds-search-page> tag must be loaded // <ds-search-page> tag must be loaded
cy.get('ds-search-page').should('be.visible'); cy.get('ds-search-page').should('be.visible');
@@ -31,7 +33,7 @@ describe('Search Page', () => {
}); });
it('should have a working grid view that passes accessibility tests', () => { it('should have a working grid view that passes accessibility tests', () => {
cy.visit('/search?query='.concat(TEST_SEARCH_TERM)); cy.visit('/search?query='.concat(query));
// Click button in sidebar to display grid view // Click button in sidebar to display grid view
cy.get('ds-search-sidebar [data-test="grid-view"]').click(); cy.get('ds-search-sidebar [data-test="grid-view"]').click();
@@ -46,9 +48,8 @@ describe('Search Page', () => {
testA11y('ds-search-page', testA11y('ds-search-page',
{ {
rules: { rules: {
// Search filters fail these two "moderate" impact rules // Card titles fail this test currently
'heading-order': { enabled: false }, 'heading-order': { enabled: false }
'landmark-unique': { enabled: false }
} }
} as Options } as Options
); );

View File

@@ -1,14 +1,16 @@
import { TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD, TEST_SUBMIT_COLLECTION_NAME, TEST_SUBMIT_COLLECTION_UUID } from 'cypress/support/e2e'; import { testA11y } from 'cypress/support/utils';
//import { TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD, TEST_SUBMIT_COLLECTION_NAME, TEST_SUBMIT_COLLECTION_UUID, TEST_ADMIN_USER, TEST_ADMIN_PASSWORD } from 'cypress/support/e2e';
import { Options } from 'cypress-axe';
describe('New Submission page', () => { describe('New Submission page', () => {
// NOTE: We already test that new submissions can be started from MyDSpace in my-dspace.spec.ts
// NOTE: We already test that new Item submissions can be started from MyDSpace in my-dspace.spec.ts
it('should create a new submission when using /submit path & pass accessibility', () => { it('should create a new submission when using /submit path & pass accessibility', () => {
// Test that calling /submit with collection & entityType will create a new submission // Test that calling /submit with collection & entityType will create a new submission
cy.visit('/submit?collection='.concat(TEST_SUBMIT_COLLECTION_UUID).concat('&entityType=none')); cy.visit('/submit?collection='.concat(Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_UUID')).concat('&entityType=none'));
// This page is restricted, so we will be shown the login form. Fill it out & submit. // This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD); cy.loginViaForm(Cypress.env('DSPACE_TEST_SUBMIT_USER'), Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD'));
// Should redirect to /workspaceitems, as we've started a new submission // Should redirect to /workspaceitems, as we've started a new submission
cy.url().should('include', '/workspaceitems'); cy.url().should('include', '/workspaceitems');
@@ -17,7 +19,7 @@ describe('New Submission page', () => {
cy.get('ds-submission-edit').should('be.visible'); cy.get('ds-submission-edit').should('be.visible');
// A Collection menu button should exist & it's value should be the selected collection // A Collection menu button should exist & it's value should be the selected collection
cy.get('#collectionControlsMenuButton span').should('have.text', TEST_SUBMIT_COLLECTION_NAME); cy.get('#collectionControlsMenuButton span').should('have.text', Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_NAME'));
// 4 sections should be visible by default // 4 sections should be visible by default
cy.get('div#section_traditionalpageone').should('be.visible'); cy.get('div#section_traditionalpageone').should('be.visible');
@@ -25,6 +27,25 @@ describe('New Submission page', () => {
cy.get('div#section_upload').should('be.visible'); cy.get('div#section_upload').should('be.visible');
cy.get('div#section_license').should('be.visible'); cy.get('div#section_license').should('be.visible');
// Test entire page for accessibility
testA11y('ds-submission-edit',
{
rules: {
// Author & Subject fields have invalid "aria-multiline" attrs.
// See https://github.com/DSpace/dspace-angular/issues/1272
'aria-allowed-attr': { enabled: false },
// All panels are accordians & fail "aria-required-children" and "nested-interactive".
// Seem to require updating ng-bootstrap and https://github.com/DSpace/dspace-angular/issues/2216
'aria-required-children': { enabled: false },
'nested-interactive': { enabled: false },
// All select boxes fail to have a name / aria-label.
// This is a bug in ng-dynamic-forms and may require https://github.com/DSpace/dspace-angular/issues/2216
'select-name': { enabled: false },
}
} as Options
);
// Discard button should work // Discard button should work
// Clicking it will display a confirmation, which we will confirm with another click // Clicking it will display a confirmation, which we will confirm with another click
cy.get('button#discard').click(); cy.get('button#discard').click();
@@ -33,10 +54,10 @@ describe('New Submission page', () => {
it('should block submission & show errors if required fields are missing', () => { it('should block submission & show errors if required fields are missing', () => {
// Create a new submission // Create a new submission
cy.visit('/submit?collection='.concat(TEST_SUBMIT_COLLECTION_UUID).concat('&entityType=none')); cy.visit('/submit?collection='.concat(Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_UUID')).concat('&entityType=none'));
// This page is restricted, so we will be shown the login form. Fill it out & submit. // This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD); cy.loginViaForm(Cypress.env('DSPACE_TEST_SUBMIT_USER'), Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD'));
// Attempt an immediate deposit without filling out any fields // Attempt an immediate deposit without filling out any fields
cy.get('button#deposit').click(); cy.get('button#deposit').click();
@@ -93,10 +114,10 @@ describe('New Submission page', () => {
it('should allow for deposit if all required fields completed & file uploaded', () => { it('should allow for deposit if all required fields completed & file uploaded', () => {
// Create a new submission // Create a new submission
cy.visit('/submit?collection='.concat(TEST_SUBMIT_COLLECTION_UUID).concat('&entityType=none')); cy.visit('/submit?collection='.concat(Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_UUID')).concat('&entityType=none'));
// This page is restricted, so we will be shown the login form. Fill it out & submit. // This page is restricted, so we will be shown the login form. Fill it out & submit.
cy.loginViaForm(TEST_SUBMIT_USER, TEST_SUBMIT_USER_PASSWORD); cy.loginViaForm(Cypress.env('DSPACE_TEST_SUBMIT_USER'), Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD'));
// Fill out all required fields (Title, Date) // Fill out all required fields (Title, Date)
cy.get('input#dc_title').type('DSpace logo uploaded via e2e tests'); cy.get('input#dc_title').type('DSpace logo uploaded via e2e tests');
@@ -131,4 +152,76 @@ describe('New Submission page', () => {
cy.get('ds-notification div.alert-success').should('be.visible'); cy.get('ds-notification div.alert-success').should('be.visible');
}); });
it('is possible to submit a new "Person" and that form passes accessibility', () => {
// To submit a different entity type, we'll start from MyDSpace
cy.visit('/mydspace');
// This page is restricted, so we will be shown the login form. Fill it out & submit.
// NOTE: At this time, we MUST login as admin to submit Person objects
cy.loginViaForm(Cypress.env('DSPACE_TEST_ADMIN_USER'), Cypress.env('DSPACE_TEST_ADMIN_PASSWORD'));
// Open the New Submission dropdown
cy.get('button[data-test="submission-dropdown"]').click();
// Click on the "Person" type in that dropdown
cy.get('#entityControlsDropdownMenu button[title="Person"]').click();
// This should display the <ds-create-item-parent-selector> (popup window)
cy.get('ds-create-item-parent-selector').should('be.visible');
// Type in a known Collection name in the search box
cy.get('ds-authorized-collection-selector input[type="search"]').type(Cypress.env('DSPACE_TEST_SUBMIT_PERSON_COLLECTION_NAME'));
// Click on the button matching that known Collection name
cy.get('ds-authorized-collection-selector button[title="'.concat(Cypress.env('DSPACE_TEST_SUBMIT_PERSON_COLLECTION_NAME')).concat('"]')).click();
// New URL should include /workspaceitems, as we've started a new submission
cy.url().should('include', '/workspaceitems');
// The Submission edit form tag should be visible
cy.get('ds-submission-edit').should('be.visible');
// A Collection menu button should exist & its value should be the selected collection
cy.get('#collectionControlsMenuButton span').should('have.text', Cypress.env('DSPACE_TEST_SUBMIT_PERSON_COLLECTION_NAME'));
// 3 sections should be visible by default
cy.get('div#section_personStep').should('be.visible');
cy.get('div#section_upload').should('be.visible');
cy.get('div#section_license').should('be.visible');
// Test entire page for accessibility
testA11y('ds-submission-edit',
{
rules: {
// All panels are accordians & fail "aria-required-children" and "nested-interactive".
// Seem to require updating ng-bootstrap and https://github.com/DSpace/dspace-angular/issues/2216
'aria-required-children': { enabled: false },
'nested-interactive': { enabled: false },
}
} as Options
);
// Click the lookup button next to "Publication" field
cy.get('button[data-test="lookup-button"]').click();
// A popup modal window should be visible
cy.get('ds-dynamic-lookup-relation-modal').should('be.visible');
// Popup modal should also pass accessibility tests
//testA11y('ds-dynamic-lookup-relation-modal');
testA11y({
include: ['ds-dynamic-lookup-relation-modal'],
exclude: [
['ul.nav-tabs'] // Tabs at top of model have several issues which seem to be caused by ng-bootstrap
],
});
// Close popup window
cy.get('ds-dynamic-lookup-relation-modal button.close').click();
// Back on the form, click the discard button to remove new submission
// Clicking it will display a confirmation, which we will confirm with another click
cy.get('button#discard').click();
cy.get('button#discard_submit').click();
});
}); });

View File

@@ -1,5 +1,11 @@
const fs = require('fs'); const fs = require('fs');
// These two global variables are used to store information about the REST API used
// by these e2e tests. They are filled out prior to running any tests in the before()
// method of e2e.ts. They can then be accessed by any tests via the getters below.
let REST_BASE_URL: string;
let REST_DOMAIN: string;
// Plugins enable you to tap into, modify, or extend the internal behavior of Cypress // Plugins enable you to tap into, modify, or extend the internal behavior of Cypress
// For more info, visit https://on.cypress.io/plugins-api // For more info, visit https://on.cypress.io/plugins-api
module.exports = (on, config) => { module.exports = (on, config) => {
@@ -30,6 +36,24 @@ module.exports = (on, config) => {
} }
return null; return null;
},
// Save value of REST Base URL, looked up before all tests.
// This allows other tests to use it easily via getRestBaseURL() below.
saveRestBaseURL(url: string) {
return (REST_BASE_URL = url);
},
// Retrieve currently saved value of REST Base URL
getRestBaseURL() {
return REST_BASE_URL ;
},
// Save value of REST Domain, looked up before all tests.
// This allows other tests to use it easily via getRestBaseDomain() below.
saveRestBaseDomain(domain: string) {
return (REST_DOMAIN = domain);
},
// Retrieve currently saved value of REST Domain
getRestBaseDomain() {
return REST_DOMAIN ;
} }
}); });
}; };

View File

@@ -5,11 +5,7 @@
import { AuthTokenInfo, TOKENITEM } from 'src/app/core/auth/models/auth-token-info.model'; import { AuthTokenInfo, TOKENITEM } from 'src/app/core/auth/models/auth-token-info.model';
import { DSPACE_XSRF_COOKIE, XSRF_REQUEST_HEADER } from 'src/app/core/xsrf/xsrf.constants'; import { DSPACE_XSRF_COOKIE, XSRF_REQUEST_HEADER } from 'src/app/core/xsrf/xsrf.constants';
import { v4 as uuidv4 } from 'uuid';
// NOTE: FALLBACK_TEST_REST_BASE_URL is only used if Cypress cannot read the REST API BaseURL
// from the Angular UI's config.json. See 'login()'.
export const FALLBACK_TEST_REST_BASE_URL = 'http://localhost:8080/server';
export const FALLBACK_TEST_REST_DOMAIN = 'localhost';
// Declare Cypress namespace to help with Intellisense & code completion in IDEs // Declare Cypress namespace to help with Intellisense & code completion in IDEs
// ALL custom commands MUST be listed here for code completion to work // ALL custom commands MUST be listed here for code completion to work
@@ -41,6 +37,13 @@ declare global {
* @param dsoType type of DSpace Object (e.g. "item", "collection", "community") * @param dsoType type of DSpace Object (e.g. "item", "collection", "community")
*/ */
generateViewEvent(uuid: string, dsoType: string): typeof generateViewEvent; generateViewEvent(uuid: string, dsoType: string): typeof generateViewEvent;
/**
* Create a new CSRF token and add to required Cookie. CSRF Token is returned
* in chainable in order to allow it to be sent also in required CSRF header.
* @returns Chainable reference to allow CSRF token to also be sent in header.
*/
createCSRFCookie(): Chainable<any>;
} }
} }
} }
@@ -54,35 +57,10 @@ declare global {
* @param password password to login as * @param password password to login as
*/ */
function login(email: string, password: string): void { function login(email: string, password: string): void {
// Cypress doesn't have access to the running application in Node.js. // Create a fake CSRF cookie/token to use in POST
// So, it's not possible to inject or load the AppConfig or environment of the Angular UI. cy.createCSRFCookie().then((csrfToken: string) => {
// Instead, we'll read our running application's config.json, which contains the configs & // get our REST API's base URL, also needed for POST
// is regenerated at runtime each time the Angular UI application starts up. cy.task('getRestBaseURL').then((baseRestUrl: string) => {
cy.task('readUIConfig').then((str: string) => {
// Parse config into a JSON object
const config = JSON.parse(str);
// Find the URL of our REST API. Have a fallback ready, just in case 'rest.baseUrl' cannot be found.
let baseRestUrl = FALLBACK_TEST_REST_BASE_URL;
if (!config.rest.baseUrl) {
console.warn("Could not load 'rest.baseUrl' from config.json. Falling back to " + FALLBACK_TEST_REST_BASE_URL);
} else {
//console.log("Found 'rest.baseUrl' in config.json. Using this REST API for login: ".concat(config.rest.baseUrl));
baseRestUrl = config.rest.baseUrl;
}
// Now find domain of our REST API, again with a fallback.
let baseDomain = FALLBACK_TEST_REST_DOMAIN;
if (!config.rest.host) {
console.warn("Could not load 'rest.host' from config.json. Falling back to " + FALLBACK_TEST_REST_DOMAIN);
} else {
baseDomain = config.rest.host;
}
// Create a fake CSRF Token. Set it in the required server-side cookie
const csrfToken = 'fakeLoginCSRFToken';
cy.setCookie(DSPACE_XSRF_COOKIE, csrfToken, { 'domain': baseDomain });
// Now, send login POST request including that CSRF token // Now, send login POST request including that CSRF token
cy.request({ cy.request({
method: 'POST', method: 'POST',
@@ -104,9 +82,7 @@ function login(email: string, password: string): void {
// This ensures the UI will recognize we are logged in on next "visit()" // This ensures the UI will recognize we are logged in on next "visit()"
cy.setCookie(TOKENITEM, JSON.stringify(authinfo)); cy.setCookie(TOKENITEM, JSON.stringify(authinfo));
}); });
});
// Remove cookie with fake CSRF token, as it's no longer needed
cy.clearCookie(DSPACE_XSRF_COOKIE);
}); });
} }
// Add as a Cypress command (i.e. assign to 'cy.login') // Add as a Cypress command (i.e. assign to 'cy.login')
@@ -141,34 +117,10 @@ Cypress.Commands.add('loginViaForm', loginViaForm);
* @param dsoType type of DSpace Object (e.g. "item", "collection", "community") * @param dsoType type of DSpace Object (e.g. "item", "collection", "community")
*/ */
function generateViewEvent(uuid: string, dsoType: string): void { function generateViewEvent(uuid: string, dsoType: string): void {
// Cypress doesn't have access to the running application in Node.js. // Create a fake CSRF cookie/token to use in POST
// So, it's not possible to inject or load the AppConfig or environment of the Angular UI. cy.createCSRFCookie().then((csrfToken: string) => {
// Instead, we'll read our running application's config.json, which contains the configs & // get our REST API's base URL, also needed for POST
// is regenerated at runtime each time the Angular UI application starts up. cy.task('getRestBaseURL').then((baseRestUrl: string) => {
cy.task('readUIConfig').then((str: string) => {
// Parse config into a JSON object
const config = JSON.parse(str);
// Find the URL of our REST API. Have a fallback ready, just in case 'rest.baseUrl' cannot be found.
let baseRestUrl = FALLBACK_TEST_REST_BASE_URL;
if (!config.rest.baseUrl) {
console.warn("Could not load 'rest.baseUrl' from config.json. Falling back to " + FALLBACK_TEST_REST_BASE_URL);
} else {
baseRestUrl = config.rest.baseUrl;
}
// Now find domain of our REST API, again with a fallback.
let baseDomain = FALLBACK_TEST_REST_DOMAIN;
if (!config.rest.host) {
console.warn("Could not load 'rest.host' from config.json. Falling back to " + FALLBACK_TEST_REST_DOMAIN);
} else {
baseDomain = config.rest.host;
}
// Create a fake CSRF Token. Set it in the required server-side cookie
const csrfToken = 'fakeGenerateViewEventCSRFToken';
cy.setCookie(DSPACE_XSRF_COOKIE, csrfToken, { 'domain': baseDomain });
// Now, send 'statistics/viewevents' POST request including that fake CSRF token in required header // Now, send 'statistics/viewevents' POST request including that fake CSRF token in required header
cy.request({ cy.request({
method: 'POST', method: 'POST',
@@ -186,11 +138,32 @@ function generateViewEvent(uuid: string, dsoType: string): void {
// We expect a 201 (which means statistics event was created) // We expect a 201 (which means statistics event was created)
expect(resp.status).to.eq(201); expect(resp.status).to.eq(201);
}); });
});
// Remove cookie with fake CSRF token, as it's no longer needed
cy.clearCookie(DSPACE_XSRF_COOKIE);
}); });
} }
// Add as a Cypress command (i.e. assign to 'cy.generateViewEvent') // Add as a Cypress command (i.e. assign to 'cy.generateViewEvent')
Cypress.Commands.add('generateViewEvent', generateViewEvent); Cypress.Commands.add('generateViewEvent', generateViewEvent);
/**
* Can be used by tests to generate a random XSRF/CSRF token and save it to
* the required XSRF/CSRF cookie for usage when sending POST requests or similar.
* The generated CSRF token is returned in a Chainable to allow it to be also sent
* in the CSRF HTTP Header.
* @returns a Cypress Chainable which can be used to get the generated CSRF Token
*/
function createCSRFCookie(): Cypress.Chainable {
// Generate a new token which is a random UUID
const csrfToken: string = uuidv4();
// Save it to our required cookie
cy.task('getRestBaseDomain').then((baseDomain: string) => {
// Create a fake CSRF Token. Set it in the required server-side cookie
cy.setCookie(DSPACE_XSRF_COOKIE, csrfToken, { 'domain': baseDomain });
});
// return the generated token wrapped in a chainable
return cy.wrap(csrfToken);
}
// Add as a Cypress command (i.e. assign to 'cy.createCSRFCookie')
Cypress.Commands.add('createCSRFCookie', createCSRFCookie);

View File

@@ -19,45 +19,54 @@ import './commands';
// Import Cypress Axe tools for all tests // Import Cypress Axe tools for all tests
// https://github.com/component-driven/cypress-axe // https://github.com/component-driven/cypress-axe
import 'cypress-axe'; import 'cypress-axe';
import { DSPACE_XSRF_COOKIE } from 'src/app/core/xsrf/xsrf.constants';
// Runs once before all tests
before(() => {
// Cypress doesn't have access to the running application in Node.js.
// So, it's not possible to inject or load the AppConfig or environment of the Angular UI.
// Instead, we'll read our running application's config.json, which contains the configs &
// is regenerated at runtime each time the Angular UI application starts up.
cy.task('readUIConfig').then((str: string) => {
// Parse config into a JSON object
const config = JSON.parse(str);
// Find URL of our REST API & save to global variable via task
let baseRestUrl = FALLBACK_TEST_REST_BASE_URL;
if (!config.rest.baseUrl) {
console.warn("Could not load 'rest.baseUrl' from config.json. Falling back to " + FALLBACK_TEST_REST_BASE_URL);
} else {
baseRestUrl = config.rest.baseUrl;
}
cy.task('saveRestBaseURL', baseRestUrl);
// Find domain of our REST API & save to global variable via task.
let baseDomain = FALLBACK_TEST_REST_DOMAIN;
if (!config.rest.host) {
console.warn("Could not load 'rest.host' from config.json. Falling back to " + FALLBACK_TEST_REST_DOMAIN);
} else {
baseDomain = config.rest.host;
}
cy.task('saveRestBaseDomain', baseDomain);
});
});
// Runs once before the first test in each "block" // Runs once before the first test in each "block"
beforeEach(() => { beforeEach(() => {
// Pre-agree to all Klaro cookies by setting the klaro-anonymous cookie // Pre-agree to all Klaro cookies by setting the klaro-anonymous cookie
// This just ensures it doesn't get in the way of matching other objects in the page. // This just ensures it doesn't get in the way of matching other objects in the page.
cy.setCookie('klaro-anonymous', '{%22authentication%22:true%2C%22preferences%22:true%2C%22acknowledgement%22:true%2C%22google-analytics%22:true%2C%22google-recaptcha%22:true}'); cy.setCookie('klaro-anonymous', '{%22authentication%22:true%2C%22preferences%22:true%2C%22acknowledgement%22:true%2C%22google-analytics%22:true%2C%22google-recaptcha%22:true}');
// Remove any CSRF cookies saved from prior tests
cy.clearCookie(DSPACE_XSRF_COOKIE);
}); });
// For better stability between tests, we visit "about:blank" (i.e. blank page) after each test. // NOTE: FALLBACK_TEST_REST_BASE_URL is only used if Cypress cannot read the REST API BaseURL
// This ensures any remaining/outstanding XHR requests are killed, so they don't affect the next test. // from the Angular UI's config.json. See 'before()' above.
// Borrowed from: https://glebbahmutov.com/blog/visit-blank-page-between-tests/ const FALLBACK_TEST_REST_BASE_URL = 'http://localhost:8080/server';
/*afterEach(() => { const FALLBACK_TEST_REST_DOMAIN = 'localhost';
cy.window().then((win) => {
win.location.href = 'about:blank';
});
});*/
// Global constants used in tests
// May be overridden in our cypress.json config file using specified environment variables.
// Default values listed here are all valid for the Demo Entities Data set available at
// https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data
// (This is the data set used in our CI environment)
// Admin account used for administrative tests
export const TEST_ADMIN_USER = Cypress.env('DSPACE_TEST_ADMIN_USER') || 'dspacedemo+admin@gmail.com';
export const TEST_ADMIN_PASSWORD = Cypress.env('DSPACE_TEST_ADMIN_PASSWORD') || 'dspace';
// Community/collection/publication used for view/edit tests
export const TEST_COLLECTION = Cypress.env('DSPACE_TEST_COLLECTION') || '282164f5-d325-4740-8dd1-fa4d6d3e7200';
export const TEST_COMMUNITY = Cypress.env('DSPACE_TEST_COMMUNITY') || '0958c910-2037-42a9-81c7-dca80e3892b4';
export const TEST_ENTITY_PUBLICATION = Cypress.env('DSPACE_TEST_ENTITY_PUBLICATION') || 'e98b0f27-5c19-49a0-960d-eb6ad5287067';
// Search term (should return results) used in search tests
export const TEST_SEARCH_TERM = Cypress.env('DSPACE_TEST_SEARCH_TERM') || 'test';
// Collection used for submission tests
export const TEST_SUBMIT_COLLECTION_NAME = Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_NAME') || 'Sample Collection';
export const TEST_SUBMIT_COLLECTION_UUID = Cypress.env('DSPACE_TEST_SUBMIT_COLLECTION_UUID') || '9d8334e9-25d3-4a67-9cea-3dffdef80144';
export const TEST_SUBMIT_USER = Cypress.env('DSPACE_TEST_SUBMIT_USER') || 'dspacedemo+submit@gmail.com';
export const TEST_SUBMIT_USER_PASSWORD = Cypress.env('DSPACE_TEST_SUBMIT_USER_PASSWORD') || 'dspace';
// USEFUL REGEX for testing // USEFUL REGEX for testing

View File

@@ -14,13 +14,8 @@
# Therefore, it should be kept in sync with that file # Therefore, it should be kept in sync with that file
version: "3.7" version: "3.7"
networks:
dspacenet:
services: services:
dspace-cli: dspace-cli:
networks:
dspacenet: {}
environment: environment:
# This assetstore zip is available from https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data # This assetstore zip is available from https://github.com/DSpace-Labs/AIP-Files/releases/tag/demo-entities-data
- LOADASSETS=https://github.com/DSpace-Labs/AIP-Files/releases/download/demo-entities-data/assetstore.tar.gz - LOADASSETS=https://github.com/DSpace-Labs/AIP-Files/releases/download/demo-entities-data/assetstore.tar.gz

View File

@@ -13,7 +13,13 @@
# #
# Therefore, it should be kept in sync with that file # Therefore, it should be kept in sync with that file
version: "3.7" version: "3.7"
networks:
# Default to using network named 'dspacenet' from docker-compose-rest.yml.
# Its full name will be prepended with the project name (e.g. "-p d7" means it will be named "d7_dspacenet")
# If COMPOSITE_PROJECT_NAME is missing, default value will be "docker" (name of folder this file is in)
default:
name: ${COMPOSE_PROJECT_NAME:-docker}_dspacenet
external: true
services: services:
dspace-cli: dspace-cli:
image: "${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-latest}" image: "${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-latest}"
@@ -30,16 +36,12 @@ services:
# solr.server: Ensure we are using the 'dspacesolr' image for Solr # solr.server: Ensure we are using the 'dspacesolr' image for Solr
solr__P__server: http://dspacesolr:8983/solr solr__P__server: http://dspacesolr:8983/solr
volumes: volumes:
- "assetstore:/dspace/assetstore" # Keep DSpace assetstore directory between reboots
- assetstore:/dspace/assetstore
entrypoint: /dspace/bin/dspace entrypoint: /dspace/bin/dspace
command: help command: help
networks:
- dspacenet
tty: true tty: true
stdin_open: true stdin_open: true
volumes: volumes:
assetstore: assetstore:
networks:
dspacenet:

View File

@@ -33,11 +33,11 @@ services:
# Tell Statistics to commit all views immediately instead of waiting on Solr's autocommit. # Tell Statistics to commit all views immediately instead of waiting on Solr's autocommit.
# 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'
image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-latest-test}"
depends_on: depends_on:
- dspacedb - dspacedb
image: dspace/dspace:latest-test
networks: networks:
dspacenet: - dspacenet
ports: ports:
- published: 8080 - published: 8080
target: 8080 target: 8080
@@ -45,8 +45,6 @@ services:
tty: true tty: true
volumes: volumes:
- assetstore:/dspace/assetstore - assetstore:/dspace/assetstore
# Mount DSpace's solr configs to a volume, so that we can share to 'dspacesolr' container (see below)
- solr_configs:/dspace/solr
# Ensure that the database is ready BEFORE starting tomcat # Ensure that the database is ready BEFORE starting tomcat
# 1. While a TCP connection to dspacedb port 5432 is not available, continue to sleep # 1. While a TCP connection to dspacedb port 5432 is not available, continue to sleep
# 2. Then, run database migration to init database tables (including any out-of-order ignored migrations, if any) # 2. Then, run database migration to init database tables (including any out-of-order ignored migrations, if any)
@@ -70,21 +68,18 @@ services:
PGDATA: /pgdata PGDATA: /pgdata
image: dspace/dspace-postgres-pgcrypto:loadsql image: dspace/dspace-postgres-pgcrypto:loadsql
networks: networks:
dspacenet: - dspacenet
stdin_open: true stdin_open: true
tty: true tty: true
volumes: volumes:
# Keep Postgres data directory between reboots
- pgdata:/pgdata - pgdata:/pgdata
# DSpace Solr container # DSpace Solr container
dspacesolr: dspacesolr:
container_name: dspacesolr container_name: dspacesolr
# Uses official Solr image at https://hub.docker.com/_/solr/ image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-latest}"
image: solr:8.11-slim
# Needs main 'dspace' container to start first to guarantee access to solr_configs
depends_on:
- dspace
networks: networks:
dspacenet: - dspacenet
ports: ports:
- published: 8983 - published: 8983
target: 8983 target: 8983
@@ -92,9 +87,6 @@ services:
tty: true tty: true
working_dir: /var/solr/data working_dir: /var/solr/data
volumes: volumes:
# Mount our "solr_configs" volume available under the Solr's configsets folder (in a 'dspace' subfolder)
# This copies the Solr configs from main 'dspace' container into 'dspacesolr' via that volume
- solr_configs:/opt/solr/server/solr/configsets/dspace
# Keep Solr data directory between reboots # Keep Solr data directory between reboots
- solr_data:/var/solr/data - solr_data:/var/solr/data
# Initialize all DSpace Solr cores using the mounted configsets (see above), then start Solr # Initialize all DSpace Solr cores using the mounted configsets (see above), then start Solr
@@ -103,14 +95,18 @@ services:
- '-c' - '-c'
- | - |
init-var-solr init-var-solr
precreate-core authority /opt/solr/server/solr/configsets/dspace/authority precreate-core authority /opt/solr/server/solr/configsets/authority
precreate-core oai /opt/solr/server/solr/configsets/dspace/oai cp -r /opt/solr/server/solr/configsets/authority/* authority
precreate-core search /opt/solr/server/solr/configsets/dspace/search precreate-core oai /opt/solr/server/solr/configsets/oai
precreate-core statistics /opt/solr/server/solr/configsets/dspace/statistics cp -r /opt/solr/server/solr/configsets/oai/* oai
precreate-core search /opt/solr/server/solr/configsets/search
cp -r /opt/solr/server/solr/configsets/search/* search
precreate-core statistics /opt/solr/server/solr/configsets/statistics
cp -r /opt/solr/server/solr/configsets/statistics/* statistics
precreate-core qaevent /opt/solr/server/solr/configsets/qaevent
cp -r /opt/solr/server/solr/configsets/qaevent/* qaevent
exec solr -f exec solr -f
volumes: volumes:
assetstore: assetstore:
pgdata: pgdata:
solr_data: solr_data:
# Special volume used to share Solr configs from 'dspace' to 'dspacesolr' container (see above)
solr_configs:

View File

@@ -43,7 +43,7 @@ services:
depends_on: depends_on:
- dspacedb - dspacedb
networks: networks:
dspacenet: - dspacenet
ports: ports:
- published: 8080 - published: 8080
target: 8080 target: 8080
@@ -51,8 +51,6 @@ services:
tty: true tty: true
volumes: volumes:
- assetstore:/dspace/assetstore - assetstore:/dspace/assetstore
# Mount DSpace's solr configs to a volume, so that we can share to 'dspacesolr' container (see below)
- solr_configs:/dspace/solr
# Ensure that the database is ready BEFORE starting tomcat # Ensure that the database is ready BEFORE starting tomcat
# 1. While a TCP connection to dspacedb port 5432 is not available, continue to sleep # 1. While a TCP connection to dspacedb port 5432 is not available, continue to sleep
# 2. Then, run database migration to init database tables # 2. Then, run database migration to init database tables
@@ -69,25 +67,23 @@ services:
container_name: dspacedb container_name: dspacedb
environment: environment:
PGDATA: /pgdata PGDATA: /pgdata
image: dspace/dspace-postgres-pgcrypto image: "${DOCKER_OWNER:-dspace}/dspace-postgres-pgcrypto:${DSPACE_VER:-latest}"
networks: networks:
dspacenet: - dspacenet
ports: ports:
- published: 5432 - published: 5432
target: 5432 target: 5432
stdin_open: true stdin_open: true
tty: true tty: true
volumes: volumes:
# Keep Postgres data directory between reboots
- pgdata:/pgdata - pgdata:/pgdata
# DSpace Solr container # DSpace Solr container
dspacesolr: dspacesolr:
container_name: dspacesolr container_name: dspacesolr
image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-latest}" image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-latest}"
# Needs main 'dspace' container to start first to guarantee access to solr_configs
depends_on:
- dspace
networks: networks:
dspacenet: - dspacenet
ports: ports:
- published: 8983 - published: 8983
target: 8983 target: 8983
@@ -115,10 +111,10 @@ services:
cp -r /opt/solr/server/solr/configsets/search/* search cp -r /opt/solr/server/solr/configsets/search/* search
precreate-core statistics /opt/solr/server/solr/configsets/statistics precreate-core statistics /opt/solr/server/solr/configsets/statistics
cp -r /opt/solr/server/solr/configsets/statistics/* statistics cp -r /opt/solr/server/solr/configsets/statistics/* statistics
precreate-core qaevent /opt/solr/server/solr/configsets/qaevent
cp -r /opt/solr/server/solr/configsets/qaevent/* qaevent
exec solr -f exec solr -f
volumes: volumes:
assetstore: assetstore:
pgdata: pgdata:
solr_data: solr_data:
# Special volume used to share Solr configs from 'dspace' to 'dspacesolr' container (see above)
solr_configs:

View File

@@ -1,4 +1,5 @@
<div class="container"> <div class="container">
<h1>{{ 'admin.access-control.bulk-access.title' | translate }}</h1>
<ds-bulk-access-browse [listId]="listId"></ds-bulk-access-browse> <ds-bulk-access-browse [listId]="listId"></ds-bulk-access-browse>
<div class="clearfix mb-3"></div> <div class="clearfix mb-3"></div>
<ds-bulk-access-settings #dsBulkSettings ></ds-bulk-access-settings> <ds-bulk-access-settings #dsBulkSettings ></ds-bulk-access-settings>

View File

@@ -201,7 +201,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
deleteEPerson(ePerson: EPerson) { deleteEPerson(ePerson: EPerson) {
if (hasValue(ePerson.id)) { if (hasValue(ePerson.id)) {
const modalRef = this.modalService.open(ConfirmationModalComponent); const modalRef = this.modalService.open(ConfirmationModalComponent);
modalRef.componentInstance.dso = ePerson; modalRef.componentInstance.name = this.dsoNameService.getName(ePerson);
modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header'; modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header';
modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info'; modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info';
modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel'; modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel';

View File

@@ -478,7 +478,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
take(1), take(1),
switchMap((eperson: EPerson) => { switchMap((eperson: EPerson) => {
const modalRef = this.modalService.open(ConfirmationModalComponent); const modalRef = this.modalService.open(ConfirmationModalComponent);
modalRef.componentInstance.dso = eperson; modalRef.componentInstance.name = this.dsoNameService.getName(eperson);
modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header'; modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header';
modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info'; modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info';
modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel'; modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel';

View File

@@ -420,7 +420,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
delete() { delete() {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((group: Group) => { this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((group: Group) => {
const modalRef = this.modalService.open(ConfirmationModalComponent); const modalRef = this.modalService.open(ConfirmationModalComponent);
modalRef.componentInstance.dso = group; modalRef.componentInstance.name = this.dsoNameService.getName(group);
modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-group.modal.header'; modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-group.modal.header';
modalRef.componentInstance.infoLabel = this.messagePrefix + '.delete-group.modal.info'; modalRef.componentInstance.infoLabel = this.messagePrefix + '.delete-group.modal.info';
modalRef.componentInstance.cancelLabel = this.messagePrefix + '.delete-group.modal.cancel'; modalRef.componentInstance.cancelLabel = this.messagePrefix + '.delete-group.modal.cancel';

View File

@@ -24,8 +24,7 @@
<tr *ngFor="let eperson of (ePeopleMembersOfGroup | async)?.page"> <tr *ngFor="let eperson of (ePeopleMembersOfGroup | async)?.page">
<td class="align-middle">{{eperson.id}}</td> <td class="align-middle">{{eperson.id}}</td>
<td class="align-middle"> <td class="align-middle">
<a (click)="ePersonDataService.startEditingNewEPerson(eperson)" <a [routerLink]="getEPersonEditRoute(eperson.id)">
[routerLink]="[ePersonDataService.getEPeoplePageRouterLink()]">
{{ dsoNameService.getName(eperson) }} {{ dsoNameService.getName(eperson) }}
</a> </a>
</td> </td>
@@ -106,8 +105,7 @@
<tr *ngFor="let eperson of (ePeopleSearch | async)?.page"> <tr *ngFor="let eperson of (ePeopleSearch | async)?.page">
<td class="align-middle">{{eperson.id}}</td> <td class="align-middle">{{eperson.id}}</td>
<td class="align-middle"> <td class="align-middle">
<a (click)="ePersonDataService.startEditingNewEPerson(eperson)" <a [routerLink]="getEPersonEditRoute(eperson.id)">
[routerLink]="[ePersonDataService.getEPeoplePageRouterLink()]">
{{ dsoNameService.getName(eperson) }} {{ dsoNameService.getName(eperson) }}
</a> </a>
</td> </td>

View File

@@ -68,9 +68,6 @@ describe('MembersListComponent', () => {
clearLinkRequests() { clearLinkRequests() {
// empty // empty
}, },
getEPeoplePageRouterLink(): string {
return '/access-control/epeople';
}
}; };
groupsDataServiceStub = { groupsDataServiceStub = {
activeGroup: activeGroup, activeGroup: activeGroup,

View File

@@ -23,6 +23,7 @@ import { NotificationsService } from '../../../../shared/notifications/notificat
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { PaginationService } from '../../../../core/pagination/pagination.service'; import { PaginationService } from '../../../../core/pagination/pagination.service';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { getEPersonEditRoute } from '../../../access-control-routing-paths';
/** /**
* Keys to keep track of specific subscriptions * Keys to keep track of specific subscriptions
@@ -131,6 +132,8 @@ export class MembersListComponent implements OnInit, OnDestroy {
// current active group being edited // current active group being edited
groupBeingEdited: Group; groupBeingEdited: Group;
readonly getEPersonEditRoute = getEPersonEditRoute;
constructor( constructor(
protected groupDataService: GroupDataService, protected groupDataService: GroupDataService,
public ePersonDataService: EPersonDataService, public ePersonDataService: EPersonDataService,

View File

@@ -1,5 +1,5 @@
<div class="container"> <div class="container">
<h2 id="header">{{'admin.batch-import.page.header' | translate}}</h2> <h1 id="header">{{'admin.batch-import.page.header' | translate}}</h1>
<p>{{'admin.batch-import.page.help' | translate}}</p> <p>{{'admin.batch-import.page.help' | translate}}</p>
<p *ngIf="dso"> <p *ngIf="dso">
selected collection: <b>{{getDspaceObjectName()}}</b>&nbsp; selected collection: <b>{{getDspaceObjectName()}}</b>&nbsp;

View File

@@ -0,0 +1,8 @@
import { URLCombiner } from '../../core/url-combiner/url-combiner';
import { getNotificationsModuleRoute } from '../admin-routing-paths';
export const QUALITY_ASSURANCE_EDIT_PATH = 'quality-assurance';
export function getQualityAssuranceRoute(id: string) {
return new URLCombiner(getNotificationsModuleRoute(), QUALITY_ASSURANCE_EDIT_PATH, id).toString();
}

View File

@@ -0,0 +1,87 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthenticatedGuard } from '../../core/auth/authenticated.guard';
import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
import { I18nBreadcrumbsService } from '../../core/breadcrumbs/i18n-breadcrumbs.service';
import { QUALITY_ASSURANCE_EDIT_PATH } from './admin-notifications-routing-paths';
import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component';
import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.component';
import { AdminQualityAssuranceTopicsPageResolver } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page-resolver.service';
import { AdminQualityAssuranceEventsPageResolver } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.resolver';
import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component';
import { AdminQualityAssuranceSourcePageResolver } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page-resolver.service';
import { QualityAssuranceBreadcrumbResolver } from '../../core/breadcrumbs/quality-assurance-breadcrumb.resolver';
import { QualityAssuranceBreadcrumbService } from '../../core/breadcrumbs/quality-assurance-breadcrumb.service';
import {
SourceDataResolver
} from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-data.resolver';
@NgModule({
imports: [
RouterModule.forChild([
{
canActivate: [ AuthenticatedGuard ],
path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId`,
component: AdminQualityAssuranceTopicsPageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: QualityAssuranceBreadcrumbResolver,
openaireQualityAssuranceTopicsParams: AdminQualityAssuranceTopicsPageResolver
},
data: {
title: 'admin.quality-assurance.page.title',
breadcrumbKey: 'admin.quality-assurance',
showBreadcrumbsFluid: false
}
},
{
canActivate: [ AuthenticatedGuard ],
path: `${QUALITY_ASSURANCE_EDIT_PATH}`,
component: AdminQualityAssuranceSourcePageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: I18nBreadcrumbResolver,
openaireQualityAssuranceSourceParams: AdminQualityAssuranceSourcePageResolver,
sourceData: SourceDataResolver
},
data: {
title: 'admin.notifications.source.breadcrumbs',
breadcrumbKey: 'admin.notifications.source',
showBreadcrumbsFluid: false
}
},
{
canActivate: [ AuthenticatedGuard ],
path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId/:topicId`,
component: AdminQualityAssuranceEventsPageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: QualityAssuranceBreadcrumbResolver,
openaireQualityAssuranceEventsParams: AdminQualityAssuranceEventsPageResolver
},
data: {
title: 'admin.notifications.event.page.title',
breadcrumbKey: 'admin.notifications.event',
showBreadcrumbsFluid: false
}
}
])
],
providers: [
I18nBreadcrumbResolver,
I18nBreadcrumbsService,
SourceDataResolver,
AdminQualityAssuranceTopicsPageResolver,
AdminQualityAssuranceEventsPageResolver,
AdminQualityAssuranceSourcePageResolver,
QualityAssuranceBreadcrumbResolver,
QualityAssuranceBreadcrumbService
]
})
/**
* Routing module for the Notifications section of the admin sidebar
*/
export class AdminNotificationsRoutingModule {
}

View File

@@ -0,0 +1,31 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { CoreModule } from '../../core/core.module';
import { SharedModule } from '../../shared/shared.module';
import { AdminNotificationsRoutingModule } from './admin-notifications-routing.module';
import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component';
import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.component';
import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component';
import {NotificationsModule} from '../../notifications/notifications.module';
@NgModule({
imports: [
CommonModule,
SharedModule,
CoreModule.forRoot(),
AdminNotificationsRoutingModule,
NotificationsModule
],
declarations: [
AdminQualityAssuranceTopicsPageComponent,
AdminQualityAssuranceEventsPageComponent,
AdminQualityAssuranceSourcePageComponent
],
entryComponents: []
})
/**
* This module handles all components related to the notifications pages
*/
export class AdminNotificationsModule {
}

View File

@@ -0,0 +1 @@
<ds-quality-assurance-events></ds-quality-assurance-events>

View File

@@ -0,0 +1,26 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page.component';
describe('AdminQualityAssuranceEventsPageComponent', () => {
let component: AdminQualityAssuranceEventsPageComponent;
let fixture: ComponentFixture<AdminQualityAssuranceEventsPageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AdminQualityAssuranceEventsPageComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdminQualityAssuranceEventsPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create AdminQualityAssuranceEventsPageComponent', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,12 @@
import { Component } from '@angular/core';
/**
* Component for the page that show the QA events related to a specific topic.
*/
@Component({
selector: 'ds-quality-assurance-events-page',
templateUrl: './admin-quality-assurance-events-page.component.html'
})
export class AdminQualityAssuranceEventsPageComponent {
}

View File

@@ -0,0 +1,32 @@
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
/**
* Interface for the route parameters.
*/
export interface AdminQualityAssuranceEventsPageParams {
pageId?: string;
pageSize?: number;
currentPage?: number;
}
/**
* This class represents a resolver that retrieve the route data before the route is activated.
*/
@Injectable()
export class AdminQualityAssuranceEventsPageResolver implements Resolve<AdminQualityAssuranceEventsPageParams> {
/**
* Method for resolving the parameters in the current route.
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
* @returns AdminQualityAssuranceEventsPageParams Emits the route parameters
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminQualityAssuranceEventsPageParams {
return {
pageId: route.queryParams.pageId,
pageSize: parseInt(route.queryParams.pageSize, 10),
currentPage: parseInt(route.queryParams.page, 10)
};
}
}

View File

@@ -0,0 +1,47 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { QualityAssuranceSourceObject } from '../../../core/notifications/qa/models/quality-assurance-source.model';
import { QualityAssuranceSourceService } from '../../../notifications/qa/source/quality-assurance-source.service';
import {environment} from '../../../../environments/environment';
/**
* This class represents a resolver that retrieve the route data before the route is activated.
*/
@Injectable()
export class SourceDataResolver implements Resolve<Observable<QualityAssuranceSourceObject[]>> {
private pageSize = environment.qualityAssuranceConfig.pageSize;
/**
* Initialize the effect class variables.
* @param {QualityAssuranceSourceService} qualityAssuranceSourceService
*/
constructor(
private qualityAssuranceSourceService: QualityAssuranceSourceService,
private router: Router
) { }
/**
* Method for resolving the parameters in the current route.
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
* @returns Observable<QualityAssuranceSourceObject[]>
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<QualityAssuranceSourceObject[]> {
return this.qualityAssuranceSourceService.getSources(this.pageSize, 0).pipe(
map((sources: PaginatedList<QualityAssuranceSourceObject>) => {
if (sources.page.length === 1) {
this.router.navigate([this.getResolvedUrl(route) + '/' + sources.page[0].id]);
}
return sources.page;
}));
}
/**
*
* @param route url path
* @returns url path
*/
getResolvedUrl(route: ActivatedRouteSnapshot): string {
return route.pathFromRoot.map(v => v.url.map(segment => segment.toString()).join('/')).join('/');
}
}

View File

@@ -0,0 +1,32 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
/**
* Interface for the route parameters.
*/
export interface AdminQualityAssuranceSourcePageParams {
pageId?: string;
pageSize?: number;
currentPage?: number;
}
/**
* This class represents a resolver that retrieve the route data before the route is activated.
*/
@Injectable()
export class AdminQualityAssuranceSourcePageResolver implements Resolve<AdminQualityAssuranceSourcePageParams> {
/**
* Method for resolving the parameters in the current route.
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
* @returns AdminQualityAssuranceSourcePageParams Emits the route parameters
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminQualityAssuranceSourcePageParams {
return {
pageId: route.queryParams.pageId,
pageSize: parseInt(route.queryParams.pageSize, 10),
currentPage: parseInt(route.queryParams.page, 10)
};
}
}

View File

@@ -0,0 +1 @@
<ds-quality-assurance-source></ds-quality-assurance-source>

View File

@@ -0,0 +1,27 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page.component';
describe('AdminQualityAssuranceSourcePageComponent', () => {
let component: AdminQualityAssuranceSourcePageComponent;
let fixture: ComponentFixture<AdminQualityAssuranceSourcePageComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AdminQualityAssuranceSourcePageComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AdminQualityAssuranceSourcePageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create AdminQualityAssuranceSourcePageComponent', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
/**
* Component for the page that show the QA sources.
*/
@Component({
selector: 'ds-admin-quality-assurance-source-page-component',
templateUrl: './admin-quality-assurance-source-page.component.html',
})
export class AdminQualityAssuranceSourcePageComponent {}

View File

@@ -0,0 +1,32 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
/**
* Interface for the route parameters.
*/
export interface AdminQualityAssuranceTopicsPageParams {
pageId?: string;
pageSize?: number;
currentPage?: number;
}
/**
* This class represents a resolver that retrieve the route data before the route is activated.
*/
@Injectable()
export class AdminQualityAssuranceTopicsPageResolver implements Resolve<AdminQualityAssuranceTopicsPageParams> {
/**
* Method for resolving the parameters in the current route.
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
* @returns AdminQualityAssuranceTopicsPageParams Emits the route parameters
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminQualityAssuranceTopicsPageParams {
return {
pageId: route.queryParams.pageId,
pageSize: parseInt(route.queryParams.pageSize, 10),
currentPage: parseInt(route.queryParams.page, 10)
};
}
}

View File

@@ -0,0 +1 @@
<ds-quality-assurance-topic></ds-quality-assurance-topic>

View File

@@ -0,0 +1,26 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page.component';
describe('AdminQualityAssuranceTopicsPageComponent', () => {
let component: AdminQualityAssuranceTopicsPageComponent;
let fixture: ComponentFixture<AdminQualityAssuranceTopicsPageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AdminQualityAssuranceTopicsPageComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdminQualityAssuranceTopicsPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create AdminQualityAssuranceTopicsPageComponent', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,12 @@
import { Component } from '@angular/core';
/**
* Component for the page that show the QA topics related to a specific source.
*/
@Component({
selector: 'ds-notification-qa-page',
templateUrl: './admin-quality-assurance-topics-page.component.html'
})
export class AdminQualityAssuranceTopicsPageComponent {
}

View File

@@ -19,7 +19,7 @@
<table id="formats" class="table table-striped table-hover"> <table id="formats" class="table table-striped table-hover">
<thead> <thead>
<tr> <tr>
<th scope="col" [attr.aria-label]="'admin.registries.bitstream-formats.select' | translate"></th> <th scope="col"><span class="sr-only">{{'admin.registries.bitstream-formats.table.selected' | translate}}</span></th>
<th scope="col">{{'admin.registries.bitstream-formats.table.id' | translate}}</th> <th scope="col">{{'admin.registries.bitstream-formats.table.id' | translate}}</th>
<th scope="col">{{'admin.registries.bitstream-formats.table.name' | translate}}</th> <th scope="col">{{'admin.registries.bitstream-formats.table.name' | translate}}</th>
<th scope="col">{{'admin.registries.bitstream-formats.table.mimetype' | translate}}</th> <th scope="col">{{'admin.registries.bitstream-formats.table.mimetype' | translate}}</th>
@@ -35,6 +35,7 @@
[checked]="isSelected(bitstreamFormat) | async" [checked]="isSelected(bitstreamFormat) | async"
(change)="selectBitStreamFormat(bitstreamFormat, $event)" (change)="selectBitStreamFormat(bitstreamFormat, $event)"
> >
<span class="sr-only">{{'admin.registries.bitstream-formats.select' | translate}}}</span>
</label> </label>
</td> </td>
<td><a [routerLink]="['/admin/registries/bitstream-formats', bitstreamFormat.id, 'edit']">{{bitstreamFormat.id}}</a></td> <td><a [routerLink]="['/admin/registries/bitstream-formats', bitstreamFormat.id, 'edit']">{{bitstreamFormat.id}}</a></td>

View File

@@ -2,7 +2,7 @@
<div class="metadata-registry row"> <div class="metadata-registry row">
<div class="col-12"> <div class="col-12">
<h2 id="header" class="border-bottom pb-2">{{'admin.registries.metadata.head' | translate}}</h2> <h1 id="header" class="border-bottom pb-2">{{'admin.registries.metadata.head' | translate}}</h1>
<p id="description" class="pb-2">{{'admin.registries.metadata.description' | translate}}</p> <p id="description" class="pb-2">{{'admin.registries.metadata.description' | translate}}</p>
@@ -19,7 +19,7 @@
<table id="metadata-schemas" class="table table-striped table-hover"> <table id="metadata-schemas" class="table table-striped table-hover">
<thead> <thead>
<tr> <tr>
<th scope="col"></th> <th scope="col"><span class="sr-only">{{'admin.registries.metadata.schemas.table.selected' | translate}}</span></th>
<th scope="col">{{'admin.registries.metadata.schemas.table.id' | translate}}</th> <th scope="col">{{'admin.registries.metadata.schemas.table.id' | translate}}</th>
<th scope="col">{{'admin.registries.metadata.schemas.table.namespace' | translate}}</th> <th scope="col">{{'admin.registries.metadata.schemas.table.namespace' | translate}}</th>
<th scope="col">{{'admin.registries.metadata.schemas.table.name' | translate}}</th> <th scope="col">{{'admin.registries.metadata.schemas.table.name' | translate}}</th>
@@ -34,6 +34,7 @@
[checked]="isSelected(schema) | async" [checked]="isSelected(schema) | async"
(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>
</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,11 +1,11 @@
<div *ngIf="registryService.getActiveMetadataSchema() | async; then editheader; else createHeader"></div> <div *ngIf="registryService.getActiveMetadataSchema() | async; then editheader; else createHeader"></div>
<ng-template #createHeader> <ng-template #createHeader>
<h4>{{messagePrefix + '.create' | translate}}</h4> <h2>{{messagePrefix + '.create' | translate}}</h2>
</ng-template> </ng-template>
<ng-template #editheader> <ng-template #editheader>
<h4>{{messagePrefix + '.edit' | translate}}</h4> <h2>{{messagePrefix + '.edit' | translate}}</h2>
</ng-template> </ng-template>
<ds-form [formId]="formId" <ds-form [formId]="formId"

View File

@@ -1,11 +1,11 @@
<div *ngIf="registryService.getActiveMetadataField() | async; then editheader; else createHeader"></div> <div *ngIf="registryService.getActiveMetadataField() | async; then editheader; else createHeader"></div>
<ng-template #createHeader> <ng-template #createHeader>
<h4>{{messagePrefix + '.create' | translate}}</h4> <h2>{{messagePrefix + '.create' | translate}}</h2>
</ng-template> </ng-template>
<ng-template #editheader> <ng-template #editheader>
<h4>{{messagePrefix + '.edit' | translate}}</h4> <h2>{{messagePrefix + '.edit' | translate}}</h2>
</ng-template> </ng-template>
<ds-form [formId]="formId" <ds-form [formId]="formId"

View File

@@ -2,7 +2,7 @@
<div class="metadata-schema row"> <div class="metadata-schema row">
<div class="col-12" *ngVar="(metadataSchema$ | async) as schema"> <div class="col-12" *ngVar="(metadataSchema$ | async) as schema">
<h2 id="header" class="border-bottom pb-2">{{'admin.registries.schema.head' | translate}}: "{{schema?.prefix}}"</h2> <h1 id="header" class="border-bottom pb-2">{{'admin.registries.schema.head' | translate}}: "{{schema?.prefix}}"</h1>
<p id="description" class="pb-2">{{'admin.registries.schema.description' | translate:{ namespace: schema?.namespace } }}</p> <p id="description" class="pb-2">{{'admin.registries.schema.description' | translate:{ namespace: schema?.namespace } }}</p>
@@ -10,7 +10,7 @@
[metadataSchema]="schema" [metadataSchema]="schema"
(submitForm)="forceUpdateFields()"></ds-metadata-field-form> (submitForm)="forceUpdateFields()"></ds-metadata-field-form>
<h3>{{'admin.registries.schema.fields.head' | translate}}</h3> <h2>{{'admin.registries.schema.fields.head' | translate}}</h2>
<ng-container *ngVar="(metadataFields$ | async)?.payload as fields"> <ng-container *ngVar="(metadataFields$ | async)?.payload as fields">
<ds-pagination <ds-pagination
@@ -24,7 +24,7 @@
<table id="metadata-fields" class="table table-striped table-hover"> <table id="metadata-fields" class="table table-striped table-hover">
<thead> <thead>
<tr> <tr>
<th></th> <th><span class="sr-only">{{'admin.registries.schema.fields.table.selected' | translate}}</span></th>
<th scope="col">{{'admin.registries.schema.fields.table.id' | translate}}</th> <th scope="col">{{'admin.registries.schema.fields.table.id' | translate}}</th>
<th scope="col">{{'admin.registries.schema.fields.table.field' | translate}}</th> <th scope="col">{{'admin.registries.schema.fields.table.field' | translate}}</th>
<th scope="col">{{'admin.registries.schema.fields.table.scopenote' | translate}}</th> <th scope="col">{{'admin.registries.schema.fields.table.scopenote' | translate}}</th>
@@ -33,12 +33,11 @@
<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' : isActive(field) | async}">
<td> <td *ngVar="(isSelected(field) | async) as selected">
<label class="mb-0">
<input type="checkbox" <input type="checkbox"
[checked]="isSelected(field) | async" [attr.aria-label]="(selected ? 'admin.registries.schema.fields.deselect' : 'admin.registries.schema.fields.select') | translate"
[checked]="selected"
(change)="selectMetadataField(field, $event)"> (change)="selectMetadataField(field, $event)">
</label>
</td> </td>
<td class="selectable-row" (click)="editField(field)">{{field.id}}</td> <td class="selectable-row" (click)="editField(field)">{{field.id}}</td>
<td class="selectable-row" (click)="editField(field)">{{schema?.prefix}}.{{field.element}}{{field.qualifier ? '.' + field.qualifier : ''}}</td> <td class="selectable-row" (click)="editField(field)">{{schema?.prefix}}.{{field.element}}{{field.qualifier ? '.' + field.qualifier : ''}}</td>

View File

@@ -2,7 +2,12 @@ import { URLCombiner } from '../core/url-combiner/url-combiner';
import { getAdminModuleRoute } from '../app-routing-paths'; import { getAdminModuleRoute } from '../app-routing-paths';
export const REGISTRIES_MODULE_PATH = 'registries'; export const REGISTRIES_MODULE_PATH = 'registries';
export const NOTIFICATIONS_MODULE_PATH = 'notifications';
export function getRegistriesModuleRoute() { export function getRegistriesModuleRoute() {
return new URLCombiner(getAdminModuleRoute(), REGISTRIES_MODULE_PATH).toString(); return new URLCombiner(getAdminModuleRoute(), REGISTRIES_MODULE_PATH).toString();
} }
export function getNotificationsModuleRoute() {
return new URLCombiner(getAdminModuleRoute(), NOTIFICATIONS_MODULE_PATH).toString();
}

View File

@@ -6,12 +6,17 @@ import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.reso
import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow-page.component'; import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow-page.component';
import { I18nBreadcrumbsService } from '../core/breadcrumbs/i18n-breadcrumbs.service'; import { I18nBreadcrumbsService } from '../core/breadcrumbs/i18n-breadcrumbs.service';
import { AdminCurationTasksComponent } from './admin-curation-tasks/admin-curation-tasks.component'; import { AdminCurationTasksComponent } from './admin-curation-tasks/admin-curation-tasks.component';
import { REGISTRIES_MODULE_PATH } from './admin-routing-paths'; import { REGISTRIES_MODULE_PATH, NOTIFICATIONS_MODULE_PATH } from './admin-routing-paths';
import { BatchImportPageComponent } from './admin-import-batch-page/batch-import-page.component'; import { BatchImportPageComponent } from './admin-import-batch-page/batch-import-page.component';
@NgModule({ @NgModule({
imports: [ imports: [
RouterModule.forChild([ RouterModule.forChild([
{
path: NOTIFICATIONS_MODULE_PATH,
loadChildren: () => import('./admin-notifications/admin-notifications.module')
.then((m) => m.AdminNotificationsModule),
},
{ {
path: REGISTRIES_MODULE_PATH, path: REGISTRIES_MODULE_PATH,
loadChildren: () => import('./admin-registries/admin-registries.module') loadChildren: () => import('./admin-registries/admin-registries.module')

View File

@@ -1,4 +1,4 @@
<ng-template dsListableObject> <ng-template dsDynamicComponentLoader>
</ng-template> </ng-template>
<div #badges> <div #badges>
<ng-content></ng-content> <ng-content></ng-content>

View File

@@ -1,4 +1,4 @@
import { Component, ComponentFactoryResolver, ElementRef, OnInit, ViewChild } from '@angular/core'; import { Component, ComponentRef, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Item } from '../../../../../core/shared/item.model'; import { Item } from '../../../../../core/shared/item.model';
import { ViewMode } from '../../../../../core/shared/view-mode.model'; import { ViewMode } from '../../../../../core/shared/view-mode.model';
import { import {
@@ -11,9 +11,10 @@ import { SearchResultGridElementComponent } from '../../../../../shared/object-g
import { TruncatableService } from '../../../../../shared/truncatable/truncatable.service'; import { TruncatableService } from '../../../../../shared/truncatable/truncatable.service';
import { BitstreamDataService } from '../../../../../core/data/bitstream-data.service'; import { BitstreamDataService } from '../../../../../core/data/bitstream-data.service';
import { GenericConstructor } from '../../../../../core/shared/generic-constructor'; import { GenericConstructor } from '../../../../../core/shared/generic-constructor';
import { ListableObjectDirective } from '../../../../../shared/object-collection/shared/listable-object/listable-object.directive'; import { DynamicComponentLoaderDirective } from '../../../../../shared/abstract-component-loader/dynamic-component-loader.directive';
import { ThemeService } from '../../../../../shared/theme-support/theme.service'; import { ThemeService } from '../../../../../shared/theme-support/theme.service';
import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service';
import { hasValue } from '../../../../../shared/empty.util';
@listableObjectComponent(ItemSearchResult, ViewMode.GridElement, Context.AdminSearch) @listableObjectComponent(ItemSearchResult, ViewMode.GridElement, Context.AdminSearch)
@Component({ @Component({
@@ -24,17 +25,18 @@ import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service
/** /**
* The component for displaying a list element for an item search result on the admin search page * The component for displaying a list element for an item search result on the admin search page
*/ */
export class ItemAdminSearchResultGridElementComponent extends SearchResultGridElementComponent<ItemSearchResult, Item> implements OnInit { export class ItemAdminSearchResultGridElementComponent extends SearchResultGridElementComponent<ItemSearchResult, Item> implements OnDestroy, OnInit {
@ViewChild(ListableObjectDirective, { static: true }) listableObjectDirective: ListableObjectDirective; @ViewChild(DynamicComponentLoaderDirective, { static: true }) dynamicComponentLoaderDirective: DynamicComponentLoaderDirective;
@ViewChild('badges', { static: true }) badges: ElementRef; @ViewChild('badges', { static: true }) badges: ElementRef;
@ViewChild('buttons', { static: true }) buttons: ElementRef; @ViewChild('buttons', { static: true }) buttons: ElementRef;
protected compRef: ComponentRef<Component>;
constructor( constructor(
public dsoNameService: DSONameService, public dsoNameService: DSONameService,
protected truncatableService: TruncatableService, protected truncatableService: TruncatableService,
protected bitstreamDataService: BitstreamDataService, protected bitstreamDataService: BitstreamDataService,
private themeService: ThemeService, private themeService: ThemeService,
private componentFactoryResolver: ComponentFactoryResolver,
) { ) {
super(dsoNameService, truncatableService, bitstreamDataService); super(dsoNameService, truncatableService, bitstreamDataService);
} }
@@ -44,23 +46,32 @@ export class ItemAdminSearchResultGridElementComponent extends SearchResultGridE
*/ */
ngOnInit(): void { ngOnInit(): void {
super.ngOnInit(); super.ngOnInit();
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.getComponent()); const component: GenericConstructor<Component> = this.getComponent();
const viewContainerRef = this.listableObjectDirective.viewContainerRef; const viewContainerRef = this.dynamicComponentLoaderDirective.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent( this.compRef = viewContainerRef.createComponent(
componentFactory, component, {
0, index: 0,
undefined, injector: undefined,
[ projectableNodes: [
[this.badges.nativeElement], [this.badges.nativeElement],
[this.buttons.nativeElement] [this.buttons.nativeElement],
]); ],
(componentRef.instance as any).object = this.object; },
(componentRef.instance as any).index = this.index; );
(componentRef.instance as any).linkType = this.linkType; this.compRef.setInput('object',this.object);
(componentRef.instance as any).listID = this.listID; this.compRef.setInput('index', this.index);
this.compRef.setInput('linkType', this.linkType);
this.compRef.setInput('listID', this.listID);
}
ngOnDestroy(): void {
if (hasValue(this.compRef)) {
this.compRef.destroy();
this.compRef = undefined;
}
} }
/** /**

View File

@@ -124,7 +124,7 @@ export class WorkspaceItemAdminWorkflowActionsComponent implements OnInit {
*/ */
deleteSupervisionOrder(supervisionOrderEntry: SupervisionOrderListEntry) { deleteSupervisionOrder(supervisionOrderEntry: SupervisionOrderListEntry) {
const modalRef = this.modalService.open(ConfirmationModalComponent); const modalRef = this.modalService.open(ConfirmationModalComponent);
modalRef.componentInstance.dso = supervisionOrderEntry.group; modalRef.componentInstance.name = this.dsoNameService.getName(supervisionOrderEntry.group);
modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-supervision.modal.header'; modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-supervision.modal.header';
modalRef.componentInstance.infoLabel = this.messagePrefix + '.delete-supervision.modal.info'; modalRef.componentInstance.infoLabel = this.messagePrefix + '.delete-supervision.modal.info';
modalRef.componentInstance.cancelLabel = this.messagePrefix + '.delete-supervision.modal.cancel'; modalRef.componentInstance.cancelLabel = this.messagePrefix + '.delete-supervision.modal.cancel';

View File

@@ -1,4 +1,4 @@
<ng-template dsListableObject> <ng-template dsDynamicComponentLoader>
</ng-template> </ng-template>
<div #badges class="position-absolute ml-1"> <div #badges class="position-absolute ml-1">
<div class="workflow-badge"> <div class="workflow-badge">

View File

@@ -18,8 +18,8 @@ import {
ItemGridElementComponent ItemGridElementComponent
} from '../../../../../shared/object-grid/item-grid-element/item-types/item/item-grid-element.component'; } from '../../../../../shared/object-grid/item-grid-element/item-types/item/item-grid-element.component';
import { import {
ListableObjectDirective DynamicComponentLoaderDirective
} from '../../../../../shared/object-collection/shared/listable-object/listable-object.directive'; } from '../../../../../shared/abstract-component-loader/dynamic-component-loader.directive';
import { import {
WorkflowItemSearchResult WorkflowItemSearchResult
} from '../../../../../shared/object-collection/shared/workflow-item-search-result.model'; } from '../../../../../shared/object-collection/shared/workflow-item-search-result.model';
@@ -38,7 +38,7 @@ describe('WorkflowItemSearchResultAdminWorkflowGridElementComponent', () => {
let itemRD$; let itemRD$;
let linkService; let linkService;
let object; let object;
let themeService; let themeService: ThemeService;
function init() { function init() {
itemRD$ = createSuccessfulRemoteDataObject$(new Item()); itemRD$ = createSuccessfulRemoteDataObject$(new Item());
@@ -55,7 +55,11 @@ describe('WorkflowItemSearchResultAdminWorkflowGridElementComponent', () => {
init(); init();
TestBed.configureTestingModule( TestBed.configureTestingModule(
{ {
declarations: [WorkflowItemSearchResultAdminWorkflowGridElementComponent, ItemGridElementComponent, ListableObjectDirective], declarations: [
WorkflowItemSearchResultAdminWorkflowGridElementComponent,
ItemGridElementComponent,
DynamicComponentLoaderDirective,
],
imports: [ imports: [
NoopAnimationsModule, NoopAnimationsModule,
TranslateModule.forRoot(), TranslateModule.forRoot(),

View File

@@ -1,4 +1,4 @@
import { Component, ComponentFactoryResolver, ElementRef, ViewChild } from '@angular/core'; import { Component, ElementRef, ViewChild, ComponentRef, OnDestroy, OnInit } from '@angular/core';
import { Item } from '../../../../../core/shared/item.model'; import { Item } from '../../../../../core/shared/item.model';
import { ViewMode } from '../../../../../core/shared/view-mode.model'; import { ViewMode } from '../../../../../core/shared/view-mode.model';
import { import {
@@ -10,7 +10,7 @@ import { SearchResultGridElementComponent } from '../../../../../shared/object-g
import { TruncatableService } from '../../../../../shared/truncatable/truncatable.service'; import { TruncatableService } from '../../../../../shared/truncatable/truncatable.service';
import { BitstreamDataService } from '../../../../../core/data/bitstream-data.service'; import { BitstreamDataService } from '../../../../../core/data/bitstream-data.service';
import { GenericConstructor } from '../../../../../core/shared/generic-constructor'; import { GenericConstructor } from '../../../../../core/shared/generic-constructor';
import { ListableObjectDirective } from '../../../../../shared/object-collection/shared/listable-object/listable-object.directive'; import { DynamicComponentLoaderDirective } from '../../../../../shared/abstract-component-loader/dynamic-component-loader.directive';
import { WorkflowItem } from '../../../../../core/submission/models/workflowitem.model'; import { WorkflowItem } from '../../../../../core/submission/models/workflowitem.model';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { LinkService } from '../../../../../core/cache/builders/link.service'; import { LinkService } from '../../../../../core/cache/builders/link.service';
@@ -24,6 +24,7 @@ import { take } from 'rxjs/operators';
import { WorkflowItemSearchResult } from '../../../../../shared/object-collection/shared/workflow-item-search-result.model'; import { WorkflowItemSearchResult } from '../../../../../shared/object-collection/shared/workflow-item-search-result.model';
import { ThemeService } from '../../../../../shared/theme-support/theme.service'; import { ThemeService } from '../../../../../shared/theme-support/theme.service';
import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service';
import { hasValue } from '../../../../../shared/empty.util';
@listableObjectComponent(WorkflowItemSearchResult, ViewMode.GridElement, Context.AdminWorkflowSearch) @listableObjectComponent(WorkflowItemSearchResult, ViewMode.GridElement, Context.AdminWorkflowSearch)
@Component({ @Component({
@@ -34,11 +35,11 @@ import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service
/** /**
* The component for displaying a grid element for an workflow item on the admin workflow search page * The component for displaying a grid element for an workflow item on the admin workflow search page
*/ */
export class WorkflowItemSearchResultAdminWorkflowGridElementComponent extends SearchResultGridElementComponent<WorkflowItemSearchResult, WorkflowItem> { export class WorkflowItemSearchResultAdminWorkflowGridElementComponent extends SearchResultGridElementComponent<WorkflowItemSearchResult, WorkflowItem> implements OnDestroy, OnInit {
/** /**
* Directive used to render the dynamic component in * Directive used to render the dynamic component in
*/ */
@ViewChild(ListableObjectDirective, { static: true }) listableObjectDirective: ListableObjectDirective; @ViewChild(DynamicComponentLoaderDirective, { static: true }) dynamicComponentLoaderDirective: DynamicComponentLoaderDirective;
/** /**
* The html child that contains the badges html * The html child that contains the badges html
@@ -55,9 +56,10 @@ export class WorkflowItemSearchResultAdminWorkflowGridElementComponent extends S
*/ */
public item$: Observable<Item>; public item$: Observable<Item>;
protected compRef: ComponentRef<Component>;
constructor( constructor(
public dsoNameService: DSONameService, public dsoNameService: DSONameService,
private componentFactoryResolver: ComponentFactoryResolver,
private linkService: LinkService, private linkService: LinkService,
protected truncatableService: TruncatableService, protected truncatableService: TruncatableService,
private themeService: ThemeService, private themeService: ThemeService,
@@ -75,26 +77,34 @@ export class WorkflowItemSearchResultAdminWorkflowGridElementComponent extends S
this.dso = this.linkService.resolveLink(this.dso, followLink('item')); this.dso = this.linkService.resolveLink(this.dso, followLink('item'));
this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload()); this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload());
this.item$.pipe(take(1)).subscribe((item: Item) => { this.item$.pipe(take(1)).subscribe((item: Item) => {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.getComponent(item)); const component: GenericConstructor<Component> = this.getComponent(item);
const viewContainerRef = this.listableObjectDirective.viewContainerRef; const viewContainerRef = this.dynamicComponentLoaderDirective.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent( this.compRef = viewContainerRef.createComponent(
componentFactory, component, {
0, index: 0,
undefined, injector: undefined,
[ projectableNodes: [
[this.badges.nativeElement], [this.badges.nativeElement],
[this.buttons.nativeElement] [this.buttons.nativeElement],
]); ],
(componentRef.instance as any).object = item; },
(componentRef.instance as any).index = this.index;
(componentRef.instance as any).linkType = this.linkType;
(componentRef.instance as any).listID = this.listID;
componentRef.changeDetectorRef.detectChanges();
}
); );
this.compRef.setInput('object', item);
this.compRef.setInput('index', this.index);
this.compRef.setInput('linkType', this.linkType);
this.compRef.setInput('listID', this.listID);
this.compRef.changeDetectorRef.detectChanges();
});
}
ngOnDestroy(): void {
if (hasValue(this.compRef)) {
this.compRef.destroy();
this.compRef = undefined;
}
} }
/** /**

View File

@@ -1,4 +1,4 @@
<ng-template dsListableObject> <ng-template dsDynamicComponentLoader>
</ng-template> </ng-template>
<div #badges class="position-absolute ml-1"> <div #badges class="position-absolute ml-1">
<div class="workflow-badge"> <div class="workflow-badge">

View File

@@ -20,8 +20,8 @@ import {
ItemGridElementComponent ItemGridElementComponent
} from '../../../../../shared/object-grid/item-grid-element/item-types/item/item-grid-element.component'; } from '../../../../../shared/object-grid/item-grid-element/item-types/item/item-grid-element.component';
import { import {
ListableObjectDirective DynamicComponentLoaderDirective
} from '../../../../../shared/object-collection/shared/listable-object/listable-object.directive'; } from '../../../../../shared/abstract-component-loader/dynamic-component-loader.directive';
import { import {
WorkflowItemSearchResult WorkflowItemSearchResult
} from '../../../../../shared/object-collection/shared/workflow-item-search-result.model'; } from '../../../../../shared/object-collection/shared/workflow-item-search-result.model';
@@ -45,7 +45,7 @@ describe('WorkspaceItemSearchResultAdminWorkflowGridElementComponent', () => {
let itemRD$; let itemRD$;
let linkService; let linkService;
let object; let object;
let themeService; let themeService: ThemeService;
let supervisionOrderDataService; let supervisionOrderDataService;
function init() { function init() {
@@ -67,7 +67,11 @@ describe('WorkspaceItemSearchResultAdminWorkflowGridElementComponent', () => {
init(); init();
TestBed.configureTestingModule( TestBed.configureTestingModule(
{ {
declarations: [WorkspaceItemSearchResultAdminWorkflowGridElementComponent, ItemGridElementComponent, ListableObjectDirective], declarations: [
WorkspaceItemSearchResultAdminWorkflowGridElementComponent,
ItemGridElementComponent,
DynamicComponentLoaderDirective,
],
imports: [ imports: [
NoopAnimationsModule, NoopAnimationsModule,
TranslateModule.forRoot(), TranslateModule.forRoot(),

View File

@@ -1,4 +1,4 @@
import { Component, ComponentFactoryResolver, ElementRef, ViewChild, OnInit } from '@angular/core'; import { Component, ElementRef, ViewChild, OnInit, OnDestroy, ComponentRef } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs'; import { BehaviorSubject, Observable } from 'rxjs';
import { map, mergeMap, take, tap } from 'rxjs/operators'; import { map, mergeMap, take, tap } from 'rxjs/operators';
@@ -16,9 +16,7 @@ import {
import { TruncatableService } from '../../../../../shared/truncatable/truncatable.service'; import { TruncatableService } from '../../../../../shared/truncatable/truncatable.service';
import { BitstreamDataService } from '../../../../../core/data/bitstream-data.service'; import { BitstreamDataService } from '../../../../../core/data/bitstream-data.service';
import { GenericConstructor } from '../../../../../core/shared/generic-constructor'; import { GenericConstructor } from '../../../../../core/shared/generic-constructor';
import { import { DynamicComponentLoaderDirective } from '../../../../../shared/abstract-component-loader/dynamic-component-loader.directive';
ListableObjectDirective
} from '../../../../../shared/object-collection/shared/listable-object/listable-object.directive';
import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model'; import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model';
import { LinkService } from '../../../../../core/cache/builders/link.service'; import { LinkService } from '../../../../../core/cache/builders/link.service';
import { followLink } from '../../../../../shared/utils/follow-link-config.model'; import { followLink } from '../../../../../shared/utils/follow-link-config.model';
@@ -37,6 +35,7 @@ import { SupervisionOrder } from '../../../../../core/supervision-order/models/s
import { PaginatedList } from '../../../../../core/data/paginated-list.model'; import { PaginatedList } from '../../../../../core/data/paginated-list.model';
import { SupervisionOrderDataService } from '../../../../../core/supervision-order/supervision-order-data.service'; import { SupervisionOrderDataService } from '../../../../../core/supervision-order/supervision-order-data.service';
import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service';
import { hasValue } from '../../../../../shared/empty.util';
@listableObjectComponent(WorkspaceItemSearchResult, ViewMode.GridElement, Context.AdminWorkflowSearch) @listableObjectComponent(WorkspaceItemSearchResult, ViewMode.GridElement, Context.AdminWorkflowSearch)
@Component({ @Component({
@@ -47,7 +46,7 @@ import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service
/** /**
* The component for displaying a grid element for an workflow item on the admin workflow search page * The component for displaying a grid element for an workflow item on the admin workflow search page
*/ */
export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends SearchResultGridElementComponent<WorkspaceItemSearchResult, WorkspaceItem> implements OnInit { export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends SearchResultGridElementComponent<WorkspaceItemSearchResult, WorkspaceItem> implements OnDestroy, OnInit {
/** /**
* The item linked to the workspace item * The item linked to the workspace item
@@ -67,7 +66,7 @@ export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends
/** /**
* Directive used to render the dynamic component in * Directive used to render the dynamic component in
*/ */
@ViewChild(ListableObjectDirective, { static: true }) listableObjectDirective: ListableObjectDirective; @ViewChild(DynamicComponentLoaderDirective, { static: true }) dynamicComponentLoaderDirective: DynamicComponentLoaderDirective;
/** /**
* The html child that contains the badges html * The html child that contains the badges html
@@ -79,9 +78,13 @@ export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends
*/ */
@ViewChild('buttons', { static: true }) buttons: ElementRef; @ViewChild('buttons', { static: true }) buttons: ElementRef;
/**
* The reference to the dynamic component
*/
protected compRef: ComponentRef<Component>;
constructor( constructor(
public dsoNameService: DSONameService, public dsoNameService: DSONameService,
private componentFactoryResolver: ComponentFactoryResolver,
private linkService: LinkService, private linkService: LinkService,
protected truncatableService: TruncatableService, protected truncatableService: TruncatableService,
private themeService: ThemeService, private themeService: ThemeService,
@@ -100,24 +103,24 @@ export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends
this.dso = this.linkService.resolveLink(this.dso, followLink('item')); this.dso = this.linkService.resolveLink(this.dso, followLink('item'));
this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload()); this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload());
this.item$.pipe(take(1)).subscribe((item: Item) => { this.item$.pipe(take(1)).subscribe((item: Item) => {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.getComponent(item)); const component: GenericConstructor<Component> = this.getComponent(item);
const viewContainerRef = this.listableObjectDirective.viewContainerRef; const viewContainerRef = this.dynamicComponentLoaderDirective.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent( this.compRef = viewContainerRef.createComponent(
componentFactory, component, {
0, index: 0,
undefined, projectableNodes: [
[
[this.badges.nativeElement], [this.badges.nativeElement],
[this.buttons.nativeElement] [this.buttons.nativeElement]
]); ],
(componentRef.instance as any).object = item; });
(componentRef.instance as any).index = this.index; this.compRef.setInput('object', item);
(componentRef.instance as any).linkType = this.linkType; this.compRef.setInput('index', this.index);
(componentRef.instance as any).listID = this.listID; this.compRef.setInput('linkType', this.linkType);
componentRef.changeDetectorRef.detectChanges(); this.compRef.setInput('listID', this.listID);
this.compRef.changeDetectorRef.detectChanges();
} }
); );
@@ -130,6 +133,13 @@ export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends
}); });
} }
ngOnDestroy(): void {
if (hasValue(this.compRef)) {
this.compRef.destroy();
this.compRef = undefined;
}
}
/** /**
* Fetch the component depending on the item's entity type, view mode and context * Fetch the component depending on the item's entity type, view mode and context
* @returns {GenericConstructor<Component>} * @returns {GenericConstructor<Component>}

View File

@@ -1,4 +1,4 @@
import { ChangeDetectorRef, Component, Inject } from '@angular/core'; import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core';
import { import {
BrowseByMetadataPageComponent, BrowseByMetadataPageComponent,
browseParamsToOptions, browseParamsToOptions,
@@ -19,6 +19,8 @@ import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface';
import { RemoteData } from '../../core/data/remote-data'; import { RemoteData } from '../../core/data/remote-data';
import { Item } from '../../core/shared/item.model'; import { Item } from '../../core/shared/item.model';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import { rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { BrowseByDataType } from '../browse-by-switcher/browse-by-data-type';
@Component({ @Component({
selector: 'ds-browse-by-date-page', selector: 'ds-browse-by-date-page',
@@ -30,7 +32,8 @@ import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
* A metadata definition (a.k.a. browse id) is a short term used to describe one or multiple metadata fields. * A metadata definition (a.k.a. browse id) is a short term used to describe one or multiple metadata fields.
* An example would be 'dateissued' for 'dc.date.issued' * An example would be 'dateissued' for 'dc.date.issued'
*/ */
export class BrowseByDatePageComponent extends BrowseByMetadataPageComponent { @rendersBrowseBy(BrowseByDataType.Date)
export class BrowseByDatePageComponent extends BrowseByMetadataPageComponent implements OnInit {
/** /**
* The default metadata keys to use for determining the lower limit of the StartsWith dropdown options * The default metadata keys to use for determining the lower limit of the StartsWith dropdown options

View File

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

View File

@@ -2,7 +2,7 @@ import { first } from 'rxjs/operators';
import { BrowseByGuard } from './browse-by-guard'; import { BrowseByGuard } from './browse-by-guard';
import { of as observableOf } from 'rxjs'; import { of as observableOf } from 'rxjs';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils'; import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils';
import { BrowseByDataType } from './browse-by-switcher/browse-by-decorator'; import { BrowseByDataType } from './browse-by-switcher/browse-by-data-type';
import { ValueListBrowseDefinition } from '../core/shared/value-list-browse-definition.model'; import { ValueListBrowseDefinition } from '../core/shared/value-list-browse-definition.model';
import { DSONameServiceMock } from '../shared/mocks/dso-name.service.mock'; import { DSONameServiceMock } from '../shared/mocks/dso-name.service.mock';
import { DSONameService } from '../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../core/breadcrumbs/dso-name.service';

View File

@@ -1,5 +1,5 @@
import { combineLatest as observableCombineLatest, Observable, Subscription } from 'rxjs'; import { combineLatest as observableCombineLatest, Observable, Subscription } from 'rxjs';
import { Component, Inject, OnInit, OnDestroy } from '@angular/core'; import { Component, Inject, OnInit, OnDestroy, Input } from '@angular/core';
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';
@@ -22,6 +22,9 @@ import { Collection } from '../../core/shared/collection.model';
import { Community } from '../../core/shared/community.model'; import { Community } from '../../core/shared/community.model';
import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface'; import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import { rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { BrowseByDataType } from '../browse-by-switcher/browse-by-data-type';
import { Context } from '../../core/shared/context.model';
export const BBM_PAGINATION_ID = 'bbm'; export const BBM_PAGINATION_ID = 'bbm';
@@ -36,8 +39,19 @@ export const BBM_PAGINATION_ID = 'bbm';
* or multiple metadata fields. An example would be 'author' for * or multiple metadata fields. An example would be 'author' for
* 'dc.contributor.*' * 'dc.contributor.*'
*/ */
@rendersBrowseBy(BrowseByDataType.Metadata)
export class BrowseByMetadataPageComponent implements OnInit, OnDestroy { export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
/**
* The optional context
*/
@Input() context: Context;
/**
* The {@link BrowseByDataType} of this Component
*/
@Input() browseByType: BrowseByDataType;
/** /**
* The list of browse-entries to display * The list of browse-entries to display
*/ */
@@ -130,7 +144,6 @@ export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
@Inject(APP_CONFIG) public appConfig: AppConfig, @Inject(APP_CONFIG) public appConfig: AppConfig,
public dsoNameService: DSONameService, public dsoNameService: DSONameService,
) { ) {
this.fetchThumbnails = this.appConfig.browseBy.showThumbnails; this.fetchThumbnails = this.appConfig.browseBy.showThumbnails;
this.paginationConfig = Object.assign(new PaginationComponentOptions(), { this.paginationConfig = Object.assign(new PaginationComponentOptions(), {
id: BBM_PAGINATION_ID, id: BBM_PAGINATION_ID,
@@ -278,7 +291,7 @@ export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); this.subs.filter((sub: Subscription) => hasValue(sub)).forEach((sub: Subscription) => sub.unsubscribe());
this.paginationService.clearPagination(this.paginationConfig.id); this.paginationService.clearPagination(this.paginationConfig.id);
} }

View File

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

View File

@@ -5,12 +5,19 @@ import { ItemDataService } from '../core/data/item-data.service';
import { BrowseService } from '../core/browse/browse.service'; import { BrowseService } from '../core/browse/browse.service';
import { BrowseByGuard } from './browse-by-guard'; import { BrowseByGuard } from './browse-by-guard';
import { SharedBrowseByModule } from '../shared/browse-by/shared-browse-by.module'; import { SharedBrowseByModule } from '../shared/browse-by/shared-browse-by.module';
import { BrowseByPageComponent } from './browse-by-page/browse-by-page.component';
import { SharedModule } from '../shared/shared.module';
const DECLARATIONS = [
BrowseByPageComponent,
];
@NgModule({ @NgModule({
imports: [ imports: [
SharedBrowseByModule, SharedBrowseByModule,
BrowseByRoutingModule, BrowseByRoutingModule,
BrowseByModule.withEntryComponents(), BrowseByModule,
SharedModule,
], ],
providers: [ providers: [
ItemDataService, ItemDataService,
@@ -18,8 +25,11 @@ import { SharedBrowseByModule } from '../shared/browse-by/shared-browse-by.modul
BrowseByGuard, BrowseByGuard,
], ],
declarations: [ declarations: [
...DECLARATIONS,
] ],
exports: [
...DECLARATIONS,
],
}) })
export class BrowseByPageModule { export class BrowseByPageModule {

View File

@@ -0,0 +1,2 @@
<ds-browse-by-switcher [browseByType]="browseByType$ | async">
</ds-browse-by-switcher>

View File

@@ -0,0 +1,69 @@
// eslint-disable-next-line max-classes-per-file
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowseByPageComponent } from './browse-by-page.component';
import { BrowseBySwitcherComponent } from '../browse-by-switcher/browse-by-switcher.component';
import { DynamicComponentLoaderDirective } from '../../shared/abstract-component-loader/dynamic-component-loader.directive';
import { ActivatedRoute } from '@angular/router';
import { ActivatedRouteStub } from '../../shared/testing/active-router.stub';
import { getMockThemeService } from '../../shared/mocks/theme-service.mock';
import { ThemeService } from '../../shared/theme-support/theme.service';
import { rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { Component } from '@angular/core';
import { BrowseDefinition } from '../../core/shared/browse-definition.model';
import { By } from '@angular/platform-browser';
import { BrowseByDataType } from '../browse-by-switcher/browse-by-data-type';
@rendersBrowseBy('BrowseByPageComponent' as BrowseByDataType)
@Component({
// eslint-disable-next-line @angular-eslint/component-selector
selector: '',
template: '<span id="BrowseByTestComponent"></span>',
})
class BrowseByTestComponent {
}
class TestBrowseByPageBrowseDefinition extends BrowseDefinition {
getRenderType(): BrowseByDataType {
return 'BrowseByPageComponent' as BrowseByDataType;
}
}
describe('BrowseByPageComponent', () => {
let component: BrowseByPageComponent;
let fixture: ComponentFixture<BrowseByPageComponent>;
let activatedRoute: ActivatedRouteStub;
let themeService: ThemeService;
beforeEach(async () => {
activatedRoute = new ActivatedRouteStub();
themeService = getMockThemeService();
await TestBed.configureTestingModule({
declarations: [
BrowseByPageComponent,
BrowseBySwitcherComponent,
DynamicComponentLoaderDirective,
],
providers: [
BrowseByTestComponent,
{ provide: ActivatedRoute, useValue: activatedRoute },
{ provide: ThemeService, useValue: themeService },
],
}).compileComponents();
fixture = TestBed.createComponent(BrowseByPageComponent);
component = fixture.componentInstance;
});
it('should create the correct browse section based on the route browseDefinition', () => {
activatedRoute.testData = {
browseDefinition: new TestBrowseByPageBrowseDefinition(),
};
fixture.detectChanges();
expect(component).toBeTruthy();
expect(fixture.debugElement.query(By.css('#BrowseByTestComponent'))).not.toBeNull();
});
});

View File

@@ -0,0 +1,31 @@
import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { BrowseDefinition } from '../../core/shared/browse-definition.model';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { BrowseByDataType } from '../browse-by-switcher/browse-by-data-type';
@Component({
selector: 'ds-browse-by-page',
templateUrl: './browse-by-page.component.html',
styleUrls: ['./browse-by-page.component.scss'],
})
export class BrowseByPageComponent implements OnInit {
browseByType$: Observable<BrowseByDataType>;
constructor(
protected route: ActivatedRoute,
) {
}
/**
* Fetch the correct browse-by component by using the relevant config from the route data
*/
ngOnInit(): void {
this.browseByType$ = this.route.data.pipe(
map((data: { browseDefinition: BrowseDefinition }) => data.browseDefinition.getRenderType()),
);
}
}

View File

@@ -3,7 +3,7 @@ import { NgModule } from '@angular/core';
import { BrowseByGuard } from './browse-by-guard'; import { BrowseByGuard } from './browse-by-guard';
import { BrowseByDSOBreadcrumbResolver } from './browse-by-dso-breadcrumb.resolver'; import { BrowseByDSOBreadcrumbResolver } from './browse-by-dso-breadcrumb.resolver';
import { BrowseByI18nBreadcrumbResolver } from './browse-by-i18n-breadcrumb.resolver'; import { BrowseByI18nBreadcrumbResolver } from './browse-by-i18n-breadcrumb.resolver';
import { ThemedBrowseBySwitcherComponent } from './browse-by-switcher/themed-browse-by-switcher.component'; import { BrowseByPageComponent } from './browse-by-page/browse-by-page.component';
import { DSOEditMenuResolver } from '../shared/dso-page/dso-edit-menu.resolver'; import { DSOEditMenuResolver } from '../shared/dso-page/dso-edit-menu.resolver';
@NgModule({ @NgModule({
@@ -18,7 +18,7 @@ import { DSOEditMenuResolver } from '../shared/dso-page/dso-edit-menu.resolver';
children: [ children: [
{ {
path: ':id', path: ':id',
component: ThemedBrowseBySwitcherComponent, component: BrowseByPageComponent,
canActivate: [BrowseByGuard], canActivate: [BrowseByGuard],
resolve: { breadcrumb: BrowseByI18nBreadcrumbResolver }, resolve: { breadcrumb: BrowseByI18nBreadcrumbResolver },
data: { title: 'browse.title.page', breadcrumbKey: 'browse.metadata' } data: { title: 'browse.title.page', breadcrumbKey: 'browse.metadata' }

View File

@@ -0,0 +1,6 @@
export enum BrowseByDataType {
Title = 'title',
Metadata = 'text',
Date = 'date',
Hierarchy = 'hierarchy',
}

View File

@@ -1,4 +1,5 @@
import { BrowseByDataType, rendersBrowseBy } from './browse-by-decorator'; import { BrowseByDataType } from './browse-by-data-type';
import { rendersBrowseBy } from './browse-by-decorator';
describe('BrowseByDecorator', () => { describe('BrowseByDecorator', () => {
const titleDecorator = rendersBrowseBy(BrowseByDataType.Title); const titleDecorator = rendersBrowseBy(BrowseByDataType.Title);

View File

@@ -1,40 +1,36 @@
import { Component } from '@angular/core';
import { hasNoValue } from '../../shared/empty.util'; import { hasNoValue } from '../../shared/empty.util';
import { InjectionToken } from '@angular/core'; import { DEFAULT_THEME, resolveTheme } from '../../shared/object-collection/shared/listable-object/listable-object.decorator';
import { Context } from '../../core/shared/context.model';
import { GenericConstructor } from '../../core/shared/generic-constructor'; import { GenericConstructor } from '../../core/shared/generic-constructor';
import { import { BrowseByDataType } from './browse-by-data-type';
DEFAULT_THEME,
resolveTheme
} from '../../shared/object-collection/shared/listable-object/listable-object.decorator';
export enum BrowseByDataType {
Title = 'title',
Metadata = 'text',
Date = 'date'
}
export const DEFAULT_BROWSE_BY_TYPE = BrowseByDataType.Metadata; export const DEFAULT_BROWSE_BY_TYPE = BrowseByDataType.Metadata;
export const DEFAULT_BROWSE_BY_CONTEXT = Context.Any;
export const BROWSE_BY_COMPONENT_FACTORY = new InjectionToken<(browseByType, theme) => GenericConstructor<any>>('getComponentByBrowseByType', { const map: Map<BrowseByDataType, Map<Context, Map<string, GenericConstructor<Component>>>> = new Map();
providedIn: 'root',
factory: () => getComponentByBrowseByType
});
const map = new Map();
/** /**
* Decorator used for rendering Browse-By pages by type * Decorator used for rendering Browse-By pages by type
* @param browseByType The type of page * @param browseByType The type of page
* @param context The optional context for the component
* @param theme The optional theme for the component * @param theme The optional theme for the component
*/ */
export function rendersBrowseBy(browseByType: string, theme = DEFAULT_THEME) { export function rendersBrowseBy(browseByType: BrowseByDataType, context = DEFAULT_BROWSE_BY_CONTEXT, theme = DEFAULT_THEME) {
return function decorator(component: any) { return function decorator(component: any) {
if (hasNoValue(browseByType)) {
return;
}
if (hasNoValue(map.get(browseByType))) { if (hasNoValue(map.get(browseByType))) {
map.set(browseByType, new Map()); map.set(browseByType, new Map());
} }
if (hasNoValue(map.get(browseByType).get(theme))) { if (hasNoValue(map.get(browseByType).get(context))) {
map.get(browseByType).set(theme, component); map.get(browseByType).set(context, new Map());
}
if (hasNoValue(map.get(browseByType).get(context).get(theme))) {
map.get(browseByType).get(context).set(theme, component);
} else { } else {
throw new Error(`There can't be more than one component to render Browse-By of type "${browseByType}" and theme "${theme}"`); throw new Error(`There can't be more than one component to render Browse-By of type "${browseByType}", context "${context}" and theme "${theme}"`);
} }
}; };
} }
@@ -42,12 +38,17 @@ export function rendersBrowseBy(browseByType: string, theme = DEFAULT_THEME) {
/** /**
* Get the component used for rendering a Browse-By page by type * Get the component used for rendering a Browse-By page by type
* @param browseByType The type of page * @param browseByType The type of page
* @param context The context to match
* @param theme the theme to match * @param theme the theme to match
*/ */
export function getComponentByBrowseByType(browseByType, theme) { export function getComponentByBrowseByType(browseByType: BrowseByDataType, context: Context, theme: string): GenericConstructor<Component> {
let themeMap = map.get(browseByType); let contextMap: Map<Context, Map<string, GenericConstructor<Component>>> = map.get(browseByType);
if (hasNoValue(contextMap)) {
contextMap = map.get(DEFAULT_BROWSE_BY_TYPE);
}
let themeMap: Map<string, GenericConstructor<Component>> = contextMap.get(context);
if (hasNoValue(themeMap)) { if (hasNoValue(themeMap)) {
themeMap = map.get(DEFAULT_BROWSE_BY_TYPE); themeMap = contextMap.get(DEFAULT_BROWSE_BY_CONTEXT);
} }
const comp = resolveTheme(themeMap, theme); const comp = resolveTheme(themeMap, theme);
if (hasNoValue(comp)) { if (hasNoValue(comp)) {

View File

@@ -1 +0,0 @@
<ng-container *ngComponentOutlet="browseByComponent | async"></ng-container>

View File

@@ -1,13 +1,23 @@
import { BrowseBySwitcherComponent } from './browse-by-switcher.component'; import { BrowseBySwitcherComponent } from './browse-by-switcher.component';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { SimpleChange, Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router'; import { rendersBrowseBy } from './browse-by-decorator';
import { BROWSE_BY_COMPONENT_FACTORY, BrowseByDataType } from './browse-by-decorator';
import { BehaviorSubject } from 'rxjs';
import { ThemeService } from '../../shared/theme-support/theme.service'; import { ThemeService } from '../../shared/theme-support/theme.service';
import { FlatBrowseDefinition } from '../../core/shared/flat-browse-definition.model'; import { FlatBrowseDefinition } from '../../core/shared/flat-browse-definition.model';
import { ValueListBrowseDefinition } from '../../core/shared/value-list-browse-definition.model'; import { ValueListBrowseDefinition } from '../../core/shared/value-list-browse-definition.model';
import { NonHierarchicalBrowseDefinition } from '../../core/shared/non-hierarchical-browse-definition'; import { NonHierarchicalBrowseDefinition } from '../../core/shared/non-hierarchical-browse-definition';
import { getMockThemeService } from '../../shared/mocks/theme-service.mock';
import { DynamicComponentLoaderDirective } from '../../shared/abstract-component-loader/dynamic-component-loader.directive';
import { BrowseByDataType } from './browse-by-data-type';
@rendersBrowseBy('BrowseBySwitcherComponent' as BrowseByDataType)
@Component({
// eslint-disable-next-line @angular-eslint/component-selector
selector: '',
template: '<span id="BrowseByTestComponent"></span>',
})
class BrowseByTestComponent {
}
describe('BrowseBySwitcherComponent', () => { describe('BrowseBySwitcherComponent', () => {
let comp: BrowseBySwitcherComponent; let comp: BrowseBySwitcherComponent;
@@ -41,46 +51,45 @@ describe('BrowseBySwitcherComponent', () => {
), ),
]; ];
const data = new BehaviorSubject(createDataWithBrowseDefinition(new FlatBrowseDefinition()));
const activatedRouteStub = {
data
};
let themeService: ThemeService; let themeService: ThemeService;
let themeName: string; const themeName = 'dspace';
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
themeName = 'dspace'; themeService = getMockThemeService(themeName);
themeService = jasmine.createSpyObj('themeService', {
getThemeName: themeName,
});
TestBed.configureTestingModule({ void TestBed.configureTestingModule({
declarations: [BrowseBySwitcherComponent], declarations: [
providers: [ BrowseBySwitcherComponent,
{ provide: ActivatedRoute, useValue: activatedRouteStub }, DynamicComponentLoaderDirective,
{ provide: ThemeService, useValue: themeService }, ],
{ provide: BROWSE_BY_COMPONENT_FACTORY, useValue: jasmine.createSpy('getComponentByBrowseByType').and.returnValue(null) } providers: [
BrowseByTestComponent,
{ provide: ThemeService, useValue: themeService },
], ],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();
})); }));
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(BrowseBySwitcherComponent); fixture = TestBed.createComponent(BrowseBySwitcherComponent);
comp = fixture.componentInstance; comp = fixture.componentInstance;
spyOn(comp, 'getComponent').and.returnValue(BrowseByTestComponent);
spyOn(comp, 'connectInputsAndOutputs').and.callThrough();
})); }));
types.forEach((type: NonHierarchicalBrowseDefinition) => { types.forEach((type: NonHierarchicalBrowseDefinition) => {
describe(`when switching to a browse-by page for "${type.id}"`, () => { describe(`when switching to a browse-by page for "${type.id}"`, () => {
beforeEach(() => { beforeEach(async () => {
data.next(createDataWithBrowseDefinition(type)); comp.browseByType = type.dataType;
comp.ngOnChanges({
browseByType: new SimpleChange(undefined, type.dataType, true),
});
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
}); });
it(`should call getComponentByBrowseByType with type "${type.dataType}"`, () => { it(`should call getComponent with type "${type.dataType}"`, () => {
expect((comp as any).getComponentByBrowseByType).toHaveBeenCalledWith(type.dataType, themeName); expect(comp.getComponent).toHaveBeenCalled();
expect(comp.connectInputsAndOutputs).toHaveBeenCalled();
}); });
}); });
}); });

View File

@@ -1,38 +1,32 @@
import { Component, Inject, OnInit } from '@angular/core'; import { Component, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router'; import { getComponentByBrowseByType } from './browse-by-decorator';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BROWSE_BY_COMPONENT_FACTORY } from './browse-by-decorator';
import { GenericConstructor } from '../../core/shared/generic-constructor'; import { GenericConstructor } from '../../core/shared/generic-constructor';
import { BrowseDefinition } from '../../core/shared/browse-definition.model'; import { AbstractComponentLoaderComponent } from '../../shared/abstract-component-loader/abstract-component-loader.component';
import { ThemeService } from '../../shared/theme-support/theme.service'; import { BrowseByDataType } from './browse-by-data-type';
import { Context } from '../../core/shared/context.model';
@Component({ @Component({
selector: 'ds-browse-by-switcher', selector: 'ds-browse-by-switcher',
templateUrl: './browse-by-switcher.component.html' templateUrl: '../../shared/abstract-component-loader/abstract-component-loader.component.html'
}) })
/** export class BrowseBySwitcherComponent extends AbstractComponentLoaderComponent<Component> {
* Component for determining what Browse-By component to use depending on the metadata (browse ID) provided
*/
export class BrowseBySwitcherComponent implements OnInit {
/** @Input() context: Context;
* Resolved browse-by component
*/
browseByComponent: Observable<any>;
public constructor(protected route: ActivatedRoute, @Input() browseByType: BrowseByDataType;
protected themeService: ThemeService,
@Inject(BROWSE_BY_COMPONENT_FACTORY) private getComponentByBrowseByType: (browseByType, theme) => GenericConstructor<any>) {
}
/** protected inputNamesDependentForComponent: (keyof this & string)[] = [
* Fetch the correct browse-by component by using the relevant config from the route data 'context',
*/ 'browseByType',
ngOnInit(): void { ];
this.browseByComponent = this.route.data.pipe(
map((data: { browseDefinition: BrowseDefinition }) => this.getComponentByBrowseByType(data.browseDefinition.getRenderType(), this.themeService.getThemeName())) protected inputNames: (keyof this & string)[] = [
); 'context',
'browseByType',
];
public getComponent(): GenericConstructor<Component> {
return getComponentByBrowseByType(this.browseByType, this.context, this.themeService.getThemeName());
} }
} }

View File

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

View File

@@ -1,14 +1,14 @@
import { Component, OnInit, Inject, OnDestroy } from '@angular/core'; import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { VocabularyOptions } from '../../core/submission/vocabularies/models/vocabulary-options.model'; import { VocabularyOptions } from '../../core/submission/vocabularies/models/vocabulary-options.model';
import { VocabularyEntryDetail } from '../../core/submission/vocabularies/models/vocabulary-entry-detail.model'; import { VocabularyEntryDetail } from '../../core/submission/vocabularies/models/vocabulary-entry-detail.model';
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { Observable, Subscription } from 'rxjs'; import { Observable, Subscription } from 'rxjs';
import { BrowseDefinition } from '../../core/shared/browse-definition.model'; import { BrowseDefinition } from '../../core/shared/browse-definition.model';
import { GenericConstructor } from '../../core/shared/generic-constructor'; import { rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { BROWSE_BY_COMPONENT_FACTORY } from '../browse-by-switcher/browse-by-decorator';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { ThemeService } from 'src/app/shared/theme-support/theme.service';
import { HierarchicalBrowseDefinition } from '../../core/shared/hierarchical-browse-definition.model'; import { HierarchicalBrowseDefinition } from '../../core/shared/hierarchical-browse-definition.model';
import { BrowseByDataType } from '../browse-by-switcher/browse-by-data-type';
import { Context } from '../../core/shared/context.model';
@Component({ @Component({
selector: 'ds-browse-by-taxonomy-page', selector: 'ds-browse-by-taxonomy-page',
@@ -18,8 +18,19 @@ import { HierarchicalBrowseDefinition } from '../../core/shared/hierarchical-bro
/** /**
* Component for browsing items by metadata in a hierarchical controlled vocabulary * Component for browsing items by metadata in a hierarchical controlled vocabulary
*/ */
@rendersBrowseBy(BrowseByDataType.Hierarchy)
export class BrowseByTaxonomyPageComponent implements OnInit, OnDestroy { export class BrowseByTaxonomyPageComponent implements OnInit, OnDestroy {
/**
* The optional context
*/
@Input() context: Context;
/**
* The {@link BrowseByDataType} of this Component
*/
@Input() browseByType: BrowseByDataType;
/** /**
* The {@link VocabularyOptions} object * The {@link VocabularyOptions} object
*/ */
@@ -51,28 +62,27 @@ export class BrowseByTaxonomyPageComponent implements OnInit, OnDestroy {
queryParams: any; queryParams: any;
/** /**
* Resolved browse-by component * Resolved browse-by definition
*/ */
browseByComponent: Observable<any>; browseDefinition$: Observable<BrowseDefinition>;
/** /**
* Subscriptions to track * Subscriptions to track
*/ */
browseByComponentSubs: Subscription[] = []; subs: Subscription[] = [];
public constructor( protected route: ActivatedRoute, public constructor(
protected themeService: ThemeService, protected route: ActivatedRoute,
@Inject(BROWSE_BY_COMPONENT_FACTORY) private getComponentByBrowseByType: (browseByType, theme) => GenericConstructor<any>) { ) {
} }
ngOnInit(): void { ngOnInit(): void {
this.browseByComponent = this.route.data.pipe( this.browseDefinition$ = this.route.data.pipe(
map((data: { browseDefinition: BrowseDefinition }) => { map((data: { browseDefinition: BrowseDefinition }) => {
this.getComponentByBrowseByType(data.browseDefinition.getRenderType(), this.themeService.getThemeName());
return data.browseDefinition; return data.browseDefinition;
}) })
); );
this.browseByComponentSubs.push(this.browseByComponent.subscribe((browseDefinition: HierarchicalBrowseDefinition) => { this.subs.push(this.browseDefinition$.subscribe((browseDefinition: HierarchicalBrowseDefinition) => {
this.facetType = browseDefinition.facetType; this.facetType = browseDefinition.facetType;
this.vocabularyName = browseDefinition.vocabulary; this.vocabularyName = browseDefinition.vocabulary;
this.vocabularyOptions = { name: this.vocabularyName, closed: true }; this.vocabularyOptions = { name: this.vocabularyName, closed: true };
@@ -113,6 +123,6 @@ export class BrowseByTaxonomyPageComponent implements OnInit, OnDestroy {
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.browseByComponentSubs.forEach((sub: Subscription) => sub.unsubscribe()); this.subs.forEach((sub: Subscription) => sub.unsubscribe());
} }
} }

View File

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

View File

@@ -1,7 +1,6 @@
import { combineLatest as observableCombineLatest } from 'rxjs'; import { combineLatest as observableCombineLatest } from 'rxjs';
import { Component, Inject } from '@angular/core'; import { Component, Inject, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router'; import { ActivatedRoute, Params, Router } from '@angular/router';
import { hasValue } from '../../shared/empty.util';
import { import {
BrowseByMetadataPageComponent, BrowseByMetadataPageComponent,
browseParamsToOptions, getBrowseSearchOptions browseParamsToOptions, getBrowseSearchOptions
@@ -14,6 +13,8 @@ import { map } 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';
import { rendersBrowseBy } from '../browse-by-switcher/browse-by-decorator';
import { BrowseByDataType } from '../browse-by-switcher/browse-by-data-type';
@Component({ @Component({
selector: 'ds-browse-by-title-page', selector: 'ds-browse-by-title-page',
@@ -23,7 +24,8 @@ import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
/** /**
* Component for browsing items by title (dc.title) * Component for browsing items by title (dc.title)
*/ */
export class BrowseByTitlePageComponent extends BrowseByMetadataPageComponent { @rendersBrowseBy(BrowseByDataType.Title)
export class BrowseByTitlePageComponent extends BrowseByMetadataPageComponent implements OnInit {
public constructor(protected route: ActivatedRoute, public constructor(protected route: ActivatedRoute,
protected browseService: BrowseService, protected browseService: BrowseService,
@@ -57,8 +59,4 @@ export class BrowseByTitlePageComponent extends BrowseByMetadataPageComponent {
this.updateStartsWithTextOptions(); this.updateStartsWithTextOptions();
} }
ngOnDestroy(): void {
this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe());
}
} }

View File

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

View File

@@ -5,28 +5,22 @@ import { BrowseByMetadataPageComponent } from './browse-by-metadata-page/browse-
import { BrowseByDatePageComponent } from './browse-by-date-page/browse-by-date-page.component'; import { BrowseByDatePageComponent } from './browse-by-date-page/browse-by-date-page.component';
import { BrowseBySwitcherComponent } from './browse-by-switcher/browse-by-switcher.component'; import { BrowseBySwitcherComponent } from './browse-by-switcher/browse-by-switcher.component';
import { BrowseByTaxonomyPageComponent } from './browse-by-taxonomy-page/browse-by-taxonomy-page.component'; import { BrowseByTaxonomyPageComponent } from './browse-by-taxonomy-page/browse-by-taxonomy-page.component';
import { ThemedBrowseBySwitcherComponent } from './browse-by-switcher/themed-browse-by-switcher.component';
import { ComcolModule } from '../shared/comcol/comcol.module'; import { ComcolModule } from '../shared/comcol/comcol.module';
import { ThemedBrowseByMetadataPageComponent } from './browse-by-metadata-page/themed-browse-by-metadata-page.component';
import { ThemedBrowseByDatePageComponent } from './browse-by-date-page/themed-browse-by-date-page.component';
import { ThemedBrowseByTitlePageComponent } from './browse-by-title-page/themed-browse-by-title-page.component';
import { ThemedBrowseByTaxonomyPageComponent } from './browse-by-taxonomy-page/themed-browse-by-taxonomy-page.component';
import { SharedBrowseByModule } from '../shared/browse-by/shared-browse-by.module'; import { SharedBrowseByModule } from '../shared/browse-by/shared-browse-by.module';
import { DsoPageModule } from '../shared/dso-page/dso-page.module'; import { DsoPageModule } from '../shared/dso-page/dso-page.module';
import { FormModule } from '../shared/form/form.module'; import { FormModule } from '../shared/form/form.module';
import { SharedModule } from '../shared/shared.module'; import { SharedModule } from '../shared/shared.module';
const DECLARATIONS = [
BrowseBySwitcherComponent,
];
const ENTRY_COMPONENTS = [ const ENTRY_COMPONENTS = [
// put only entry components that use custom decorator // put only entry components that use custom decorator
BrowseByTitlePageComponent, BrowseByTitlePageComponent,
BrowseByMetadataPageComponent, BrowseByMetadataPageComponent,
BrowseByDatePageComponent, BrowseByDatePageComponent,
BrowseByTaxonomyPageComponent, BrowseByTaxonomyPageComponent,
ThemedBrowseByMetadataPageComponent,
ThemedBrowseByDatePageComponent,
ThemedBrowseByTitlePageComponent,
ThemedBrowseByTaxonomyPageComponent,
]; ];
@NgModule({ @NgModule({
@@ -39,12 +33,12 @@ const ENTRY_COMPONENTS = [
SharedModule, SharedModule,
], ],
declarations: [ declarations: [
BrowseBySwitcherComponent, ...DECLARATIONS,
ThemedBrowseBySwitcherComponent,
...ENTRY_COMPONENTS ...ENTRY_COMPONENTS
], ],
exports: [ exports: [
BrowseBySwitcherComponent ...DECLARATIONS,
...ENTRY_COMPONENTS,
] ]
}) })
export class BrowseByModule { export class BrowseByModule {

View File

@@ -6,7 +6,7 @@
<p>{{'collection.edit.item-mapper.description' | translate}}</p> <p>{{'collection.edit.item-mapper.description' | translate}}</p>
<ul ngbNav (navChange)="tabChange($event)" [destroyOnHide]="true" #tabs="ngbNav" class="nav-tabs"> <ul ngbNav (navChange)="tabChange($event)" [destroyOnHide]="true" #tabs="ngbNav" class="nav-tabs">
<li [ngbNavItem]="'browseTab'" role="presentation"> <li [ngbNavItem]="'browseTab'" role="presentation" data-test="browseTab">
<a ngbNavLink>{{'collection.edit.item-mapper.tabs.browse' | translate}}</a> <a ngbNavLink>{{'collection.edit.item-mapper.tabs.browse' | translate}}</a>
<ng-template ngbNavContent> <ng-template ngbNavContent>
<div class="mt-2"> <div class="mt-2">
@@ -23,7 +23,7 @@
</div> </div>
</ng-template> </ng-template>
</li> </li>
<li [ngbNavItem]="'mapTab'" role="presentation"> <li [ngbNavItem]="'mapTab'" role="presentation" data-test="mapTab">
<a ngbNavLink>{{'collection.edit.item-mapper.tabs.map' | translate}}</a> <a ngbNavLink>{{'collection.edit.item-mapper.tabs.map' | translate}}</a>
<ng-template ngbNavContent> <ng-template ngbNavContent>
<div class="row mt-2"> <div class="row mt-2">

View File

@@ -13,7 +13,7 @@
<!-- Collection logo --> <!-- Collection logo -->
<ds-comcol-page-logo *ngIf="logoRD$" <ds-comcol-page-logo *ngIf="logoRD$"
[logo]="(logoRD$ | async)?.payload" [logo]="(logoRD$ | async)?.payload"
[alternateText]="'Collection Logo'"> [alternateText]="'collection.logo' | translate">
</ds-comcol-page-logo> </ds-comcol-page-logo>
<!-- Handle --> <!-- Handle -->

View File

@@ -1,17 +1,17 @@
<div class="container-fluid mb-2" *ngVar="(itemTemplateRD$ | async) as itemTemplateRD"> <div class="container-fluid mb-2" *ngVar="(itemTemplateRD$ | async) as itemTemplateRD">
<label>{{ 'collection.edit.template.label' | translate}}</label> <span class="d-inline-block mb-2">{{ 'collection.edit.template.label' | translate}}</span>
<div class="button-row space-children-mr"> <div class="button-row space-children-mr">
<button *ngIf="!itemTemplateRD?.payload" class="btn btn-success" (click)="addItemTemplate()"> <button *ngIf="!itemTemplateRD?.payload" class="btn btn-success" (click)="addItemTemplate()">
<i class="fas fa-plus"></i> <i class="fas fa-plus" aria-hidden="true"></i>
<span class="d-none d-sm-inline">&nbsp;{{"collection.edit.template.add-button" | translate}}</span> <span class="d-none d-sm-inline">&nbsp;{{"collection.edit.template.add-button" | translate}}</span>
</button> </button>
<button *ngIf="itemTemplateRD?.payload" class="btn btn-danger" (click)="deleteItemTemplate()"> <button *ngIf="itemTemplateRD?.payload" class="btn btn-danger" (click)="deleteItemTemplate()">
<i class="fas fa-trash-alt"></i> <i class="fas fa-trash-alt" aria-hidden="true"></i>
<span class="d-none d-sm-inline">&nbsp;{{"collection.edit.template.delete-button" | translate}}</span> <span class="d-none d-sm-inline">&nbsp;{{"collection.edit.template.delete-button" | translate}}</span>
</button> </button>
<button *ngIf="itemTemplateRD?.payload" class="btn btn-primary" <button *ngIf="itemTemplateRD?.payload" class="btn btn-primary"
[routerLink]="'/collections/' + (dsoRD$ | async)?.payload.uuid + '/itemtemplate'"> [routerLink]="'/collections/' + (dsoRD$ | async)?.payload.uuid + '/itemtemplate'">
<i class="fas fa-edit"></i> <i class="fas fa-edit" aria-hidden="true"></i>
<span class="d-none d-sm-inline">&nbsp;{{"collection.edit.template.edit-button" | translate}}</span> <span class="d-none d-sm-inline">&nbsp;{{"collection.edit.template.edit-button" | translate}}</span>
</button> </button>
</div> </div>

View File

@@ -1,6 +1,6 @@
<div *ngVar="(contentSource$ |async) as contentSource"> <div *ngVar="(contentSource$ |async) as contentSource">
<div class="container-fluid space-children-mr" *ngIf="shouldShow"> <div class="container-fluid space-children-mr" *ngIf="shouldShow">
<h4>{{ 'collection.source.controls.head' | translate }}</h4> <h3>{{ 'collection.source.controls.head' | translate }}</h3>
<div> <div>
<span class="font-weight-bold">{{'collection.source.controls.harvest.status' | translate}}</span> <span class="font-weight-bold">{{'collection.source.controls.harvest.status' | translate}}</span>
<span>{{contentSource?.harvestStatus}}</span> <span>{{contentSource?.harvestStatus}}</span>

View File

@@ -26,7 +26,7 @@
for="externalSourceCheck">{{ 'collection.edit.tabs.source.external' | translate }}</label> for="externalSourceCheck">{{ 'collection.edit.tabs.source.external' | translate }}</label>
</div> </div>
<ds-themed-loading *ngIf="!contentSource" [message]="'loading.content-source' | translate"></ds-themed-loading> <ds-themed-loading *ngIf="!contentSource" [message]="'loading.content-source' | translate"></ds-themed-loading>
<h4 *ngIf="contentSource && (contentSource?.harvestType !== harvestTypeNone)">{{ 'collection.edit.tabs.source.form.head' | translate }}</h4> <h3 *ngIf="contentSource && (contentSource?.harvestType !== harvestTypeNone)">{{ 'collection.edit.tabs.source.form.head' | translate }}</h3>
</div> </div>
<div class="row"> <div class="row">
<ds-form *ngIf="formGroup && contentSource && (contentSource?.harvestType !== harvestTypeNone)" <ds-form *ngIf="formGroup && contentSource && (contentSource?.harvestType !== harvestTypeNone)"

View File

@@ -4,9 +4,9 @@
<cdk-tree-node *cdkTreeNodeDef="let node; when: isShowMore" cdkTreeNodePadding <cdk-tree-node *cdkTreeNodeDef="let node; when: isShowMore" cdkTreeNodePadding
class="example-tree-node show-more-node"> class="example-tree-node show-more-node">
<div class="btn-group"> <div class="btn-group">
<button type="button" class="btn btn-default" cdkTreeNodeToggle> <span aria-hidden="true" class="btn btn-default invisible" cdkTreeNodeToggle>
<span class="fa fa-chevron-right invisible" aria-hidden="true"></span> <span class="fa fa-chevron-right"></span>
</button> </span>
<div class="align-middle pt-2"> <div class="align-middle pt-2">
<button *ngIf="!(dataSource.loading$ | async)" (click)="getNextPage(node)" <button *ngIf="!(dataSource.loading$ | async)" (click)="getNextPage(node)"
class="btn btn-outline-primary btn-sm" role="button"> class="btn btn-outline-primary btn-sm" role="button">
@@ -24,20 +24,21 @@
<cdk-tree-node *cdkTreeNodeDef="let node; when: hasChild" cdkTreeNodePadding <cdk-tree-node *cdkTreeNodeDef="let node; when: hasChild" cdkTreeNodePadding
class="example-tree-node expandable-node"> class="example-tree-node expandable-node">
<div class="btn-group"> <div class="btn-group">
<button type="button" class="btn btn-default" cdkTreeNodeToggle <button *ngIf="hasChild(null, node) | async" type="button" class="btn btn-default" cdkTreeNodeToggle
[title]="'toggle ' + dsoNameService.getName(node.payload)" [attr.aria-label]="(node.isExpanded ? 'communityList.collapse' : 'communityList.expand') | translate:{ name: dsoNameService.getName(node.payload) }"
[attr.aria-label]="'toggle ' + dsoNameService.getName(node.payload)"
(click)="toggleExpanded(node)" (click)="toggleExpanded(node)"
[ngClass]="(hasChild(null, node)| async) ? 'visible' : 'invisible'" data-test="expand-button">
[attr.data-test]="(hasChild(null, node)| async) ? 'expand-button' : ''">
<span class="{{node.isExpanded ? 'fa fa-chevron-down' : 'fa fa-chevron-right'}}" <span class="{{node.isExpanded ? 'fa fa-chevron-down' : 'fa fa-chevron-right'}}"
aria-hidden="true"></span> aria-hidden="true"></span>
<span class="sr-only">{{ (node.isExpanded ? 'communityList.collapse' : 'communityList.expand') | translate:{ name: dsoNameService.getName(node.payload) } }}</span>
</button> </button>
<!--Don't render the button when non-expandable otherwise it's still accessible, instead render this placeholder-->
<span *ngIf="!(hasChild(null, node) | async)" aria-hidden="true" class="btn btn-default invisible">
<span class="fa fa-chevron-right"></span>
</span>
<div class="d-flex flex-row"> <div class="d-flex flex-row">
<span class="align-middle pt-2 lead"> <span class="align-middle pt-2 lead">
<a [routerLink]="node.route" class="lead"> <a [routerLink]="node.route" class="lead">{{ dsoNameService.getName(node.payload) }}</a>
{{ dsoNameService.getName(node.payload) }}
</a>
<span class="pr-2">&nbsp;</span> <span class="pr-2">&nbsp;</span>
<span *ngIf="node.payload.archivedItemsCount >= 0" class="badge badge-pill badge-secondary align-top archived-items-lead">{{node.payload.archivedItemsCount}}</span> <span *ngIf="node.payload.archivedItemsCount >= 0" class="badge badge-pill badge-secondary align-top archived-items-lead">{{node.payload.archivedItemsCount}}</span>
</span> </span>
@@ -46,10 +47,9 @@
<ds-truncatable [id]="node.id"> <ds-truncatable [id]="node.id">
<div class="text-muted" cdkTreeNodePadding> <div class="text-muted" cdkTreeNodePadding>
<div class="d-flex" *ngIf="node.payload.shortDescription"> <div class="d-flex" *ngIf="node.payload.shortDescription">
<button type="button" class="btn btn-default invisible"> <span aria-hidden="true" class="btn btn-default invisible">
<span class="{{node.isExpanded ? 'fa fa-chevron-down' : 'fa fa-chevron-right'}}" <span class="fa fa-chevron-right"></span>
aria-hidden="true"></span> </span>
</button>
<ds-truncatable-part [id]="node.id" [minLines]="3"> <ds-truncatable-part [id]="node.id" [minLines]="3">
<span>{{node.payload.shortDescription}}</span> <span>{{node.payload.shortDescription}}</span>
</ds-truncatable-part> </ds-truncatable-part>
@@ -58,10 +58,9 @@
</ds-truncatable> </ds-truncatable>
<div class="d-flex" *ngIf="node===loadingNode && dataSource.loading$ | async" <div class="d-flex" *ngIf="node===loadingNode && dataSource.loading$ | async"
cdkTreeNodePadding> cdkTreeNodePadding>
<button type="button" class="btn btn-default invisible"> <span aria-hidden="true" class="btn btn-default invisible">
<span class="{{node.isExpanded ? 'fa fa-chevron-down' : 'fa fa-chevron-right'}}" <span class="fa fa-chevron-right"></span>
aria-hidden="true"></span> </span>
</button>
<ds-themed-loading class="ds-themed-loading"></ds-themed-loading> <ds-themed-loading class="ds-themed-loading"></ds-themed-loading>
</div> </div>
</cdk-tree-node> </cdk-tree-node>
@@ -69,22 +68,19 @@
<cdk-tree-node *cdkTreeNodeDef="let node; when: !(hasChild && isShowMore)" cdkTreeNodePadding <cdk-tree-node *cdkTreeNodeDef="let node; when: !(hasChild && isShowMore)" cdkTreeNodePadding
class="example-tree-node childless-node"> class="example-tree-node childless-node">
<div class="btn-group"> <div class="btn-group">
<button type="button" class="btn btn-default" cdkTreeNodeToggle> <span aria-hidden="true" class="btn btn-default invisible" cdkTreeNodeToggle>
<span class="fa fa-chevron-right invisible" aria-hidden="true"></span> <span class="fa fa-chevron-right"></span>
</button> </span>
<h6 class="align-middle pt-2"> <h6 class="align-middle pt-2">
<a [routerLink]="node.route" class="lead"> <a [routerLink]="node.route" class="lead">{{ dsoNameService.getName(node.payload) }}</a>
{{ dsoNameService.getName(node.payload) }}
</a>
</h6> </h6>
</div> </div>
<ds-truncatable [id]="node.id"> <ds-truncatable [id]="node.id">
<div class="text-muted" cdkTreeNodePadding> <div class="text-muted" cdkTreeNodePadding>
<div class="d-flex" *ngIf="node.payload.shortDescription"> <div class="d-flex" *ngIf="node.payload.shortDescription">
<button type="button" class="btn btn-default invisible"> <span aria-hidden="true" class="btn btn-default invisible">
<span class="{{node.isExpanded ? 'fa fa-chevron-down' : 'fa fa-chevron-right'}}" <span class="fa fa-chevron-right"></span>
aria-hidden="true"></span> </span>
</button>
<ds-truncatable-part [id]="node.id" [minLines]="3"> <ds-truncatable-part [id]="node.id" [minLines]="3">
<span>{{node.payload.shortDescription}}</span> <span>{{node.payload.shortDescription}}</span>
</ds-truncatable-part> </ds-truncatable-part>

View File

@@ -0,0 +1,4 @@
::ng-deep .fa-chevron-right::before {
display: block;
width: 16px;
}

View File

@@ -5,7 +5,7 @@ import { CommunityListService, showMoreFlatNode, toFlatNode } from '../community
import { CdkTreeModule } from '@angular/cdk/tree'; import { CdkTreeModule } from '@angular/cdk/tree';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock'; import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA, DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing'; import { RouterTestingModule } from '@angular/router/testing';
import { Community } from '../../core/shared/community.model'; import { Community } from '../../core/shared/community.model';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
@@ -300,12 +300,14 @@ describe('CommunityListComponent', () => {
describe('second top community node is expanded and has more children (collections) than page size of collection', () => { describe('second top community node is expanded and has more children (collections) than page size of collection', () => {
describe('children of second top com are added (page-limited pageSize 2)', () => { describe('children of second top com are added (page-limited pageSize 2)', () => {
let allNodes; let allNodes: DebugElement[];
beforeEach(fakeAsync(() => { beforeEach(fakeAsync(() => {
const chevronExpand = fixture.debugElement.queryAll(By.css('.expandable-node button')); const toggleButtons: DebugElement[] = fixture.debugElement.queryAll(By.css('.expandable-node button'));
const chevronExpandSpan = fixture.debugElement.queryAll(By.css('.expandable-node button span')); const toggleButtonText: DebugElement = toggleButtons[1].query(By.css('span'));
if (chevronExpandSpan[1].nativeElement.classList.contains('fa-chevron-right')) { expect(toggleButtonText).not.toBeNull();
chevronExpand[1].nativeElement.click();
if (toggleButtonText.nativeElement.classList.contains('fa-chevron-right')) {
toggleButtons[1].nativeElement.click();
tick(); tick();
fixture.detectChanges(); fixture.detectChanges();
} }
@@ -315,17 +317,18 @@ describe('CommunityListComponent', () => {
allNodes = [...expandableNodesFound, ...childlessNodesFound]; allNodes = [...expandableNodesFound, ...childlessNodesFound];
})); }));
it('tree contains 2 (page-limited) top com, 2 (page-limited) coll of 2nd top com, a show more for those page-limited coll and show more for page-limited top com', () => { it('tree contains 2 (page-limited) top com, 2 (page-limited) coll of 2nd top com, a show more for those page-limited coll and show more for page-limited top com', () => {
mockTopFlatnodesUnexpanded.slice(0, 2).map((topFlatnode: FlatNode) => { const allNodeNames: string[] = allNodes.map((node: DebugElement) => node.nativeElement.innerText.trim());
expect(allNodes.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === topFlatnode.name);
})).toBeTruthy();
});
mockCollectionsPage1.map((coll) => {
expect(allNodes.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === coll.name);
})).toBeTruthy();
});
expect(allNodes.length).toEqual(4); expect(allNodes.length).toEqual(4);
const flatNodes: string[] = mockTopFlatnodesUnexpanded.slice(0, 2).map((flatNode: FlatNode) => flatNode.name);
for (const flatNode of flatNodes) {
expect(allNodeNames).toContain(flatNode);
}
expect(flatNodes.length).toBe(2);
const page1CollectionNames: string[] = mockCollectionsPage1.map((collection: Collection) => collection.name);
for (const collectionName of page1CollectionNames) {
expect(allNodeNames).toContain(collectionName);
}
expect(page1CollectionNames.length).toBe(2);
const showMoreEl = fixture.debugElement.queryAll(By.css('.show-more-node')); const showMoreEl = fixture.debugElement.queryAll(By.css('.show-more-node'));
expect(showMoreEl.length).toEqual(2); expect(showMoreEl.length).toEqual(2);
}); });

View File

@@ -19,6 +19,7 @@ import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
@Component({ @Component({
selector: 'ds-community-list', selector: 'ds-community-list',
templateUrl: './community-list.component.html', templateUrl: './community-list.component.html',
styleUrls: ['./community-list.component.scss'],
}) })
export class CommunityListComponent implements OnInit, OnDestroy { export class CommunityListComponent implements OnInit, OnDestroy {

View File

@@ -7,7 +7,7 @@
<!-- Community name --> <!-- Community name -->
<ds-comcol-page-header [name]="dsoNameService.getName(communityPayload)"></ds-comcol-page-header> <ds-comcol-page-header [name]="dsoNameService.getName(communityPayload)"></ds-comcol-page-header>
<!-- Community logo --> <!-- Community logo -->
<ds-comcol-page-logo *ngIf="logoRD$" [logo]="(logoRD$ | async)?.payload" [alternateText]="'Community Logo'"> <ds-comcol-page-logo *ngIf="logoRD$" [logo]="(logoRD$ | async)?.payload" [alternateText]="'community.logo' | translate">
</ds-comcol-page-logo> </ds-comcol-page-logo>
<!-- Handle --> <!-- Handle -->
<ds-themed-comcol-page-handle [content]="communityPayload.handle" [title]="'community.page.handle'"> <ds-themed-comcol-page-handle [content]="communityPayload.handle" [title]="'community.page.handle'">

View File

@@ -7,11 +7,11 @@
<div class="form-group row"> <div class="form-group row">
<div class="col text-right space-children-mr"> <div class="col text-right space-children-mr">
<button class="btn btn-outline-secondary" (click)="onCancel(dso)" [disabled]="(processing$ | async)"> <button class="btn btn-outline-secondary" (click)="onCancel(dso)" [disabled]="(processing$ | async)">
<i class="fas fa-times"></i> {{'community.delete.cancel' | translate}} <i class="fas fa-times" aria-hidden="true"></i> {{'community.delete.cancel' | translate}}
</button> </button>
<button class="btn btn-danger" (click)="onConfirm(dso)" [disabled]="(processing$ | async)"> <button class="btn btn-danger" (click)="onConfirm(dso)" [disabled]="(processing$ | async)">
<span *ngIf="processing$ | async"><i class='fas fa-circle-notch fa-spin'></i> {{'community.delete.processing' | translate}}</span> <span *ngIf="processing$ | async"><i class='fas fa-circle-notch fa-spin' aria-hidden="true"></i> {{'community.delete.processing' | translate}}</span>
<span *ngIf="!(processing$ | async)"><i class="fas fa-trash"></i> {{'community.delete.confirm' | translate}}</span> <span *ngIf="!(processing$ | async)"><i class="fas fa-trash" aria-hidden="true"></i> {{'community.delete.confirm' | translate}}</span>
</button> </button>
</div> </div>
</div> </div>

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