codeRender.ts 1.3 KB

123456789101112131415161718192021222324252627282930
  1. import copySVG from "../../assets/icons/copy.svg";
  2. import {i18n} from "../i18n/index";
  3. export const codeRender = (element: HTMLElement, lang: (keyof II18nLang)) => {
  4. element.querySelectorAll("pre > code").forEach((e: HTMLElement, index: number) => {
  5. if (e.className.indexOf("language-mermaid") > -1 || e.className.indexOf("language-echarts") > -1) {
  6. return;
  7. }
  8. if (e.style.maxHeight.indexOf("px") > -1) {
  9. return;
  10. }
  11. // 避免预览区在渲染后由于代码块过多产生性能问题 https://github.com/b3log/vditor/issues/67
  12. if (element.className.indexOf("vditor-preview") > -1 && index > 5) {
  13. return;
  14. }
  15. const divElement = document.createElement("div");
  16. divElement.className = "vditor-copy";
  17. divElement.innerHTML = `<textarea>${e.innerText}</textarea><span aria-label="${i18n[lang].copy}"
  18. onmouseover="this.setAttribute('aria-label', '${i18n[lang].copy}')"
  19. class="vditor-tooltipped vditor-tooltipped__w"
  20. onclick="this.previousElementSibling.select();document.execCommand('copy');` +
  21. `this.setAttribute('aria-label', '${i18n[lang].copied}')">${copySVG}</span>`;
  22. e.before(divElement);
  23. e.style.maxHeight = (window.outerHeight - 40) + "px";
  24. });
  25. };