Skip to content
6 changes: 3 additions & 3 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,13 @@ jobs:
sleep 10
docker container ls
# Verify production frontend started successfully.
# 1. Make sure /home path has "DSpace software" (this is in the footer of the page)
# 1. Make sure /home path has "DSpace software" (this is in the footer of the page; without double quotes)
# 2. Also check /community-list page lists one of the test Communities in the loaded test data
- name: Verify production frontend is responding properly
run: |
result=$(wget -O- -q http://127.0.0.1:4000/home)
echo "$result"
echo "$result" | grep -oE "\"DSpace software\""
echo "$result" | grep -oE "DSpace software"
- name: Error logs of production frontend (if error in startup)
if: ${{ failure() }}
run: |
Expand Down Expand Up @@ -196,4 +196,4 @@ jobs:
# Shutdown our containers
- name: Shutdown running Docker containers
run: |
docker compose -f docker/docker-compose.yml -f docker/docker-compose-rest.yml down
docker compose -f docker/docker-compose.yml -f docker/docker-compose-rest.yml down
6 changes: 3 additions & 3 deletions src/modules/app/browser-app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ import { BrowserInitService } from './browser-init.service';

export const REQ_KEY = makeStateKey<string>('req');

export function createTranslateLoader(transferState: TransferState, http: HttpClient) {
return new TranslateBrowserLoader(transferState, http, 'assets/i18n/', '.json');
export function createTranslateLoader(http: HttpClient) {
return new TranslateBrowserLoader(http, 'assets/i18n/', '.json');
}

export function getRequest(transferState: TransferState): any {
Expand All @@ -98,7 +98,7 @@ export const browserAppConfig: ApplicationConfig = mergeApplicationConfig({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [TransferState, HttpClient],
deps: [HttpClient],
},
missingTranslationHandler: provideMissingTranslationHandler(MissingTranslationHelper),
}),
Expand Down
36 changes: 34 additions & 2 deletions src/modules/app/browser-init.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ import {
filter,
find,
map,
switchMap,
timeout,
} from 'rxjs/operators';

import { logStartupMessage } from '../../../startup-message';
Expand All @@ -59,6 +61,11 @@ import { MatomoService } from '../../app/statistics/matomo.service';
import { StoreAction } from '../../app/store.actions';
import { environment } from '../../environments/environment';

/**
* Maximum time (in ms) the client-side initialization waits for the i18n messages of the current language
*/
const TRANSLATIONS_TIMEOUT_MS = 5000;

/**
* Performs client-side initialization.
*/
Expand Down Expand Up @@ -125,6 +132,7 @@ export class BrowserInitService extends InitService {
logStartupMessage(environment);

this.initI18n();
const translationsLoaded = this.loadTranslations();
this.initAngulartics();
this.initGoogleAnalytics();
this.initMatomo();
Expand All @@ -134,7 +142,10 @@ export class BrowserInitService extends InitService {

this.initOrejime();

await lastValueFrom(this.authenticationReady$());
await Promise.all([
lastValueFrom(this.authenticationReady$()),
translationsLoaded,
]);
this.menuProviderService.initPersistentMenus(false);

return true;
Expand Down Expand Up @@ -165,6 +176,28 @@ export class BrowserInitService extends InitService {
}
}

/**
* Wait until the i18n messages for the current language are loaded, so they're available when the app is rendered
* client side. Otherwise, the translated texts of the server-side rendered page would be briefly replaced by their
* message keys. The download itself usually started earlier, from the preload link added during SSR.
*
* Resolves after {@link TRANSLATIONS_TIMEOUT_MS} at the latest, so the app is never blocked by a hanging request
* (e.g. to determine the language of the authenticated user, or to download the messages). In that case, the messages
* are applied as soon as they're loaded.
* @private
*/
private async loadTranslations(): Promise<void> {
try {
await firstValueFrom(this.localeService.getCurrentLanguageCode().pipe(
switchMap((lang: string) => this.translate.use(lang)),
timeout(TRANSLATIONS_TIMEOUT_MS),
));
} catch (e) {
// don't block the app if the translation message catalog can't be loaded
console.error('Failed to load translation message catalog', e);
}
}

private trackAuthTokenExpiration(): void {
this.authService.trackTokenExpiration();
}
Expand Down Expand Up @@ -242,5 +275,4 @@ export class BrowserInitService extends InitService {
this.rootDataService.invalidateRootCache();
});
}

}
8 changes: 4 additions & 4 deletions src/modules/app/server-app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import {
import {
APP_ID,
ApplicationConfig,
DOCUMENT,
importProvidersFrom,
mergeApplicationConfig,
TransferState,
} from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideServerRendering } from '@angular/ssr';
Expand Down Expand Up @@ -64,8 +64,8 @@ import { SubmissionService } from '../../app/submission/submission.service';
import { TranslateServerLoader } from '../../ngx-translate-loaders/translate-server.loader';
import { ServerInitService } from './server-init.service';

export function createTranslateLoader(transferState: TransferState) {
return new TranslateServerLoader(transferState, 'dist/server/assets/i18n/', '.json');
export function createTranslateLoader(document: Document) {
return new TranslateServerLoader(document, 'dist/server/assets/i18n/', '.json');
}

export const serverAppConfig: ApplicationConfig = mergeApplicationConfig({
Expand All @@ -81,7 +81,7 @@ export const serverAppConfig: ApplicationConfig = mergeApplicationConfig({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [TransferState],
deps: [DOCUMENT],
},
}),
...ServerInitService.providers(),
Expand Down
15 changes: 0 additions & 15 deletions src/ngx-translate-loaders/ngx-translate-state.ts

This file was deleted.

37 changes: 7 additions & 30 deletions src/ngx-translate-loaders/translate-browser.loader.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,29 @@
import { HttpClient } from '@angular/common/http';
import { TransferState } from '@angular/core';
import { hasValue } from '@dspace/shared/utils/empty.util';
import { TranslateLoader } from '@ngx-translate/core';
import {
Observable,
of,
} from 'rxjs';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { environment } from '../environments/environment';
import {
NGX_TRANSLATE_STATE,
NgxTranslateState,
} from './ngx-translate-state';
import { getTranslationFileName } from './translation-file-name';

/**
* A TranslateLoader for ngx-translate to retrieve i18n messages from the TransferState, or download
* them if they're not available there
* A TranslateLoader for ngx-translate to retrieve i18n messages using HttpClient
*/
export class TranslateBrowserLoader implements TranslateLoader {
constructor(
protected transferState: TransferState,
protected http: HttpClient,
protected prefix?: string,
protected suffix?: string,
) {
}

/**
* Return the i18n messages for a given language, first try to find them in the TransferState
* retrieve them using HttpClient if they're not available there
* Return the i18n messages for a given language
*
* @param lang the language code
*/
getTranslation(lang: string): Observable<any> {
// Get the ngx-translate messages from the transfer state, to speed up the initial page load
// client side
const state = this.transferState.get<NgxTranslateState>(NGX_TRANSLATE_STATE, {});
const messages = state[lang];
if (hasValue(messages)) {
return of(messages);
} else {
const translationHash: string = environment.production ? `.${(process.env.languageHashes as any)[lang + '.json5']}` : '';
// If they're not available on the transfer state (e.g. when running in dev mode), retrieve
// them using HttpClient
return this.http.get(`${this.prefix}${lang}${translationHash}${this.suffix}`, { responseType: 'text' }).pipe(
map((json: any) => JSON.parse(json)),
);
}
return this.http.get(`${this.prefix}${getTranslationFileName(lang, this.suffix)}`, { responseType: 'text' }).pipe(
map((json: any) => JSON.parse(json)),
);
}
}
58 changes: 36 additions & 22 deletions src/ngx-translate-loaders/translate-server.loader.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,73 @@
import { readFileSync } from 'node:fs';

import { TransferState } from '@angular/core';
import { TranslateLoader } from '@ngx-translate/core';
import {
Observable,
of,
} from 'rxjs';

import {
NGX_TRANSLATE_STATE,
NgxTranslateState,
} from './ngx-translate-state';
import { getTranslationFileName } from './translation-file-name';

/**
* A TranslateLoader for ngx-translate to parse json5 files server-side, and store them in the
* TransferState
* A TranslateLoader for ngx-translate to parse json5 files server-side.
*
* The parsed translation messages are intentionally NOT stored in the TransferState, as that would embed the
* complete i18n message catalog in every server-side rendered page. Instead, a preload link for the
* (cacheable) translation file is added to the document head, so the browser can start downloading
* the file right away while the client app is bootstrapping.
*/
export class TranslateServerLoader implements TranslateLoader {

constructor(
protected transferState: TransferState,
protected document: Document,
protected prefix: string = 'dist/assets/i18n/',
protected suffix: string = '.json',
protected browserPrefix: string = 'assets/i18n/',
) {
}

/**
* Return the i18n messages for a given language, and store them in the TransferState
* Return the i18n messages for a given language and add a preload link for them to the document
*
* @param lang the language code
*/
public getTranslation(lang: string): Observable<any> {
const translationHash: string = (process.env.languageHashes as any)[lang + '.json5'];
// Retrieve the file for the given language, and parse it
const messages = JSON.parse(readFileSync(`${this.prefix}${lang}.${translationHash}${this.suffix}`, 'utf8'));
// Store the parsed messages in the transfer state so they'll be available immediately when the
// app loads on the client
this.storeInTransferState(lang, messages);
this.addPreloadLink(`${this.browserPrefix}${getTranslationFileName(lang, this.suffix)}`);
// Return the parsed messages to translate things server side
return of(messages);
}

/**
* Store the i18n messages for the given language code in the transfer state, so they can be
* retrieved client side
* Add a preload link for the translation file, so the download starts as soon as the browser parses the document head
*
* @param lang the language code
* @param messages the i18n messages
* The link is inserted directly after the base element (if any), so the relative href is resolved
* against the base href.
*
* @param href the (relative) URL of the translation file
* @protected
*/
protected storeInTransferState(lang: string, messages) {
const prevState = this.transferState.get<NgxTranslateState>(NGX_TRANSLATE_STATE, {});
const nextState = Object.assign({}, prevState, {
[lang]: messages,
});
this.transferState.set(NGX_TRANSLATE_STATE, nextState);
protected addPreloadLink(href: string) {
const head = this.document?.head;
if (!head) {
console.warn(`No document head available, the preload link for ${href} is not added`);
return;
}
if (head.querySelector(`link[rel="preload"][href="${href}"]`)) {
// ignore silently if the link is already present
return;
}
const link = this.document.createElement('link');
// download translation file with high priority while the page is parsed, and keep it for the later request
link.setAttribute('rel', 'preload');
// translation file is requested via HttpClient (XHR): "fetch" ensures preloaded response is reused for that request
link.setAttribute('as', 'fetch');
// required for "fetch" preloads, so the preloaded response matches the HttpClient request
link.setAttribute('crossorigin', 'anonymous');
link.setAttribute('href', href);
const base = head.querySelector('base');
head.insertBefore(link, base ? base.nextSibling : head.firstChild);
}
}
15 changes: 15 additions & 0 deletions src/ngx-translate-loaders/translation-file-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { environment } from '../environments/environment';

/**
* Returns name of the i18n translation file under which the browser can retrieve translation messages for the given
* language.
* In production mode the i18n translation file name contains the content hash of the translation file, so it can be
* easily cached.
*
* @param lang the language code
* @param suffix the file extension
*/
export function getTranslationFileName(lang: string, suffix: string): string {
const i18nFileHash: string = environment.production ? `.${(process.env.languageHashes as any)[lang + '.json5']}` : '';
return `${lang}${i18nFileHash}${suffix}`;
}
Loading