| 1 | import { defineCodeblockTransformer } from '@slidev/types' |
| 2 | import lz from 'lz-string' |
| 3 | import { extractBracedExpression } from '../utils' |
| 4 | |
| 5 | const RE_MONACO = /^([\w'-]+)?\s*\{(monaco[\w-]*)\}/ |
| 6 | const RE_DIFF_SEPARATOR = /^\s*~~~\s*\n/m |
| 7 | |
| 8 | export default defineCodeblockTransformer(async ({ info, code, options: { data: { config }, mode } }) => { |
| 9 | const match = info.match(RE_MONACO) |
| 10 | if (!match) |
| 11 | return |
| 12 | const [, lang = '', monaco] = match |
| 13 | |
| 14 | const rest = info.slice(match[0].length) |
| 15 | const options = rest.trimStart().startsWith('{') |
| 16 | ? extractBracedExpression(rest) |
| 17 | : undefined |
| 18 | |
| 19 | const monacoEnabled = config.monaco === true || config.monaco === mode |
| 20 | if (!monacoEnabled) { |
| 21 | return |
| 22 | } |
| 23 | |
| 24 | let encoded |
| 25 | let diff = '' |
| 26 | if (monaco === 'monaco-diff') { |
| 27 | const [original, modified] = code.split(RE_DIFF_SEPARATOR, 2) |
| 28 | encoded = lz.compressToBase64(original) |
| 29 | diff = modified === undefined |
| 30 | ? '' |
| 31 | : `diff-lz="${lz.compressToBase64(modified)}"` |
| 32 | } |
| 33 | else { |
| 34 | encoded = lz.compressToBase64(code) |
| 35 | } |
| 36 | |
| 37 | const optionsProp = options |
| 38 | ? `v-bind="${options}"` |
| 39 | : '' |
| 40 | const runnable = monaco === 'monaco-run' |
| 41 | ? 'runnable' |
| 42 | : '' |
| 43 | return `<Monaco ${optionsProp} ${runnable} lang="${lang}" code-lz="${encoded}" ${diff} />` |
| 44 | }) |
| 45 |