<!-- eslint-disable no-cond-assign -->
<!-- eslint-disable unicorn/prefer-string-slice -->
<script setup lang="ts">
import katex from 'katex'

import 'katex/dist/katex.min.css'

const props = defineProps<{
  text: any
}>()

defineOptions({ name: 'LatexText' })

// 匹配公式的正则
// const regex_1 = /(\$.*?\$)/g
const regex_2 = /(<span data-.+?="[^"]*"><\/span>)/g
// const regex_3 = /(!\[.*?\]\(.*?\))/g

// 添加为katex渲染
function addLatexText(list: any[], text: string) {
  list.push({
    isLatex: true,
    content: katex.renderToString(text, { throwOnError: false, strict: false }),
  })
}

// 第1步：美元符判定
// function parseLatex1_$(list: any[], text: string) {
//   const parts = text.split(regex_1)
//   for (const part of parts) {
//     if (part.startsWith('$') && part.endsWith('$')) {
//       addLatexText(list, part.substring(1, part.length - 1))
//     } else {
//       list.push({
//         content: part,
//       })
//     }
//   }
// }

// 第2步：标签判定
function parseLatex2_tag(list: any[], text: string) {
  if (!text?.length) return
  const parts = text.split(regex_2)
  if (!parts?.length) return
  for (const part of parts) {
    let match: any
    if (part.includes('type="formula"') && (match = part.match(/(?<=data-value=").*?(?=")/))) {
      const text = match[0].replace('\t', String.raw`\t`).replace('\n', String.raw`\n`)
      addLatexText(list, text)
    } else {
      list.push({
        content: part,
      })
    }
  }
}

// 第3步：![]()判定
// function parseLatex3_md_img(list: any[], text: string) {
//   const parts = text.split(regex_3)
//   for (const part of parts) {
//     let match: any
//     if ((match = part.match(/(?<=\]\().+?(?=\))/))) {
//       list.push({
//         content: `<img src="${match[0]}">`,
//       })
//     } else {
//       list.push({
//         content: part,
//       })
//     }
//   }
// }

const renderText = computed(() => {
  const list = [] as any[]
  parseLatex2_tag(list, props.text)
  let html = ''
  for (const item of list) {
    html += item.content
  }
  return html
})
</script>

<template>
  <div class="latex-text" v-html="renderText"></div>
</template>
