render.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import Vditor from '../src/method'
  2. import '../src/assets/less/index.less'
  3. const outlineElement = document.getElementById('outline')
  4. const previewElement = document.getElementById('preview')
  5. document.querySelector('.markdown-list').addEventListener('click', function (event) {
  6. if (event.target.tagName === 'SPAN') {
  7. render(event.target.getAttribute('data-file'))
  8. }
  9. })
  10. previewElement.addEventListener('click', function (event) {
  11. if (event.target.tagName === 'IMG') {
  12. Vditor.previewImage(event.target, 'zh_CN', outlineElement.classList.contains('dark') ? 'dark' : 'classic')
  13. }
  14. })
  15. const render = (fileName) => {
  16. fetch(`/demo/markdown/${fileName}.md`).then(response => response.text()).then(markdown => {
  17. Vditor.preview(previewElement, markdown, {
  18. markdown: {
  19. toc: true, listStyle: fileName === 'cute-list',
  20. }, speech: {
  21. enable: true,
  22. }, anchor: 1, after() {
  23. if (window.innerWidth <= 768) {
  24. return
  25. }
  26. Vditor.outlineRender(previewElement, outlineElement)
  27. if (outlineElement.innerText.trim() !== '') {
  28. outlineElement.style.display = 'block'
  29. }
  30. }, lazyLoadImage: 'https://unpkg.com/vditor/dist/images/img-loading.svg', renderers: {
  31. renderHeading: (node, entering) => {
  32. const id = Lute.GetHeadingID(node)
  33. if (entering) {
  34. return [`<h${node.__internal_object__.HeadingLevel} id="${id}" class="vditor__heading"><span class="prefix"></span><span>`, Lute.WalkContinue]
  35. } else {
  36. return [`</span><a id="vditorAnchor-${id}" class="vditor-anchor" href="#${id}"><svg viewBox="0 0 16 16" version="1.1" width="16" height="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a></h${node.__internal_object__.HeadingLevel}>`, Lute.WalkContinue]
  37. }
  38. },
  39. },
  40. })
  41. })
  42. }
  43. render('zh_CN')
  44. window.setTheme = (theme) => {
  45. if (theme === 'dark') {
  46. Vditor.setCodeTheme('native')
  47. Vditor.setContentTheme('dark', 'https://unpkg.com/vditor/dist/css/content-theme')
  48. outlineElement.classList.add('dark')
  49. document.querySelector('html').style.backgroundColor = '#2f363d'
  50. } else {
  51. Vditor.setCodeTheme('github')
  52. Vditor.setContentTheme('light', 'https://unpkg.com/vditor/dist/css/content-theme')
  53. outlineElement.classList.remove('dark')
  54. document.querySelector('html').style.backgroundColor = '#fff'
  55. }
  56. }