[DURACOM-240] Assure the MathJax script has been registered before rendering

This commit is contained in:
Giuseppe Digilio
2024-03-21 09:46:14 +01:00
parent cfa2882a28
commit 418f07bbf2
4 changed files with 43 additions and 8 deletions

View File

@@ -1,4 +1,8 @@
import { Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import {
Inject,
Injectable,
} from '@angular/core';
import {
BehaviorSubject,
Observable,
@@ -6,6 +10,10 @@ import {
} from 'rxjs';
import { environment } from 'src/environments/environment';
import {
NativeWindowRef,
NativeWindowService,
} from '../services/window.service';
import {
MathJaxConfig,
MathService,
@@ -14,6 +22,9 @@ import {
@Injectable({
providedIn: 'root',
})
/**
* Provide the MathService for CSR
*/
export class ClientMathService extends MathService {
protected isReady$: Subject<boolean>;
@@ -39,7 +50,10 @@ export class ClientMathService extends MathService {
id: 'MathJaxBackupScript',
};
constructor() {
constructor(
@Inject(DOCUMENT) private _document: Document,
@Inject(NativeWindowService) protected _window: NativeWindowRef,
) {
super();
this.isReady$ = new BehaviorSubject<boolean>(false);
@@ -52,16 +66,21 @@ export class ClientMathService extends MathService {
});
}
/**
* Register the specified MathJax script in the document
*
* @param config The configuration object for the script
*/
protected async registerMathJaxAsync(config: MathJaxConfig): Promise<any> {
if (environment.markdown.mathjax) {
return new Promise<void>((resolve, reject) => {
const optionsScript: HTMLScriptElement = document.createElement('script');
const optionsScript: HTMLScriptElement = this._document.createElement('script');
optionsScript.type = 'text/javascript';
optionsScript.text = `MathJax = ${JSON.stringify(this.mathJaxOptions)};`;
document.head.appendChild(optionsScript);
this._document.head.appendChild(optionsScript);
const script: HTMLScriptElement = document.createElement('script');
const script: HTMLScriptElement = this._document.createElement('script');
script.id = config.id;
script.type = 'text/javascript';
script.src = config.source;
@@ -69,19 +88,27 @@ export class ClientMathService extends MathService {
script.async = true;
script.onload = () => resolve();
script.onerror = error => reject(error);
document.head.appendChild(script);
this._document.head.appendChild(script);
});
}
return Promise.resolve();
}
/**
* Return the status of the script registration
*/
ready(): Observable<boolean> {
return this.isReady$;
}
/**
* Render the specified element using the MathJax JavaScript
*
* @param element The element to render with MathJax
*/
render(element: HTMLElement) {
if (environment.markdown.mathjax) {
(window as any).MathJax.typesetPromise([element]);
this._window.nativeWindow.MathJax.typesetPromise([element]);
}
}
}