| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- @props(['content' => '', 'class' => '', 'inline' => false])
- <div class="math-render {{ $class }}" data-math-content="{!! $content !!}">
- {!! $content !!}
- </div>
- @push('scripts')
- <script>
- (function() {
- 'use strict';
- function renderMathElement(element) {
- if (typeof window.katex === 'undefined') {
- // 等待 KaTeX 加载
- if (window.mathRenderAttempts < 50) {
- window.mathRenderAttempts++;
- setTimeout(() => renderMathElement(element), 100);
- }
- return;
- }
- // 避免重复渲染
- if (element.dataset.rendered === 'true') {
- return;
- }
- const content = element.dataset.mathContent || element.textContent;
- if (!content) return;
- try {
- let html = content;
- // 渲染 $$...$$ 块级公式
- html = html.replace(/\$\$([\s\S]*?)\$\$/g, (match, formula) => {
- try {
- return window.katex.renderToString(formula.trim(), {
- throwOnError: false,
- displayMode: true
- });
- } catch (e) {
- console.warn('KaTeX render error:', e);
- return match;
- }
- });
- // 渲染 $...$ 行内公式
- html = html.replace(/\$(.*?)\$/g, (match, formula) => {
- try {
- return window.katex.renderToString(formula, {
- throwOnError: false,
- displayMode: false
- });
- } catch (e) {
- console.warn('KaTeX render error:', e);
- return match;
- }
- });
- // 渲染 \(...\) 行内公式
- html = html.replace(/\\\((.*?)\\\)/g, (match, formula) => {
- try {
- return window.katex.renderToString(formula, {
- throwOnError: false,
- displayMode: false
- });
- } catch (e) {
- console.warn('KaTeX render error:', e);
- return match;
- }
- });
- element.innerHTML = html;
- element.dataset.rendered = 'true';
- } catch (e) {
- console.error('Math render error:', e);
- }
- }
- function renderAllMath() {
- document.querySelectorAll('.math-render:not([data-rendered="true"])').forEach(renderMathElement);
- }
- // 初始化
- document.addEventListener('DOMContentLoaded', () => {
- if (typeof window.katex === 'undefined') {
- const script = document.createElement('script');
- script.src = '/js/katex.min.js';
- script.onload = () => {
- window.mathRenderAttempts = 0;
- renderAllMath();
- };
- document.head.appendChild(script);
- } else {
- renderAllMath();
- }
- });
- // Livewire 兼容性
- document.addEventListener('livewire:initialized', () => {
- renderAllMath();
- });
- document.addEventListener('livewire:updated', () => {
- setTimeout(renderAllMath, 100);
- });
- // Alpine.js 兼容性
- document.addEventListener('alpine:init', () => {
- renderAllMath();
- });
- // 自定义事件监听
- document.addEventListener('math:render', () => {
- renderAllMath();
- });
- })();
- </script>
- @endpush
- @push('styles')
- <link rel="stylesheet" href="/css/katex/katex.min.css">
- @endpush
|