EveSunMaple / Frosti

A clean, elegant, and fast static blog template! 🚀 Developed with Astro
https://frosti.saroprock.com
GNU General Public License v3.0
181 stars 30 forks source link

fix katex in content index #38

Closed Loping151 closed 1 month ago

Loping151 commented 1 month ago

~谢罪,早知道把前两个typo并在这里了~

拉取侧边栏目录时,采用的是读html而不是直接从markdown里拉。如果我们有需要在标题中使用latex符号,会导致常见的katex的符号复制问题。因为heading.textContent的逻辑是提取html中所有文本部分,而katex渲染的html会例如

(如果markdown中标题为### 关于$\gamma$和$\beta$的必要性

<h4 id="关于\gamma和\beta的必要性">关于<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>γ</mi></mrow><annotation encoding="application/x-tex">\gamma</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.05556em;">γ</span></span></span></span>和<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>β</mi></mrow><annotation encoding="application/x-tex">\beta</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.05278em;">β</span></span></span></span>的必要性<a href="#关于\gamma和\beta的必要性" class="anchor"><span class="anchor-icon" data-pagefind-ignore="">#</span></a></h4>

image 显然,默认逻辑下,显示的是: image

这段代码修改了拉取逻辑,跳过了冗余的部分(即 $\gamma$ \gamma)部分

  function getCleanText(element: HTMLElement) {
    let text = "";
    element.childNodes.forEach((node: ChildNode) => {
      if (node.nodeType === Node.TEXT_NODE) {
        text += node.textContent;
      } else if (node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).className !== 'katex-mathml') {
        text += getCleanText(node as HTMLElement);
      }
    });
    return text;
  }

修复后,符号显示正常: image

ps:上面这篇文章位于 https://blog.loping151.com/blog/2024/%E9%9D%A2%E8%AF%95%E5%A4%8D%E7%9B%98-1/

vercel[bot] commented 1 month ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
frosti ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 15, 2024 9:58am
EveSunMaple commented 1 month ago

非常感谢,不过我倒是打算将 toc 写成一个 remark 插件(早上没时间写了),以减少 js。这里先合并,到后面我研究研究再看!