toc-and-anchor.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. export default class TocAndAnchorConfigurer {
  2. constructor(crowi, renderToc) {
  3. this.crowi = crowi;
  4. this.renderToc = renderToc;
  5. }
  6. configure(md) {
  7. md.use(require('markdown-it-toc-and-anchor').default, {
  8. anchorLinkBefore: false,
  9. anchorLinkSymbol: '',
  10. anchorLinkSymbolClassName: 'fa fa-link',
  11. anchorClassName: 'revision-head-link',
  12. })
  13. .use(require('markdown-it-named-headers'), { // overwrite id defined by markdown-it-toc-and-anchor
  14. slugify: this.customSlugify,
  15. })
  16. ;
  17. // set toc render function
  18. if (this.renderToc != null) {
  19. md.set({
  20. tocCallback: (tocMarkdown, tocArray, tocHtml) => {
  21. this.renderToc(tocHtml);
  22. },
  23. });
  24. }
  25. }
  26. /**
  27. * create Base64 encoded id
  28. * @see https://qiita.com/satokaz/items/64582da4640898c4bf42
  29. * @param {string} header
  30. */
  31. customSlugify(header) {
  32. return encodeURIComponent(header.trim()
  33. .toLowerCase()
  34. .replace(/[\]\[\!\"\#\$\%\&\'\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~]/g, '')
  35. .replace(/\s+/g, '-')) // Replace spaces with hyphens
  36. .replace(/\-+$/, ''); // Replace trailing hyphen
  37. }
  38. }