|
| 1 | +import MarkdownIt from 'markdown-it' |
| 2 | +import { defineNuxtPlugin } from '#app' |
| 3 | + |
| 4 | +const markdownIt = new MarkdownIt({ |
| 5 | + html: true, |
| 6 | + xhtmlOut: false, |
| 7 | + breaks: true, |
| 8 | + langPrefix: 'language-', |
| 9 | + linkify: true, |
| 10 | + typographer: true, |
| 11 | + quotes: '“”‘’', |
| 12 | +}) |
| 13 | + |
| 14 | +markdownIt.linkify.set({ fuzzyEmail: false }) |
| 15 | + |
| 16 | +// Remember old renderer, if overridden, or proxy to default renderer |
| 17 | +const defaultRender = markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) { |
| 18 | + return self.renderToken(tokens, idx, options) |
| 19 | +} |
| 20 | + |
| 21 | +markdownIt.renderer.rules.link_open = function (tokens, idx, options, env, self) { |
| 22 | + // If you are sure other plugins can't add `target` - drop check below |
| 23 | + const aIndex = tokens[idx].attrIndex('target') |
| 24 | + const relIndex = tokens[idx].attrIndex('rel') |
| 25 | + |
| 26 | + if (aIndex < 0) { |
| 27 | + tokens[idx].attrPush(['target', '_blank']) |
| 28 | + } |
| 29 | + else { |
| 30 | + tokens[idx].attrs[aIndex][1] = '_blank' |
| 31 | + } |
| 32 | + |
| 33 | + if (relIndex < 0) { |
| 34 | + tokens[idx].attrPush(['rel', 'noopener noreferrer']) |
| 35 | + } |
| 36 | + else { |
| 37 | + tokens[idx].attrs[relIndex][1] = 'noopener noreferrer' |
| 38 | + } |
| 39 | + |
| 40 | + // pass token to default renderer. |
| 41 | + return defaultRender(tokens, idx, options, env, self) |
| 42 | +} |
| 43 | + |
| 44 | +export default defineNuxtPlugin((nuxtApp) => { |
| 45 | + nuxtApp.provide('mdit', markdownIt) |
| 46 | +}) |
0 commit comments