返回 slidev
Monaco.vue
根目录 / packages / client / builtin / Monaco.vue
1 <!--
2 Monaco Editor
3 (auto transformed, you don't need to use this component directly)
4
5 Usage:
6
7 ```ts {monaco}
8 const your_code = 'here'
9 ```
10
11 Learn more: https://sli.dev/guide/syntax.html#monaco-editor
12 -->
13
14 <script setup lang="ts">
15 import type { RawAtValue } from '@slidev/types'
16 import type * as monaco from 'monaco-editor'
17 import { debounce } from '@antfu/utils'
18 import { whenever } from '@vueuse/core'
19 import lz from 'lz-string'
20 import { computed, defineAsyncComponent, nextTick, onMounted, ref } from 'vue'
21 import { useNav } from '../composables/useNav'
22 import { useSlideContext } from '../context'
23 import { configs } from '../env'
24 import { makeId } from '../logic/utils'
25
26 const props = withDefaults(
27 defineProps<{
28 codeLz?: string
29 diffLz?: string
30 lang?: string
31 readonly?: boolean
32 lines?: boolean
33 lineNumbers?: 'on' | 'off' | 'relative' | 'interval'
34 height?: number | string // Posible values: 'initial', 'auto', '100%', '200px', etc.
35 editorOptions?: monaco.editor.IEditorOptions
36 ata?: boolean
37 runnable?: boolean
38 writable?: string
39 autorun?: boolean | 'once'
40 showOutputAt?: RawAtValue
41 outputHeight?: string
42 outputFontSize?: number | string
43 highlightOutput?: boolean
44 runnerOptions?: Record<string, unknown>
45 }>(),
46 {
47 codeLz: '',
48 lang: 'typescript',
49 readonly: false,
50 lines: configs.lineNumbers,
51 height: 'initial',
52 ata: true,
53 runnable: false,
54 autorun: true,
55 highlightOutput: true,
56 },
57 )
58
59 const CodeRunner = defineAsyncComponent(() => import('../internals/CodeRunner.vue').then(r => r.default))
60
61 const code = ref(lz.decompressFromBase64(props.codeLz).trimEnd())
62 const diff = props.diffLz && ref(lz.decompressFromBase64(props.diffLz).trimEnd())
63 const isWritable = computed(() => props.writable && !props.readonly && __DEV__)
64 const lineNumbers = props.lineNumbers ?? (props.lines ? 'on' : 'off')
65
66 const langMap: Record<string, string> = {
67 ts: 'typescript',
68 js: 'javascript',
69 }
70 const lang = langMap[props.lang] ?? props.lang
71 const extMap: Record<string, string> = {
72 typescript: 'mts',
73 javascript: 'mjs',
74 ts: 'mts',
75 js: 'mjs',
76 }
77 const ext = extMap[props.lang] ?? props.lang
78
79 const container = ref<HTMLDivElement>()
80
81 const contentHeight = ref(0)
82 const initialHeight = ref<number>()
83 const height = computed(() => {
84 if (props.height === 'auto')
85 return `${contentHeight.value}px`
86 if (props.height === 'initial')
87 return `${initialHeight.value}px`
88 return props.height
89 })
90
91 const editorFontSize = ref<number | string | undefined>(props.editorOptions?.fontSize)
92 const outputFontSize = computed(() => props.outputFontSize ?? editorFontSize.value)
93
94 const loadTypes = ref<() => void>()
95 const { $page: thisSlideNo, $renderContext: renderContext } = useSlideContext()
96 const { currentSlideNo } = useNav()
97 const stopWatchTypesLoading = whenever(
98 () => Math.abs(thisSlideNo.value - currentSlideNo.value) <= 1 && loadTypes.value,
99 (loadTypes) => {
100 if (['slide', 'presenter'].includes(renderContext.value))
101 loadTypes()
102 else
103 setTimeout(loadTypes, 5000)
104 },
105 )
106
107 onMounted(async () => {
108 // Lazy load monaco, so it will be bundled in async chunk
109 const { default: setup } = await import('../setup/monaco')
110 const { ata, monaco, editorOptions } = await setup()
111 const model = monaco.editor.createModel(code.value, lang, monaco.Uri.parse(`file:///${makeId()}.${ext}`))
112 model.onDidChangeContent(() => code.value = model.getValue())
113 const commonOptions = {
114 automaticLayout: true,
115 readOnly: props.readonly,
116 lineNumbers,
117 minimap: { enabled: false },
118 overviewRulerBorder: false,
119 overviewRulerLanes: 0,
120 padding: { top: 10, bottom: 10 },
121 lineNumbersMinChars: 3,
122 bracketPairColorization: { enabled: false },
123 tabSize: 2,
124 fontSize: 11.5,
125 fontFamily: 'var(--slidev-code-font-family)',
126 scrollBeyondLastLine: false,
127 useInlineViewWhenSpaceIsLimited: false,
128 ...editorOptions,
129 ...props.editorOptions,
130 } satisfies monaco.editor.IStandaloneEditorConstructionOptions & monaco.editor.IDiffEditorConstructionOptions
131
132 if (editorOptions.fontSize != null || props.editorOptions?.fontSize != null)
133 editorFontSize.value = commonOptions.fontSize
134
135 let editableEditor: monaco.editor.IStandaloneCodeEditor
136 if (diff) {
137 const diffModel = monaco.editor.createModel(diff.value, lang, monaco.Uri.parse(`file:///${makeId()}.${ext}`))
138 diffModel.onDidChangeContent(() => code.value = model.getValue())
139 const editor = monaco.editor.createDiffEditor(container.value!, {
140 renderOverviewRuler: false,
141 ...commonOptions,
142 })
143 editor.setModel({
144 original: model,
145 modified: diffModel,
146 })
147 const originalEditor = editor.getOriginalEditor()
148 const modifiedEditor = editor.getModifiedEditor()
149 const onContentSizeChange = () => {
150 const newHeight = Math.max(originalEditor.getContentHeight(), modifiedEditor.getContentHeight()) + 4
151 initialHeight.value ??= newHeight
152 contentHeight.value = newHeight
153 nextTick(() => editor.layout())
154 }
155 originalEditor.onDidContentSizeChange(onContentSizeChange)
156 modifiedEditor.onDidContentSizeChange(onContentSizeChange)
157 editableEditor = modifiedEditor
158 }
159 else {
160 const editor = monaco.editor.create(container.value!, {
161 model,
162 lineDecorationsWidth: 0,
163 ...commonOptions,
164 })
165 editor.onDidContentSizeChange((e) => {
166 const newHeight = e.contentHeight + 4
167 initialHeight.value ??= newHeight
168 contentHeight.value = newHeight
169 nextTick(() => editableEditor.layout())
170 })
171
172 editableEditor = editor
173 }
174 loadTypes.value = () => {
175 stopWatchTypesLoading()
176 import('#slidev/monaco-types')
177 if (props.ata) {
178 ata(editableEditor.getValue())
179 editableEditor.onDidChangeModelContent(debounce(1000, () => {
180 ata(editableEditor.getValue())
181 }))
182 }
183 }
184 const originalLayoutContentWidget = editableEditor.layoutContentWidget.bind(editableEditor)
185 editableEditor.layoutContentWidget = (widget: any) => {
186 originalLayoutContentWidget(widget)
187 const id = widget.getId()
188 if (id === 'editor.contrib.resizableContentHoverWidget') {
189 widget._resizableNode.domNode.style.transform = widget._positionPreference === 1
190 ? /* ABOVE */ `translateY(calc(100% * (var(--slidev-slide-scale) - 1)))`
191 : /* BELOW */ `` // reset
192 }
193 }
194
195 editableEditor.addAction({
196 id: 'slidev-save',
197 label: 'Save',
198 keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS],
199 run: () => {
200 if (!isWritable.value || !import.meta.hot?.send) {
201 console.warn('[Slidev] this monaco editor is not writable, save action is ignored.')
202 return
203 }
204 import.meta.hot.send('slidev:monaco-write', {
205 file: props.writable!,
206 content: editableEditor.getValue(),
207 })
208 },
209 })
210
211 nextTick(() => monaco.editor.remeasureFonts())
212 setTimeout(() => monaco.editor.remeasureFonts(), 1000)
213 })
214 </script>
215
216 <template>
217 <div class="relative slidev-monaco-container">
218 <div class="relative slidev-monaco-container-inner" :style="{ height }">
219 <div ref="container" class="absolute inset-0.5" />
220 </div>
221 <CodeRunner
222 v-if="props.runnable"
223 v-model="code"
224 :lang="lang"
225 :autorun="props.autorun"
226 :show-output-at="props.showOutputAt"
227 :height="props.outputHeight"
228 :font-size="outputFontSize"
229 :highlight-output="props.highlightOutput"
230 :runner-options="props.runnerOptions"
231 />
232 </div>
233 </template>
234
235 <style>
236 div[widgetid='messageoverlay'] {
237 transform: translateY(calc(100% * (var(--slidev-slide-scale) - 1)));
238 }
239
240 .slidev-monaco-container {
241 position: relative;
242 margin: var(--slidev-code-margin);
243 line-height: var(--slidev-code-line-height);
244 border-radius: var(--slidev-code-radius);
245 background: var(--slidev-code-background);
246 }
247
248 .slidev-monaco-container-inner {
249 padding: var(--slidev-code-padding);
250 }
251
252 .slidev-monaco-container .monaco-editor {
253 --monaco-monospace-font: var(--slidev-code-font-family);
254 --vscode-editor-background: var(--slidev-code-background);
255 --vscode-editorGutter-background: var(--slidev-code-background);
256 }
257
258 /** Revert styles */
259 .slidev-monaco-container .monaco-editor a {
260 border-bottom: none;
261 }
262
263 .slidev-monaco-container .monaco-editor a:hover {
264 border-bottom: none;
265 }
266 </style>
267
267 lines Plain Text