| 1 | import type { MarkdownTransformContext, ResolvedSlidevOptions, SlidevPluginOptions } from '@slidev/types' |
| 2 | import type { Plugin } from 'vite' |
| 3 | import MagicString from 'magic-string-stack' |
| 4 | import Markdown from 'unplugin-vue-markdown/vite' |
| 5 | import setupTransformers from '../setups/transformers' |
| 6 | import { useMarkdownItPlugins } from '../syntax' |
| 7 | import { regexSlideSourceId } from './common' |
| 8 | |
| 9 | const RE_MD_EXT = /\.md$/ |
| 10 | |
| 11 | export async function createMarkdownPlugin( |
| 12 | options: ResolvedSlidevOptions, |
| 13 | { markdown: mdOptions }: SlidevPluginOptions, |
| 14 | ): Promise<Plugin> { |
| 15 | const markdownTransformMap = new Map<string, MagicString>() |
| 16 | const extras = await setupTransformers(options.roots) |
| 17 | const transformers = [ |
| 18 | ...extras.pre, |
| 19 | ...extras.preCodeblock, |
| 20 | ...extras.postCodeblock, |
| 21 | ...extras.post, |
| 22 | ] |
| 23 | |
| 24 | return Markdown({ |
| 25 | include: [RE_MD_EXT], |
| 26 | wrapperClasses: '', |
| 27 | headEnabled: false, |
| 28 | frontmatter: false, |
| 29 | escapeCodeTagInterpolation: false, |
| 30 | markdownOptions: { |
| 31 | quotes: '""\'\'', |
| 32 | html: true, |
| 33 | xhtmlOut: true, |
| 34 | linkify: true, |
| 35 | ...mdOptions?.markdownOptions, |
| 36 | }, |
| 37 | ...mdOptions, |
| 38 | async markdownSetup(md) { |
| 39 | await useMarkdownItPlugins(md, options, markdownTransformMap, extras.codeblocks) |
| 40 | await mdOptions?.markdownSetup?.(md) |
| 41 | }, |
| 42 | transforms: { |
| 43 | ...mdOptions?.transforms, |
| 44 | async before(code, id) { |
| 45 | // Skip entry Markdown files |
| 46 | if (options.data.markdownFiles[id]) |
| 47 | return '' |
| 48 | |
| 49 | code = await mdOptions?.transforms?.before?.(code, id) ?? code |
| 50 | |
| 51 | const match = id.match(regexSlideSourceId) |
| 52 | if (!match) |
| 53 | return code |
| 54 | |
| 55 | const s = new MagicString(code) |
| 56 | markdownTransformMap.set(id, s) |
| 57 | const ctx: MarkdownTransformContext = { |
| 58 | s, |
| 59 | slide: options.data.slides[+match[1] - 1], |
| 60 | options, |
| 61 | } |
| 62 | |
| 63 | for (const transformer of transformers) { |
| 64 | if (!transformer) |
| 65 | continue |
| 66 | await transformer(ctx) |
| 67 | if (!ctx.s.isEmpty()) |
| 68 | ctx.s.commit() |
| 69 | } |
| 70 | |
| 71 | return s.toString() |
| 72 | }, |
| 73 | }, |
| 74 | }) as Plugin |
| 75 | } |
| 76 |