Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mermaid 图表 自适应黑白主题模式。非原生实现方式 #988

Open
appotry opened this issue Aug 2, 2023 · 0 comments
Open

mermaid 图表 自适应黑白主题模式。非原生实现方式 #988

appotry opened this issue Aug 2, 2023 · 0 comments
Labels
✨ enhancement New feature request

Comments

@appotry
Copy link

appotry commented Aug 2, 2023

mermaid 库 本身里面有这个接口,但没有完成这个功能。 刚刚看到有人外部完成了这个功能。可以考虑把这个加入主题中

演示地址 here

(function(window){
'use strict'

  const elementCode = '.language-mermaid'
  const loadMermaid = function(theme) {
    window.mermaid.initialize({theme})
    window.mermaid.init({theme}, document.querySelectorAll(elementCode))
  }
  const saveOriginalData = function(){
    return new Promise((resolve, reject) => {
      try {
        var els = document.querySelectorAll(elementCode),
            count = els.length;
        els.forEach(element => {
          element.setAttribute('data-original-code', element.innerHTML)
          count--
          if(count == 0){
            resolve()
          }
        });
      } catch (error) {
       reject(error) 
      }
    })
  }
  const resetProcessed = function(){
    return new Promise((resolve, reject) => {
      try {
        var els = document.querySelectorAll(elementCode),
            count = els.length;
        els.forEach(element => {
          if(element.getAttribute('data-original-code') != null){
            element.removeAttribute('data-processed')
            element.innerHTML = element.getAttribute('data-original-code')
          }
          count--
          if(count == 0){
            resolve()
          }
        });
      } catch (error) {
       reject(error) 
      }
    })
  } 

  const init = ()=>{
    saveOriginalData()
    .catch( console.error )
    document.body.addEventListener('dark-theme-set', ()=>{
      resetProcessed()
      .then(loadMermaid('dark'))
      .catch(console.error)
    })
    document.body.addEventListener('light-theme-set', ()=>{
      resetProcessed()
      .then(loadMermaid('default'))
      .catch(console.error)
    })
  }
  window.initMermaid = init
})(window);

来源 mermaid-js/mermaid#1945

如果可能,还是希望官方mermaid自带支持,不过这个实现方式也算不错了

@appotry appotry added the ✨ enhancement New feature request label Aug 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✨ enhancement New feature request
Projects
None yet
Development

No branches or pull requests

1 participant