Skip to content

Commit

Permalink
fix: 修复无法正常渲染 mermaid 的问题(id 冲突)
Browse files Browse the repository at this point in the history
不检查 url 属性,因为 svg 里似乎没有
  • Loading branch information
HowieHz committed Dec 13, 2024
1 parent f4e2d3d commit 06259f0
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions templates/fragments/layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,37 @@
div.innerHTML = mermaidData.svg;
item.parentElement.insertBefore(div, item.nextSibling);
div.setAttribute("data-processed", "true");

// 为每个 SVG 元素中的 id 添加前缀
const svgElement = div.querySelector("svg");

function updateAttribute(refElement, attribute, originalId, newId) {
const value = refElement.getAttribute(attribute);
if (value && value.includes(`#${originalId}`)) {
refElement.setAttribute(attribute, value.replace(`#${originalId}`, `#${newId}`));
}
}

// 更新 id
svgElement.querySelectorAll("[id]").forEach((element) => {
const originalId = element.getAttribute("id");
const newId = `${theme}-${id}-${originalId}`;
element.setAttribute("id", newId);

// 更新引用这些 id 的元素
// marker 标签被使用在很多属性上,用 marker 的属性有 marker-start, marker-mid, marker-end
// symbol 被 use 标签使用,xlink:href 已经被废弃,但是还有一些库在使用,现在用 href
const elementsUsingId = svgElement.querySelectorAll(
`[marker-start*="#${originalId}"], [marker-mid*="#${originalId}"], [marker-end*="#${originalId}"], [xlink:href*="#${originalId}"], [href*="#${originalId}"]`
);
const attributesToUpdate = ["marker-start", "marker-mid", "marker-end", "xlink:href", "href"];
elementsUsingId.forEach((refElement) => {
attributesToUpdate.forEach((attribute) => {
updateAttribute(refElement, attribute, originalId, newId);
});
});
});

// 隐藏原始 class="auto" 的元素
item.style.display = "none";
})
Expand Down

0 comments on commit 06259f0

Please sign in to comment.