Skip to content
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
3 changes: 3 additions & 0 deletions src/Repl.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface Props {
autoResize?: boolean
showCompileOutput?: boolean
showImportMap?: boolean
showTsConfig?: boolean
clearConsole?: boolean
sfcOptions?: SFCOptions
layout?: 'horizontal' | 'vertical'
Expand All @@ -31,6 +32,7 @@ const props = withDefaults(defineProps<Props>(), {
autoResize: true,
showCompileOutput: true,
showImportMap: true,
showTsConfig: true,
clearConsole: true,
ssr: false,
previewOptions: () => ({
Expand Down Expand Up @@ -69,6 +71,7 @@ store.init()
provide('store', store)
provide('autoresize', props.autoResize)
provide('import-map', toRef(props, 'showImportMap'))
provide('tsconfig', toRef(props, 'showTsConfig'))
provide('clear-console', toRef(props, 'clearConsole'))
provide('preview-options', props.previewOptions)
</script>
Expand Down
27 changes: 19 additions & 8 deletions src/editor/FileSelector.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Store, importMapFile } from '../store'
import { Store, importMapFile, tsconfigFile } from '../store'
import { computed, inject, ref, VNode, Ref } from 'vue'

const store = inject('store') as Store
Expand All @@ -15,10 +15,14 @@ const pending = ref<boolean | string>(false)
* This is a display name so it should always strip off the `src/` prefix.
*/
const pendingFilename = ref('Comp.vue')
const showImportMap = inject('import-map') as Ref<boolean>
const showTsConfig = inject<Ref<boolean>>('tsconfig')
const showImportMap = inject<Ref<boolean>>('import-map')
const files = computed(() =>
Object.entries(store.state.files)
.filter(([name, file]) => name !== importMapFile && !file.hidden)
.filter(
([name, file]) =>
name !== importMapFile && name !== tsconfigFile && !file.hidden
)
.map(([name]) => name)
)

Expand Down Expand Up @@ -121,9 +125,7 @@ function horizontalScroll(e: WheelEvent) {
@click="store.setActive(file)"
@dblclick="i > 0 && editFileName(file)"
>
<span class="label">{{
file === importMapFile ? 'Import Map' : stripSrcPrefix(file)
}}</span>
<span class="label">{{ stripSrcPrefix(file) }}</span>
<span v-if="i > 0" class="remove" @click.stop="store.deleteFile(file)">
<svg class="icon" width="12" height="12" viewBox="0 0 24 24">
<line stroke="#999" x1="18" y1="6" x2="6" y2="18"></line>
Expand All @@ -147,9 +149,18 @@ function horizontalScroll(e: WheelEvent) {
</template>
<button class="add" @click="startAddFile">+</button>

<div v-if="showImportMap" class="import-map-wrapper">
<div class="import-map-wrapper">
<div
class="file import-map"
v-if="showTsConfig"
class="file"
:class="{ active: store.state.activeFile.filename === tsconfigFile }"
@click="store.setActive(tsconfigFile)"
>
<span class="label">tsconfig.json</span>
</div>
<div
v-if="showImportMap"
class="file"
:class="{ active: store.state.activeFile.filename === importMapFile }"
@click="store.setActive(importMapFile)"
>
Expand Down
94 changes: 62 additions & 32 deletions src/monaco/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,67 @@ export function loadWasm() {
return onigasm.loadWASM(onigasmWasm)
}

let disposeVue: undefined | (() => void)
export async function reloadVue(store: Store) {
disposeVue?.()

const worker = editor.createWebWorker<any>({
moduleId: 'vs/language/vue/vueWorker',
label: 'vue',
host: createJsDelivrDtsHost(
!store.vueVersion
? {}
: {
vue: store.vueVersion,
'@vue/compiler-core': store.vueVersion,
'@vue/compiler-dom': store.vueVersion,
'@vue/compiler-sfc': store.vueVersion,
'@vue/compiler-ssr': store.vueVersion,
'@vue/reactivity': store.vueVersion,
'@vue/runtime-core': store.vueVersion,
'@vue/runtime-dom': store.vueVersion,
'@vue/shared': store.vueVersion,
},
(filename, text) => {
getOrCreateModel(Uri.file(filename), undefined, text)
}
),
createData: {
tsconfig: store.getTsConfig?.() || {},
},
})
const languageId = ['vue', 'javascript', 'typescript']
const getSyncUris = () =>
Object.keys(store.state.files).map((filename) =>
Uri.parse(`file:///${filename}`)
)
const { dispose: disposeMarkers } = volar.editor.activateMarkers(
worker,
languageId,
'vue',
getSyncUris,
editor
)
const { dispose: disposeAutoInsertion } = volar.editor.activateAutoInsertion(
worker,
languageId,
getSyncUris,
editor
)
const { dispose: disposeProvides } = await volar.languages.registerProvides(
worker,
languageId,
getSyncUris,
languages
)

disposeVue = () => {
disposeMarkers()
disposeAutoInsertion()
disposeProvides()
}
}

export function loadMonacoEnv(store: Store) {
;(self as any).MonacoEnvironment = {
async getWorker(_: any, label: string) {
Expand All @@ -75,36 +136,5 @@ export function loadMonacoEnv(store: Store) {
languages.register({ id: 'vue', extensions: ['.vue'] })
languages.register({ id: 'javascript', extensions: ['.js'] })
languages.register({ id: 'typescript', extensions: ['.ts'] })
languages.onLanguage('vue', async () => {
const worker = editor.createWebWorker<any>({
moduleId: 'vs/language/vue/vueWorker',
label: 'vue',
host: createJsDelivrDtsHost(
!store.vueVersion
? {}
: {
vue: store.vueVersion,
'@vue/compiler-core': store.vueVersion,
'@vue/compiler-dom': store.vueVersion,
'@vue/compiler-sfc': store.vueVersion,
'@vue/compiler-ssr': store.vueVersion,
'@vue/reactivity': store.vueVersion,
'@vue/runtime-core': store.vueVersion,
'@vue/runtime-dom': store.vueVersion,
'@vue/shared': store.vueVersion,
},
(filename, text) => {
getOrCreateModel(Uri.file(filename), undefined, text)
}
),
})
const languageId = ['vue', 'javascript', 'typescript']
const getSyncUris = () =>
Object.keys(store.state.files).map((filename) =>
Uri.parse(`file:///${filename}`)
)
volar.editor.activateMarkers(worker, languageId, 'vue', getSyncUris, editor)
volar.editor.activateAutoInsertion(worker, languageId, getSyncUris, editor)
volar.languages.registerProvides(worker, languageId, getSyncUris, languages)
})
languages.onLanguage('vue', () => reloadVue(store))
}
56 changes: 31 additions & 25 deletions src/monaco/vue.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,38 @@ import type * as monaco from 'monaco-editor-core'
import * as ts from 'typescript'
import { Config, resolveConfig } from '@vue/language-service'
import { createLanguageService } from '@volar/monaco/worker'
import createTypeScriptService from 'volar-service-typescript'
import createTypeScriptService, { IDtsHost } from 'volar-service-typescript'

self.onmessage = () => {
worker.initialize((ctx: monaco.worker.IWorkerContext) => {
const compilerOptions: ts.CompilerOptions = {
...ts.getDefaultCompilerOptions(),
allowJs: true,
checkJs: true,
jsx: ts.JsxEmit.Preserve,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
allowImportingTsExtensions: true,
}
const baseConfig: Config = {
services: {
typescript: createTypeScriptService({ dtsHost: ctx.host }),
},
}
worker.initialize(
(
ctx: monaco.worker.IWorkerContext<IDtsHost>,
{ tsconfig }: { tsconfig: any }
) => {
const { options: compilerOptions } = ts.convertCompilerOptionsFromJson(
tsconfig?.compilerOptions || {},
''
)

return createLanguageService({
workerContext: ctx,
config: resolveConfig(baseConfig, compilerOptions, {}, ts as any),
typescript: {
module: ts as any,
compilerOptions,
},
})
})
const baseConfig: Config = {
services: {
typescript: createTypeScriptService({ dtsHost: ctx.host }),
},
}

return createLanguageService({
workerContext: ctx,
config: resolveConfig(
baseConfig,
compilerOptions,
tsconfig.vueCompilerOptions || {},
ts as any
),
typescript: {
module: ts as any,
compilerOptions,
},
})
}
)
}
52 changes: 50 additions & 2 deletions src/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { version, reactive, watchEffect } from 'vue'
import { version, reactive, watchEffect, watch } from 'vue'
import * as defaultCompiler from 'vue/compiler-sfc'
import { compileFile } from './transform'
import { utoa, atou } from './utils'
Expand All @@ -9,10 +9,12 @@ import {
} from 'vue/compiler-sfc'
import { OutputModes } from './output/types'
import { Selection } from 'monaco-editor-core'
import { reloadVue } from './monaco/env'

const defaultMainFile = 'src/App.vue'

export const importMapFile = 'import-map.json'
export const tsconfigFile = 'tsconfig.json'

const welcomeCode = `
<script setup>
Expand All @@ -27,6 +29,21 @@ const msg = ref('Hello World!')
</template>
`.trim()

const tsconfig = {
compilerOptions: {
allowJs: true,
checkJs: true,
jsx: 'Preserve',
target: 'ESNext',
module: 'ESNext',
moduleResolution: 'Bundler',
allowImportingTsExtensions: true,
},
vueCompilerOptions: {
target: 3.3,
},
}

export class File {
filename: string
code: string
Expand Down Expand Up @@ -89,6 +106,7 @@ export interface Store {
deleteFile: (filename: string) => void
renameFile: (oldFilename: string, newFilename: string) => void
getImportMap: () => any
getTsConfig?: () => any
initialShowOutput: boolean
initialOutputMode: OutputModes
}
Expand Down Expand Up @@ -152,6 +170,7 @@ export class ReplStore implements Store {
})

this.initImportMap()
this.initTsConfig()
}

// don't start compiling until the options are set
Expand All @@ -161,6 +180,12 @@ export class ReplStore implements Store {
(errs) => (this.state.errors = errs)
)
)

watch(
() => this.state.files[tsconfigFile]?.code,
() => reloadVue(this)
)

this.state.errors = []
for (const file in this.state.files) {
if (file !== defaultMainFile) {
Expand All @@ -171,6 +196,27 @@ export class ReplStore implements Store {
}
}

private initTsConfig() {
if (!this.state.files[tsconfigFile]) {
this.setTsConfig(tsconfig)
}
}

setTsConfig(config: any) {
this.state.files[tsconfigFile] = new File(
tsconfigFile,
JSON.stringify(config, undefined, 2)
)
}

getTsConfig() {
try {
return JSON.parse(this.state.files[tsconfigFile].code)
} catch {
return {}
}
}

setActive(filename: string) {
this.state.activeFile = this.state.files[filename]
}
Expand Down Expand Up @@ -378,7 +424,9 @@ function setFile(
// prefix user files with src/
// for cleaner Volar path completion when using Monaco editor
const normalized =
filename !== importMapFile && !filename.startsWith('src/')
filename !== importMapFile &&
filename !== tsconfigFile &&
!filename.startsWith('src/')
? `src/${filename}`
: filename
files[normalized] = new File(normalized, content)
Expand Down
2 changes: 2 additions & 0 deletions test/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const App = {
: `${location.origin}/src/vue-server-renderer-dev-proxy`,
}))

console.log(store)

watchEffect(() => history.replaceState({}, '', store.serialize()))

// setTimeout(() => {
Expand Down