From f9fedcd1ca56a6965c9617a16d2fba834f8a44a1 Mon Sep 17 00:00:00 2001 From: Johnson Chu Date: Wed, 5 Jul 2023 13:32:01 +0800 Subject: [PATCH] feat: respect browser language close #123 --- src/monaco/env.ts | 16 +++++++++++++++- src/monaco/vue.worker.ts | 11 ++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/monaco/env.ts b/src/monaco/env.ts index d6e28d99..1f53753a 100644 --- a/src/monaco/env.ts +++ b/src/monaco/env.ts @@ -7,7 +7,6 @@ import onigasmWasm from 'onigasm/lib/onigasm.wasm?url' import { editor, languages, Uri } from 'monaco-editor-core' import * as volar from '@volar/monaco' import { Store } from '../store' -import { createJsDelivrDtsHost } from 'volar-service-typescript' import { getOrCreateModel } from './utils' import type { CreateData } from './vue.worker' @@ -76,15 +75,30 @@ export class WorkerHost { } } +async function fetchJson(url: string) { + try { + const res = await fetch(url); + if (res.status === 200) { + return await res.json(); + } + } catch { + // ignore + } +} + let disposeVue: undefined | (() => void) export async function reloadVue(store: Store) { disposeVue?.() + const locale = navigator.language.toLowerCase() + const tsLocalized = await fetchJson(`https://cdn.jsdelivr.net/npm/typescript/lib/${locale}/diagnosticMessages.generated.json`) const worker = editor.createWebWorker({ moduleId: 'vs/language/vue/vueWorker', label: 'vue', host: new WorkerHost(), createData: { + locale: locale, + tsLocalized: tsLocalized, tsconfig: store.getTsConfig?.() || {}, dependencies: !store.vueVersion ? {} diff --git a/src/monaco/vue.worker.ts b/src/monaco/vue.worker.ts index 099e95be..aa2bee0f 100644 --- a/src/monaco/vue.worker.ts +++ b/src/monaco/vue.worker.ts @@ -8,6 +8,8 @@ import { createLanguageService, createLanguageHost, createServiceEnvironment } f import type { WorkerHost } from './env' export interface CreateData { + locale: string + tsLocalized: any tsconfig: { compilerOptions?: ts.CompilerOptions vueCompilerOptions?: Partial @@ -19,7 +21,7 @@ self.onmessage = () => { worker.initialize( ( ctx: monaco.worker.IWorkerContext, - { tsconfig, dependencies }: CreateData + { tsconfig, dependencies, locale, tsLocalized }: CreateData ) => { const { options: compilerOptions } = ts.convertCompilerOptionsFromJson( tsconfig?.compilerOptions || {}, @@ -30,6 +32,13 @@ self.onmessage = () => { const jsDelivrFs = createJsDelivrFs(ctx.host.onFetchCdnFile) const jsDelivrUriResolver = createJsDelivrUriResolver('/node_modules', dependencies) + if (locale) { + env.locale = locale + } + if (tsLocalized) { + host.getLocalizedDiagnosticMessages = () => tsLocalized + } + decorateServiceEnvironment(env, jsDelivrUriResolver, jsDelivrFs) return createLanguageService(