import { Component, OnChanges, SimpleChanges, ChangeDetectionStrategy, ElementRef, inject, input } from '@angular/core' import { loadKatex, typesetMath } from './katex' /** * Math rendering component for Angular. * Renders LaTeX math expressions using KaTeX. * * Note: Consumers must import `@comark/plugin-katex/katex.css` in their own * project to load the KaTeX styles (e.g. in `styles.css` or a global import). * * @example * ```typescript * import { Math } from '@comark/plugin-katex/angular' * ``` */ @Component({ selector: 'comark-math', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: '', }) export class Math implements OnChanges { readonly content = input.required() readonly class = input('') readonly __node = input({}) private elementRef = inject(ElementRef) ngOnChanges(_changes: SimpleChanges): void { this.renderMath() } private renderMath(): void { if (typeof document === 'undefined') return const isInline = this.class()?.includes('inline') const hostEl = this.elementRef.nativeElement as HTMLElement while (hostEl.firstChild) { hostEl.removeChild(hostEl.firstChild) } const wrapper = document.createElement(isInline ? 'span' : 'div') wrapper.className = isInline ? 'math inline' : 'math block' const content = this.content() const html = typesetMath(content, !isInline) if (html) { wrapper.innerHTML = html } else { // Unfinished or invalid TeX, and TeX before KaTeX loads, stays readable as its source. wrapper.textContent = content if (html === undefined) { loadKatex().then( () => content === this.content() && this.renderMath(), () => {} ) } } hostEl.appendChild(wrapper) } }