|
| 1 | +import { Injectable } from '@angular/core'; |
| 2 | +import { Observable, ReplaySubject, Subject } from 'rxjs'; |
| 3 | +import { environment } from 'src/environments/environment'; |
| 4 | +import { MathJaxConfig, MathService } from './math.service'; |
| 5 | + |
| 6 | +@Injectable({ |
| 7 | + providedIn: 'root' |
| 8 | +}) |
| 9 | +export class ClientMathService extends MathService { |
| 10 | + |
| 11 | + protected isReady$: Subject<boolean>; |
| 12 | + |
| 13 | + protected mathJaxOptions = { |
| 14 | + tex: { |
| 15 | + inlineMath: [['$', '$'], ['\\(', '\\)']] |
| 16 | + }, |
| 17 | + svg: { |
| 18 | + fontCache: 'global' |
| 19 | + }, |
| 20 | + startup: { |
| 21 | + typeset: false |
| 22 | + } |
| 23 | + }; |
| 24 | + |
| 25 | + protected mathJax: MathJaxConfig = { |
| 26 | + source: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js', |
| 27 | + id: 'MathJaxScript' |
| 28 | + }; |
| 29 | + protected mathJaxFallback: MathJaxConfig = { |
| 30 | + source: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-chtml.min.js', |
| 31 | + id: 'MathJaxBackupScript' |
| 32 | + }; |
| 33 | + |
| 34 | + constructor() { |
| 35 | + super(); |
| 36 | + |
| 37 | + this.isReady$ = new ReplaySubject<boolean>(); |
| 38 | + |
| 39 | + void this.registerMathJaxAsync(this.mathJax) |
| 40 | + .then(() => this.isReady$.next(true)) |
| 41 | + .catch(_ => { |
| 42 | + void this.registerMathJaxAsync(this.mathJaxFallback) |
| 43 | + .then(() => this.isReady$.next(true)); |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + protected async registerMathJaxAsync(config: MathJaxConfig): Promise<any> { |
| 48 | + if (environment.markdown.mathjax) { |
| 49 | + return new Promise<void>((resolve, reject) => { |
| 50 | + |
| 51 | + const optionsScript: HTMLScriptElement = document.createElement('script'); |
| 52 | + optionsScript.type = 'text/javascript'; |
| 53 | + optionsScript.text = `MathJax = ${JSON.stringify(this.mathJaxOptions)};`; |
| 54 | + document.head.appendChild(optionsScript); |
| 55 | + |
| 56 | + const script: HTMLScriptElement = document.createElement('script'); |
| 57 | + script.id = config.id; |
| 58 | + script.type = 'text/javascript'; |
| 59 | + script.src = config.source; |
| 60 | + script.crossOrigin = 'anonymous'; |
| 61 | + script.async = true; |
| 62 | + script.onload = () => resolve(); |
| 63 | + script.onerror = error => reject(error); |
| 64 | + document.head.appendChild(script); |
| 65 | + }); |
| 66 | + } |
| 67 | + return Promise.resolve(); |
| 68 | + } |
| 69 | + |
| 70 | + ready(): Observable<boolean> { |
| 71 | + return this.isReady$; |
| 72 | + } |
| 73 | + |
| 74 | + render(element: HTMLElement) { |
| 75 | + if (environment.markdown.mathjax) { |
| 76 | + (window as any).MathJax.typesetPromise([element]); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments