Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
@if (type === 'subject') {
<span class="pe-1">
@for (subject of mdValue.value.split(separator); track subject) {
<a class="badge text-bg-info text-white cursor-pointer me-1"
<a class="badge text-wrap text-start text-bg-info text-white cursor-pointer me-1"
[href]="getLinkToSearch(-1, subject)">
{{subject}}
</a>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
</dd>
<dt>{{'item.file.description.description' | translate}}</dt>
<dd>
{{ fileInput.description }}
{{ (fileInput.description) || ('item.file.description.na' | translate) }}
</dd>
<dt>{{'item.file.description.checksum' | translate}}</dt>
<dd>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,29 @@ describe('FileDescriptionComponent', () => {
expect(fileNameElement.textContent).toContain('testFile');
});

describe('the file description', () => {
const descriptionValue = (): HTMLElement => {
const descDt = fixture.debugElement.queryAll(By.css('.file-content dt'))
.find((de) => (de.nativeElement as HTMLElement).textContent?.includes('item.file.description.description'));
expect(descDt).toBeTruthy();
return (descDt.nativeElement as HTMLElement).nextElementSibling as HTMLElement;
};

it('shows the fallback translation key when the description is empty', () => {
component.fileInput.description = '';
fixture.detectChanges();

expect(descriptionValue().textContent).toContain('item.file.description.na');
});

it('shows the description text when the description is present', () => {
component.fileInput.description = 'This is a test description';
fixture.detectChanges();

expect(descriptionValue().textContent).toContain('This is a test description');
});
});

describe('the download control', () => {
const downloadButton = (): HTMLElement => fixture.nativeElement.querySelector('a.download-btn');
const downloadRoute = (): string[] => ['bitstreams', component.fileInput.id, 'download'];
Expand Down
166 changes: 163 additions & 3 deletions src/app/static-page/static-page.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,32 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import {
Router,
RouterModule,
} from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { of } from 'rxjs';
import {
Observable,
of,
throwError,
} from 'rxjs';

import { APP_CONFIG } from '../../config/app-config.interface';
import { environment } from '../../environments/environment';
import { ConfigurationDataService } from '../core/data/configuration-data.service';
import { RemoteData } from '../core/data/remote-data';
import { ServerResponseService } from '../core/services/server-response.service';
import { ConfigurationProperty } from '../core/shared/configuration-property.model';
import { HtmlContentService } from '../shared/html-content.service';
import { ThemedLoadingComponent } from '../shared/loading/themed-loading.component';
import { RouterMock } from '../shared/mocks/router.mock';
import {
createFailedRemoteDataObject$,
createSuccessfulRemoteDataObject$,
} from '../shared/remote-data.utils';
import { StaticPageComponent } from './static-page.component';

describe('StaticPageComponent', () => {
Expand All @@ -31,12 +45,21 @@ describe('StaticPageComponent', () => {
restBase?: string,
contentPromise?: Promise<string | undefined>,
route = '/static/test-file.html',
configProperties: { [name: string]: string[] } = {},
) {
const htmlContentService = jasmine.createSpyObj('htmlContentService', {
fetchHtmlContent: of(html),
getHmtlContentByPathAndLocale: contentPromise ?? Promise.resolve(html),
});

// Unknown properties fail with 404, like a property the backend doesn't expose
const configurationService = jasmine.createSpyObj('configurationService', ['findByPropertyName']);
configurationService.findByPropertyName.and.callFake((name: string): Observable<RemoteData<ConfigurationProperty>> =>
Object.prototype.hasOwnProperty.call(configProperties, name)
? createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), { name, values: configProperties[name] }))
: createFailedRemoteDataObject$('No such configuration property', 404),
);

const responseService = jasmine.createSpyObj('responseService', {
setNotFound: null,
});
Expand Down Expand Up @@ -65,6 +88,7 @@ describe('StaticPageComponent', () => {
{ provide: HtmlContentService, useValue: htmlContentService },
{ provide: Router, useValue: router },
{ provide: ServerResponseService, useValue: responseService },
{ provide: ConfigurationDataService, useValue: configurationService },
{ provide: APP_CONFIG, useValue: appConfig },
],
})
Expand All @@ -80,7 +104,7 @@ describe('StaticPageComponent', () => {

const fixture = TestBed.createComponent(StaticPageComponent);
const component = fixture.componentInstance;
return { fixture, component, htmlContentService, responseService };
return { fixture, component, htmlContentService, responseService, configurationService };
}

function createLinkEvent(href: string, useNestedTarget = false): Event {
Expand Down Expand Up @@ -180,6 +204,142 @@ describe('StaticPageComponent', () => {
expect(component.htmlContent.value).toBe(otherHtml);
});

describe('variable interpolation', () => {
const allPlaceholdersHtml = '<p>Welcome to ${dspace.name}, provided by ${description.institution}, ' +
'located at ${description.location}.</p><p>Laws of ${description.country}, court of ${description.city}.</p>';
const allProperties = {
'dspace.name': ['Test Repository'],
'description.institution': ['Test Institute'],
'description.location': ['Test Street 1', '100 00 Test City'],
'description.city': ['Test City'],
'description.country': ['Test Country'],
};

function setupInterpolationTest(html: string, configProperties: { [name: string]: string[] } = {}, restBase?: string) {
return setupTest(html, restBase, undefined, '/static/test-file.html', configProperties);
}

async function render(fixture: ComponentFixture<StaticPageComponent>) {
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
}

let warnSpy: jasmine.Spy;

beforeEach(() => {
warnSpy = spyOn(console, 'warn');
});

it('should replace all placeholders with backend configuration properties', async () => {
const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe('<p>Welcome to Test Repository, provided by Test Institute, ' +
'located at Test Street 1, 100 00 Test City.</p><p>Laws of Test Country, court of Test City.</p>');
expect(warnSpy).not.toHaveBeenCalled();
});

it('should join a value the backend split on commas', async () => {
// How the backend returns `dspace.name = A (B), C, D`
const { fixture, component } = await setupInterpolationTest('<p>${dspace.name}</p>', {
'dspace.name': ['Test digital library at the Test Institute (TI)', 'Test Faculty', 'Test University'],
});
await render(fixture);

expect(component.htmlContent.value).toBe('<p>Test digital library at the Test Institute (TI), Test Faculty, Test University</p>');
});

it('should request each property once', async () => {
const { fixture, configurationService } = await setupInterpolationTest('<p>${dspace.name} ${dspace.name} ${description.city}</p>', allProperties);
await render(fixture);

expect(configurationService.findByPropertyName).toHaveBeenCalledTimes(2);
expect(configurationService.findByPropertyName).toHaveBeenCalledWith('dspace.name');
expect(configurationService.findByPropertyName).toHaveBeenCalledWith('description.city');
});

it('should not request any property when the page has no placeholders', async () => {
const html = '<p>No placeholders here</p>';
const { fixture, component, configurationService } = await setupInterpolationTest(html, allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe(html);
expect(configurationService.findByPropertyName).not.toHaveBeenCalled();
expect(warnSpy).not.toHaveBeenCalled();
});

it('should leave an unknown or unexposed placeholder literal and warn once', async () => {
const { fixture, component } = await setupInterpolationTest('<p>${dspace.name} ${foo.bar}</p>', allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe('<p>Test Repository ${foo.bar}</p>');
expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['foo.bar']);
});

it('should treat an empty value as missing', async () => {
const { fixture, component } = await setupInterpolationTest('<p>${dspace.name} ${description.city}</p>',
{ 'dspace.name': [''], 'description.city': [] });
await render(fixture);

expect(component.htmlContent.value).toBe('<p>${dspace.name} ${description.city}</p>');
expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name', 'description.city']);
});

it('should still show the page when a property request errors', async () => {
const { fixture, component, configurationService, responseService } = await setupInterpolationTest('<p>${dspace.name}</p>');
configurationService.findByPropertyName.and.returnValue(throwError(() => new Error('backend down')));
await render(fixture);

expect(component.contentState).toBe('found');
expect(component.htmlContent.value).toBe('<p>${dspace.name}</p>');
expect(responseService.setNotFound).not.toHaveBeenCalled();
expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']);
});

it('should HTML-escape values', async () => {
const { fixture, component } = await setupInterpolationTest('<p id="target">${dspace.name}</p>', { 'dspace.name': ['A & <b>B</b>'] });
await render(fixture);

expect(component.htmlContent.value).toBe('<p id="target">A &amp; &lt;b&gt;B&lt;/b&gt;</p>');
const target = fixture.nativeElement.querySelector('#target');
expect(target.querySelector('b')).toBeNull();
expect(target.textContent).toBe('A & <b>B</b>');
});

it('should insert values containing replacement patterns literally', async () => {
const { fixture, component } = await setupInterpolationTest(
'<p id="target">${dspace.name}|${description.city}</p>',
{ 'dspace.name': ['a$&b'], 'description.city': ['c$1$`$\'d'] },
);
await render(fixture);

expect(fixture.nativeElement.querySelector('#target').textContent).toBe('a$&b|c$1$`$\'d');
expect(component.htmlContent.value).not.toContain('${');
});

it('should not touch other placeholder syntaxes', async () => {
const html = '<p>$dspace.name {{\'x\' | translate}} $ {dspace.name}</p>';
const { fixture, component, configurationService } = await setupInterpolationTest(html, allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe(html);
expect(configurationService.findByPropertyName).not.toHaveBeenCalled();
});

it('should apply both the OAI link rewrite and variable interpolation', async () => {
const { fixture, component } = await setupInterpolationTest(
'<a href="/server/oai/request?verb=Identify">${dspace.name}</a>',
allProperties,
'https://api.example.org/repository/server',
);
await render(fixture);

expect(component.htmlContent.value)
.toBe('<a href="https://api.example.org/repository/server/oai/request?verb=Identify">Test Repository</a>');
});
});

describe('contentState behavior', () => {
it('should initialize contentState to "loading"', async () => {
const { component } = await setupTest('<div>test</div>');
Expand Down
52 changes: 51 additions & 1 deletion src/app/static-page/static-page.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@ import {
RouterModule,
} from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { BehaviorSubject } from 'rxjs';
import escapeHtml from 'lodash/escape';
import {
BehaviorSubject,
firstValueFrom,
} from 'rxjs';

import {
APP_CONFIG,
AppConfig,
} from '../../config/app-config.interface';
import { ConfigurationDataService } from '../core/data/configuration-data.service';
import { ServerResponseService } from '../core/services/server-response.service';
import { getFirstCompletedRemoteData } from '../core/shared/operators';
import { isEmpty } from '../shared/empty.util';
import { HtmlContentService } from '../shared/html-content.service';
import { ThemedLoadingComponent } from '../shared/loading/themed-loading.component';
Expand Down Expand Up @@ -48,6 +54,7 @@ export class StaticPageComponent implements OnInit {
private router: Router,
private responseService: ServerResponseService,
private changeDetector: ChangeDetectorRef,
private configurationService: ConfigurationDataService,
@Inject(APP_CONFIG) protected appConfig?: AppConfig) { }

async ngOnInit(): Promise<void> {
Expand All @@ -63,6 +70,7 @@ export class StaticPageComponent implements OnInit {
const restBase = this.appConfig?.rest?.baseUrl;
const oaiUrl = restBase ? restBase.replace(/\/+$/, '') + '/oai' : '/server/oai';
htmlContent = htmlContent.replace(/href="\/server\/oai/gi, 'href="' + oaiUrl);
htmlContent = await this.interpolateVariables(htmlContent);

this.htmlContent.next(htmlContent);
this.contentState = 'found';
Expand Down Expand Up @@ -108,6 +116,48 @@ export class StaticPageComponent implements OnInit {
this.redirectToRelativeLink(staticPageBaseUrl, href);
}

/**
* Replace `${key}` placeholders with the value of the backend configuration property `key`, e.g. `${dspace.name}`.
* The property must be listed in `rest.properties.exposed` on the backend.
* Values are HTML-escaped. A property that is not exposed, not set, empty, or fails to load leaves the placeholder unchanged.
* @param html static page content
* @private
*/
private async interpolateVariables(html: string): Promise<string> {
const keys = [...new Set((html.match(/\$\{[\w.-]+\}/g) ?? []).map((placeholder) => placeholder.slice(2, -1)))];
if (keys.length === 0) {
return html;
}
const loaded = await Promise.all(keys.map((key) => this.getConfigValue(key)));
const values = new Map(keys.map((key, i) => [key, loaded[i]]));
const missing = keys.filter((key) => values.get(key) === undefined);
if (missing.length > 0) {
console.warn('Static page: unresolved variables', missing);
}
// Function replacer: `$&`, `$'` etc. in values are inserted literally, not as replacement patterns.
return html.replace(/\$\{([\w.-]+)\}/g, (match: string, key: string) => {
const value = values.get(key);
return value === undefined ? match : escapeHtml(value);
});
}

/**
* Load a configuration property from the backend.
* @param key property name
* @returns the property value, or `undefined` if it is missing, empty, or fails to load
* @private
*/
private async getConfigValue(key: string): Promise<string | undefined> {
try {
const response = await firstValueFrom(this.configurationService.findByPropertyName(key).pipe(getFirstCompletedRemoteData()));
// The backend splits a value on commas into several values; join them back.
const value = response.hasSucceeded ? response.payload?.values?.join(', ').trim() : undefined;
return isEmpty(value) ? undefined : value;
} catch (error) {
return undefined;
}
}

private getNamespacePrefix(): string {
const nameSpace = this.appConfig?.ui?.nameSpace ?? '/';
return nameSpace === '/' ? '' : nameSpace.replace(/\/$/, '');
Expand Down
7 changes: 5 additions & 2 deletions src/assets/i18n/cs.json5
Original file line number Diff line number Diff line change
Expand Up @@ -5099,6 +5099,9 @@
// "item.file.description.description": "Description",
"item.file.description.description": "Popis",

// "item.file.description.na": "N/A",
"item.file.description.na": "Neuvedeno",

// "item.file.description.download.file": "Download file",
"item.file.description.download.file": "Stáhnout soubor",

Expand Down Expand Up @@ -10000,8 +10003,8 @@
// "submission.sections.upload.header.policy.default.withlist": "Please note that uploaded files in the {{collectionName}} collection will be accessible, in addition to what is explicitly decided for the single file, with the following group(s):",
"submission.sections.upload.header.policy.default.withlist": "Vezměte prosím na vědomí, že nahrané soubory v kolekci {{collectionName}} budou kromě toho, co je explicitně rozhodnuto pro jednotlivý soubor, přístupné podle následujících skupin:",

// "submission.sections.upload.info": "Here you will find all the files currently in the item. You can update the file metadata and access conditions or <strong>upload additional files by dragging & dropping them anywhere on the page.</strong>",
"submission.sections.upload.info": "Zde najdete všechny soubory, které jsou aktuálně v záznamu. Můžete aktualizovat metadata souborů a podmínky přístupu nebo <strong>nahrát další soubory pouhým přetažením kdekoli na stránku</strong>.",
// "submission.sections.upload.info": "Here you will find all the files currently in the item. You can update the file metadata and access conditions or <strong>upload additional files by dragging & dropping them anywhere on the page.</strong><br/>When uploading language resources, please try to use one of the recommended formats mentioned in the <a class=\"link-contrast\" href=\"https://standards.clarin.eu/sis/views/view-centre.xq?id=LINDAT\" target=\"_blank\" rel=\"noopener noreferrer\">CLARIN Standards Information System</a>.",
"submission.sections.upload.info": "Zde najdete všechny soubory, které jsou aktuálně v záznamu. Můžete aktualizovat metadata souborů a podmínky přístupu nebo <strong>nahrát další soubory pouhým přetažením kdekoli na stránku</strong>.<br/>Při nahrávání jazykových zdrojů zkuste prosím použít některý z doporučených formátů, uvedených v <a class=\"link-contrast\" href=\"https://standards.clarin.eu/sis/views/view-centre.xq?id=LINDAT\" target=\"_blank\" rel=\"noopener noreferrer\">CLARIN Standards Information System</a>.",

// "submission.sections.upload.no-entry": "No",
"submission.sections.upload.no-entry": "Ne",
Expand Down
Loading
Loading