<script lang="ts">
import "github-markdown-css/github-markdown.css";
import "./main.css";
import { onMount } from "svelte";

let content = `$E=mc^2$`;
let source = "";

let version = 0;

import { tick } from "svelte";

let complete = false;

async function updateSource() {
    complete = false;
    version += 1;
    source = content;
    if ((content.includes("$")) || (content.includes("$$"))) {
      complete = false;
      TriggerRender();
    } else {
      complete = true;
    }
}

function TriggerRender() {
  // 如果没有标签名为 mjx-container 元素，就一直循环触发
  const checkAndRender = async () => {
    await tick();
    const mjxContainer = document.querySelector('mjx-container');
    if (!mjxContainer) {
      await renderMath();
      setTimeout(checkAndRender, 100);
    } else {
      console.log("MathJax rendering complete.");
      complete = true;
    }
  };
  checkAndRender();
}

async function renderMath() {
    console.log("Rendering math...");
    const MathJax = (window as any).MathJax;
    if (!MathJax) return;
    if (MathJax.typesetPromise) {
      await MathJax.typesetPromise();
    }
}

let sizeParam = '1.2em';
onMount(async () => {
    /// @ts-ignore
    await import("mathjax-full/es5/tex-mml-svg.js");

    const urlParams = new URLSearchParams(window.location.search);
    sizeParam = urlParams.get('size') ?? sizeParam;

    (window as any).checkState = () => {
      return complete;
    };
});

</script>

<textarea name="content" id="content" bind:value={content}></textarea>
<button id="button" on:click={updateSource}>Render Math</button>

<svelte:head>
  <script>
    window.MathJax = {
      loader: {
        paths: {
          tex: 'node_modules/mathjax-full/es5/input/tex/extensions'
        }
      },
      tex: {
        inlineMath: [['$', '$']],
        displayMath: [['$$', '$$']]
      }
    };
  </script>
  <style>
    svg text[font-family=serif] {
      font-family: 'Noto Serif CJK SC', 'Noto Serif SC', 'Noto Serif', serif;
    }
  </style>
</svelte:head>

<!-- version 是一个用于强制 Svelte 重新渲染内容的变量。当内容更新时，version 会递增，从而触发 Svelte 重新渲染包含 source 的部分。 -->
{#key version}
<div id="main" class="markdown-body main" style="font-size: {sizeParam || '1.2em'}">
  {source}
</div>
{/key}
