Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: replace CodeMirror in side editor with Shiki-based textarea #1698

Merged
merged 4 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/editors.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ If you want some high-level management to your slides, we have provided the foll

## Integrated Editor

Slidev comes with an integrated [CodeMirror](https://codemirror.net/) editor that will instantly reload and save the changes to your file.
Slidev comes with an integrated editor that will instantly reload and save the changes to your file.

Click the <carbon-edit class="inline-icon-btn"/> button to open it.

Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"@slidev/parser": "workspace:*",
"@slidev/types": "workspace:*",
"@types/cli-progress": "^3.11.5",
"@types/codemirror": "^5.60.15",
"@types/connect": "^3.4.38",
"@types/debug": "^4.1.12",
"@types/file-saver": "^2.0.7",
Expand Down
60 changes: 60 additions & 0 deletions packages/client/internals/ShikiEditor.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import { getHighlighter } from '#slidev/shiki'

const props = defineProps<{
placeholder?: string
}>()
const content = defineModel<string>({ required: true })

const textareaEl = ref<HTMLTextAreaElement | null>(null)

const html = ref('')

watchEffect((onCleanup) => {
let canceled = false
onCleanup(() => canceled = true)

const c = content.value
async function updateHtml() {
const highlight = await getHighlighter()
if (canceled)
return
const h = await highlight(c, 'markdown')
if (canceled)
return
html.value = h
}
updateHtml()
})
</script>

<template>
<div class="absolute inset-x-3 inset-y-2 font-mono overflow-x-hidden overflow-y-auto">
<div class="relative w-full h-max">
<div class="relative w-full h-max" v-html="html" />
<textarea
ref="textareaEl" v-model="content" :placeholder="props.placeholder"
class="absolute inset-0 resize-none text-transparent bg-transparent focus:outline-none caret-white overflow-y-hidden"
/>
</div>
</div>
</template>

<style scoped>
:deep(code),
textarea {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
'Liberation Mono', 'Courier New', monospace;
font-feature-settings: normal;
font-variation-settings: normal;
font-size: 1em;
text-wrap: wrap;
word-break: break-all;
display: block;
width: 100%;
}
:deep(pre.shiki) {
background-color: transparent;
}
</style>
99 changes: 22 additions & 77 deletions packages/client/internals/SideEditor.vue
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<script setup lang="ts">
import { throttledWatch, useEventListener, watchThrottled } from '@vueuse/core'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { activeElement, editorHeight, editorWidth, isEditorVertical, isInputting, showEditor, isEditorVertical as vertical } from '../state'
import { useCodeMirror } from '../modules/codemirror'
import { throttledWatch, useEventListener } from '@vueuse/core'
import { computed, ref, watch } from 'vue'
import { activeElement, editorHeight, editorWidth, isInputting, showEditor, isEditorVertical as vertical } from '../state'
import { useNav } from '../composables/useNav'
import { useDynamicSlideInfo } from '../composables/useSlideInfo'
import IconButton from './IconButton.vue'
import ShikiEditor from './ShikiEditor.vue'

const props = defineProps<{
resize?: boolean
Expand All @@ -18,8 +18,6 @@ const content = ref('')
const note = ref('')
const dirty = ref(false)
const frontmatter = ref<any>({})
const contentInput = ref<HTMLTextAreaElement>()
const noteInput = ref<HTMLTextAreaElement>()

const { info, update } = useDynamicSlideInfo(currentSlideNo)

Expand Down Expand Up @@ -57,65 +55,22 @@ useEventListener('keydown', (e) => {
}
})

onMounted(async () => {
const contentEditor = await useCodeMirror(
contentInput,
computed({
get() { return content.value },
set(v) {
if (content.value.trim() !== v.trim()) {
content.value = v
dirty.value = true
}
},
}),
{
mode: 'markdown',
lineWrapping: true,
// @ts-expect-error missing types
highlightFormatting: true,
fencedCodeBlockDefaultMode: 'javascript',
},
)

const noteEditor = await useCodeMirror(
noteInput,
computed({
get() { return note.value },
set(v) {
note.value = v
dirty.value = true
},
}),
{
mode: 'markdown',
lineWrapping: true,
// @ts-expect-error missing types
highlightFormatting: true,
fencedCodeBlockDefaultMode: 'javascript',
},
)

watchThrottled(
[tab, vertical, isEditorVertical, editorWidth, editorHeight],
() => {
nextTick(() => {
if (tab.value === 'content')
contentEditor.refresh()
else
noteEditor.refresh()
})
},
{
throttle: 100,
flush: 'post',
},
)
const contentRef = computed({
get() { return content.value },
set(v) {
if (content.value.trim() !== v.trim()) {
content.value = v
dirty.value = true
}
},
})

watch(currentSlideNo, () => {
contentEditor.clearHistory()
noteEditor.clearHistory()
}, { flush: 'post' })
const noteRef = computed({
get() { return note.value },
set(v) {
note.value = v
dirty.value = true
},
})

const handlerDown = ref(false)
Expand Down Expand Up @@ -212,19 +167,9 @@ throttledWatch(
<carbon:close />
</IconButton>
</div>
<div class="overflow-hidden">
<div v-show="tab === 'content'" class="w-full h-full">
<textarea ref="contentInput" placeholder="Create slide content..." />
</div>
<div v-show="tab === 'note'" class="w-full h-full">
<textarea ref="noteInput" placeholder="Write some notes..." />
</div>
<div class="relative overflow-hidden rounded" style="background-color: var(--slidev-code-background)">
<ShikiEditor v-show="tab === 'content'" v-model="contentRef" placeholder="Create slide content..." />
<ShikiEditor v-show="tab === 'note'" v-model="noteRef" placeholder="Write some notes..." />
</div>
</div>
</template>

<style lang="postcss">
.CodeMirror {
@apply px-3 py-2 h-full overflow-hidden bg-transparent font-mono text-sm z-0;
}
</style>
56 changes: 0 additions & 56 deletions packages/client/modules/codemirror.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
"@vueuse/core": "^10.10.0",
"@vueuse/math": "^10.10.0",
"@vueuse/motion": "^2.2.3",
"codemirror": "^5.65.16",
"drauu": "^0.4.0",
"file-saver": "^2.0.5",
"floating-vue": "^5.2.2",
Expand Down
16 changes: 3 additions & 13 deletions packages/client/setup/code-runners.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { createSingletonPromise } from '@antfu/utils'
import type { CodeRunner, CodeRunnerOutput, CodeRunnerOutputText, CodeRunnerOutputs } from '@slidev/types'
import type { CodeToHastOptions } from 'shiki'

import type ts from 'typescript'
import { ref } from 'vue'
import { isDark } from '../logic/dark'
import deps from '#slidev/monaco-run-deps'
import setups from '#slidev/setups/code-runners'

Expand All @@ -15,17 +14,8 @@ export default createSingletonPromise(async () => {
ts: runTypeScript,
}

const { shiki, themes } = await import('#slidev/shiki')
const highlighter = await shiki
const highlight = (code: string, lang: string, options: Partial<CodeToHastOptions> = {}) => highlighter.codeToHtml(code, {
lang,
theme: typeof themes === 'string'
? themes
: isDark.value
? themes.dark || 'vitesse-dark'
: themes.light || 'vitesse-light',
...options,
})
const { getHighlighter } = await import('#slidev/shiki')
const highlight = await getHighlighter()

const run = async (code: string, lang: string, options: Record<string, unknown>): Promise<CodeRunnerOutputs> => {
try {
Expand Down
2 changes: 1 addition & 1 deletion packages/client/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const isScreenVertical = computed(() => windowSize.height.value - windowS
export const fullscreen = useFullscreen(isClient ? document.body : null)

export const activeElement = useActiveElement()
export const isInputting = computed(() => ['INPUT', 'TEXTAREA'].includes(activeElement.value?.tagName || '') || activeElement.value?.classList.contains('CodeMirror-code'))
export const isInputting = computed(() => ['INPUT', 'TEXTAREA'].includes(activeElement.value?.tagName || ''))
export const isOnFocus = computed(() => ['BUTTON', 'A'].includes(activeElement.value?.tagName || ''))

export const currentCamera = useLocalStorage<string>('slidev-camera', 'default', { listenToStorageChanges: false })
Expand Down
6 changes: 1 addition & 5 deletions packages/client/styles/code.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ html.dark:root {
/* Shiki */
html.dark .shiki {
color: var(--shiki-dark, inherit);
background: var(--shiki-dark-bg, inherit);
--twoslash-popup-bg: var(--shiki-dark-bg, inherit);
}

Expand Down Expand Up @@ -82,8 +83,3 @@ html:not(.dark) .shiki span {
.katex :before {
border-color: currentColor;
}

/* CodeMirror */
.CodeMirror pre.CodeMirror-placeholder {
opacity: 0.4;
}
1 change: 0 additions & 1 deletion packages/create-theme/template/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
},
"dependencies": {
"@slidev/types": "^0.49.11",
"codemirror-theme-vars": "^0.1.2",
"prism-theme-vars": "^0.2.5"
},
"devDependencies": {
Expand Down
2 changes: 0 additions & 2 deletions packages/create-theme/template/styles/prism.css
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
@import 'prism-theme-vars/base.css';
@import 'codemirror-theme-vars/base.css';
@import 'prism-theme-vars/to-codemirror.css';

:root {
--prism-font-family: var(--slidev-code-font-family);
Expand Down
16 changes: 15 additions & 1 deletion packages/slidev/node/virtual/shiki.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const templateShiki: VirtualModuleTemplate = {
id: '/@slidev/shiki',
getContent: async ({ clientRoot, roots }) => {
const options = await loadShikiSetups(clientRoot, roots)
const langs = await resolveLangs(options.langs || ['javascript', 'typescript', 'html', 'css'])
const langs = await resolveLangs(options.langs || ['markdown', 'vue', 'javascript', 'typescript', 'html', 'css'])
const resolvedThemeOptions = 'themes' in options
? {
themes: Object.fromEntries(await Promise.all(Object.entries(options.themes)
Expand Down Expand Up @@ -70,6 +70,20 @@ export const templateShiki: VirtualModuleTemplate = {
` langs: [${langsInit.join(',')}],`,
` loadWasm: import('${await resolveImportUrl('shiki/wasm')}'),`,
'})',

'let highlight',
'export async function getHighlighter() {',
' if (highlight) return highlight',
' const highlighter = await shiki',
' highlight = (code, lang, options) => highlighter.codeToHtml(code, {',
' lang,',
` theme: ${JSON.stringify(themeOptionsNames.theme)},`,
` themes: ${JSON.stringify(themeOptionsNames.themes)},`,
' defaultColor: false,',
' ...options,',
Copy link
Member Author

@KermanX KermanX Jun 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved here from:

const highlight = (code: string, lang: string, options: Partial<CodeToHastOptions> = {}) => highlighter.codeToHtml(code, {
lang,
theme: typeof themes === 'string'
? themes
: isDark.value
? themes.dark || 'vitesse-dark'
: themes.light || 'vitesse-light',
...options,
})

It now uses Shiki's dual theme feature. I am not sure why it wasn't used.

' })',
' return highlight',
'}',
)

return lines.join('\n')
Expand Down
12 changes: 1 addition & 11 deletions packages/slidev/node/vite/extendConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,7 @@ const INCLUDE_GLOBAL = [
'yaml',
]

const INCLUDE_LOCAL = [
...INCLUDE_GLOBAL,

'codemirror',
'codemirror/mode/javascript/javascript',
'codemirror/mode/css/css',
'codemirror/mode/markdown/markdown',
'codemirror/mode/xml/xml',
'codemirror/mode/htmlmixed/htmlmixed',
'codemirror/addon/display/placeholder',
].map(i => `@slidev/cli > @slidev/client > ${i}`)
const INCLUDE_LOCAL = INCLUDE_GLOBAL.map(i => `@slidev/cli > @slidev/client > ${i}`)

// @keep-sorted
const EXCLUDE_GLOBAL = [
Expand Down
Loading
Loading