diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index ce3abbcb0ed..c5fffbc5dd5 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -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: | @@ -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 \ No newline at end of file + docker compose -f docker/docker-compose.yml -f docker/docker-compose-rest.yml down diff --git a/src/modules/app/browser-app.config.ts b/src/modules/app/browser-app.config.ts index 03620d0425a..7727e7dfc0d 100644 --- a/src/modules/app/browser-app.config.ts +++ b/src/modules/app/browser-app.config.ts @@ -75,8 +75,8 @@ import { BrowserInitService } from './browser-init.service'; export const REQ_KEY = makeStateKey('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 { @@ -98,7 +98,7 @@ export const browserAppConfig: ApplicationConfig = mergeApplicationConfig({ loader: { provide: TranslateLoader, useFactory: createTranslateLoader, - deps: [TransferState, HttpClient], + deps: [HttpClient], }, missingTranslationHandler: provideMissingTranslationHandler(MissingTranslationHelper), }), diff --git a/src/modules/app/browser-init.service.ts b/src/modules/app/browser-init.service.ts index 524229d8bb5..4ca2c210680 100644 --- a/src/modules/app/browser-init.service.ts +++ b/src/modules/app/browser-init.service.ts @@ -44,6 +44,8 @@ import { filter, find, map, + switchMap, + timeout, } from 'rxjs/operators'; import { logStartupMessage } from '../../../startup-message'; @@ -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. */ @@ -125,6 +132,7 @@ export class BrowserInitService extends InitService { logStartupMessage(environment); this.initI18n(); + const translationsLoaded = this.loadTranslations(); this.initAngulartics(); this.initGoogleAnalytics(); this.initMatomo(); @@ -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; @@ -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 { + 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(); } @@ -242,5 +275,4 @@ export class BrowserInitService extends InitService { this.rootDataService.invalidateRootCache(); }); } - } diff --git a/src/modules/app/server-app.config.ts b/src/modules/app/server-app.config.ts index 6847c27cc93..605ec2f547a 100644 --- a/src/modules/app/server-app.config.ts +++ b/src/modules/app/server-app.config.ts @@ -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'; @@ -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({ @@ -81,7 +81,7 @@ export const serverAppConfig: ApplicationConfig = mergeApplicationConfig({ loader: { provide: TranslateLoader, useFactory: createTranslateLoader, - deps: [TransferState], + deps: [DOCUMENT], }, }), ...ServerInitService.providers(), diff --git a/src/ngx-translate-loaders/ngx-translate-state.ts b/src/ngx-translate-loaders/ngx-translate-state.ts deleted file mode 100644 index 3646053fadf..00000000000 --- a/src/ngx-translate-loaders/ngx-translate-state.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { makeStateKey } from '@angular/core'; - -/** - * Represents ngx-translate messages in different languages in the TransferState - */ -export class NgxTranslateState { - [lang: string]: { - [key: string]: string - } -} - -/** - * The key to store the NgxTranslateState as part of the TransferState - */ -export const NGX_TRANSLATE_STATE = makeStateKey('NGX_TRANSLATE_STATE'); diff --git a/src/ngx-translate-loaders/translate-browser.loader.ts b/src/ngx-translate-loaders/translate-browser.loader.ts index 44e1710b148..09b3d61ac65 100644 --- a/src/ngx-translate-loaders/translate-browser.loader.ts +++ b/src/ngx-translate-loaders/translate-browser.loader.ts @@ -1,26 +1,15 @@ 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, @@ -28,25 +17,13 @@ export class TranslateBrowserLoader implements TranslateLoader { } /** - * 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 { - // Get the ngx-translate messages from the transfer state, to speed up the initial page load - // client side - const state = this.transferState.get(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)), + ); } } diff --git a/src/ngx-translate-loaders/translate-server.loader.ts b/src/ngx-translate-loaders/translate-server.loader.ts index 06312b3a2b0..1b12fa15b8a 100644 --- a/src/ngx-translate-loaders/translate-server.loader.ts +++ b/src/ngx-translate-loaders/translate-server.loader.ts @@ -1,32 +1,33 @@ 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 */ @@ -34,26 +35,39 @@ export class TranslateServerLoader implements TranslateLoader { 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(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); } } diff --git a/src/ngx-translate-loaders/translation-file-name.ts b/src/ngx-translate-loaders/translation-file-name.ts new file mode 100644 index 00000000000..5361c8f419a --- /dev/null +++ b/src/ngx-translate-loaders/translation-file-name.ts @@ -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}`; +}