From 331ea8cdcd5e9c4575b738f9878efe7a1d2aaf25 Mon Sep 17 00:00:00 2001 From: taiyuuki Date: Fri, 27 Sep 2024 20:18:00 +0800 Subject: [PATCH] fix: nls plugin for monaco editor v0.52.0 --- README.md | 2 + plugins/index.ts | 1 + plugins/nls/index.ts | 307 +++++++++++------------------------------- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src/auto-imports.d.ts | 5 + src/editor/themes.ts | 6 + src/pages/index.vue | 4 +- src/static/index.ts | 1 + tsconfig.json | 4 + 10 files changed, 105 insertions(+), 229 deletions(-) diff --git a/README.md b/README.md index f5ee9ca..2946ad9 100644 --- a/README.md +++ b/README.md @@ -81,4 +81,6 @@ pnpm tauri signer generate -w ./~/.tauri/myapp.key 然后创建密码文件~/.tauri/password.key,内容就是输入的那个密码,如果留空了,创建一个空白文件即可。 +然后将myapp.key.pub的文件内容写入src-tauri/tauriconf.json中的`plugin.updater.pubkey`字段。 + 最后运行`pnpm tauri:build`打包。 \ No newline at end of file diff --git a/plugins/index.ts b/plugins/index.ts index 72176aa..3ae4b68 100644 --- a/plugins/index.ts +++ b/plugins/index.ts @@ -1,6 +1,7 @@ import { resolve } from 'node:path' import type { RouteRecord } from 'vue-router' import type { PluginEntry } from '@quasar/app-vite/types/configuration/build' + import nlsPlugin, { Languages } from './nls' import zh_hans from './nls/zh-hans.json' diff --git a/plugins/nls/index.ts b/plugins/nls/index.ts index 79df0e9..4c7089b 100644 --- a/plugins/nls/index.ts +++ b/plugins/nls/index.ts @@ -2,7 +2,6 @@ import fs from 'node:fs' import path from 'node:path' import type { Plugin } from 'vite' import MagicString from 'magic-string' -import type { Plugin as EsbuildPlugin } from 'esbuild' export enum Languages { bg = 'bg', @@ -38,7 +37,7 @@ export interface Options { * @param options 替换语言包 * @returns */ -export function esbuildPluginMonacoEditorNls(options: Options): EsbuildPlugin { +export function esbuildPluginMonacoEditorNls(options: Options) { options = Object.assign({ locale: Languages.en_gb }, options) const CURRENT_LOCALE_DATA = getLocalizeMapping(options.locale, options.localeData) @@ -97,7 +96,7 @@ export default function(options: Options): Plugin { const re = /monaco-editor[/\\]esm[/\\](.+)(?=\.js)/ if (re.exec(filepath) && code.includes('localize(')) { let path = RegExp.$1 - path = path.replaceAll('\\', '/') + path = path.replace(/\\/g, '/') code = code.replace(/localize\(/g, `localize('${path}', `) return { @@ -130,7 +129,7 @@ function transformLocalizeFuncCode( const re = /monaco-editor[/\\]esm[/\\](.+)(?=\.js)/ if (re.exec(filepath)) { let path = RegExp.$1 - path = path.replaceAll('\\', '/') + path = path.replace(/\\/g, '/') // if (filepath.includes('contextmenu')) { // console.log(filepath); @@ -164,87 +163,54 @@ function getLocalizeMapping(locale: Languages, localeData: Record | */ function getLocalizeCode(CURRENT_LOCALE_DATA: string) { return ` - /* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - let isPseudo = typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0 - const DEFAULT_TAG = 'i-default' - function _format(message, args) { - let result - if (args.length === 0) { - result = message - } else { - result = message.replace(/{(\\d+)}/g, (match, rest) => { - const index = rest[0] - const arg = args[index] - let result = match - if (typeof arg === 'string') { - result = arg - } else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) { - result = String(arg) - } - - return result - }) - } - if (isPseudo) { - - // FF3B and FF3D is the Unicode zenkaku representation for [ and ] - result = \`\uFF3B\${result.replace(/[aeiou]/g, '$&$&')}\uFF3D\` - } - - return result - } - function findLanguageForModule(config, name) { - let result = config[name] - if (result) { - return result - } - result = config['*'] - if (result) { - return result - } - - return null - } - function endWithSlash(path) { - if (path.charAt(path.length - 1) === '/') { - return path - } - - return \`\${path}/\` - } - async function getMessagesFromTranslationsService(translationServiceUrl, language, name) { - const url = \`\${endWithSlash(translationServiceUrl) + endWithSlash(language)}vscode/\${endWithSlash(name)}\` - const res = await fetch(url) - if (res.ok) { - const messages = await res.json() - - return messages - } - throw new Error(\`\${res.status} - \${res.statusText}\`) - } - function createScopedLocalize(scope) { - return function(idx, defaultValue) { - const restArgs = Array.prototype.slice.call(arguments, 2) - - return _format(scope[idx], restArgs) - } - } - function createScopedLocalize2(scope) { - return (idx, defaultValue, ...args) => ({ - value: _format(scope[idx], args), - original: _format(defaultValue, args), - }) - } - - // export function localize(data, message, ...args) { - // return _format(message, args); - // } - + /*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// eslint-disable-next-line local/code-import-patterns +import { getNLSLanguage, getNLSMessages } from './nls.messages.js'; +// eslint-disable-next-line local/code-import-patterns +export { getNLSLanguage, getNLSMessages } from './nls.messages.js'; +const isPseudo = getNLSLanguage() === 'pseudo' || (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0); +function _format(message, args) { + let result; + if (args.length === 0) { + result = message; + } + else { + result = message.replace(/\\{(\\d+)\\}/g, (match, rest) => { + const index = rest[0]; + const arg = args[index]; + let result = match; + if (typeof arg === 'string') { + result = arg; + } + else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) { + result = String(arg); + } + return result; + }); + } + if (isPseudo) { + // FF3B and FF3D is the Unicode zenkaku representation for [ and ] + result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D'; + } + return result; +} +/** + * @skipMangle + */ +// export function localize(data /* | number when built */, message /* | null when built */, ...args) { +// if (typeof data === 'number') { +// return _format(lookupMessage(data, message), args); +// } +// return _format(message, args); +// } // ------------------------invoke---------------------------------------- export function localize(path, data, defaultMessage, ...args) { + if (typeof data === 'number') { + return _format(lookupMessage(data, message), args); + } var key = typeof data === 'object' ? data.key : data; var data = ${CURRENT_LOCALE_DATA} || {}; var message = (data[path] || data?.contents?.[path] || {})[key]; @@ -254,147 +220,38 @@ function getLocalizeCode(CURRENT_LOCALE_DATA: string) { return _format(message, args); } // ------------------------invoke---------------------------------------- - - /** - * @skipMangle - */ - export function localize2(data, message, ...args) { - const original = _format(message, args) - - return { - value: original, - original, - } - } - - /** - * @skipMangle - */ - export function getConfiguredDefaultLocale(_) { - - // This returns undefined because this implementation isn't used and is overwritten by the loader - // when loaded. - return undefined - } - - /** - * @skipMangle - */ - export function setPseudoTranslation(value) { - isPseudo = value - } - - /** - * Invoked in a built product at run-time - * @skipMangle - */ - export function create(key, data) { - var _a - - return { - localize: createScopedLocalize(data[key]), - localize2: createScopedLocalize2(data[key]), - getConfiguredDefaultLocale: (_a = data.getConfiguredDefaultLocale) !== null && _a !== void 0 ? _a : _ => undefined, - } - } - - /** - * Invoked by the loader at run-time - * @skipMangle - */ - export function load(name, req, load, config) { - var _a - const pluginConfig = (_a = config['vs/nls']) !== null && _a !== void 0 ? _a : {} - if (!name || name.length === 0) { - - // TODO: We need to give back the mangled names here - return load({ - localize: localize, - localize2: localize2, - getConfiguredDefaultLocale: () => { - var _a - - return (_a = pluginConfig.availableLanguages) === null || _a === void 0 ? void 0 : _a['*'] - }, - }) - } - const language = pluginConfig.availableLanguages ? findLanguageForModule(pluginConfig.availableLanguages, name) : null - const useDefaultLanguage = language === null || language === DEFAULT_TAG - let suffix = '.nls' - if (!useDefaultLanguage) { - suffix = \`\${suffix}.\${language}\` - } - const messagesLoaded = messages => { - if (Array.isArray(messages)) { - messages.localize = createScopedLocalize(messages) - messages.localize2 = createScopedLocalize2(messages) - } else { - messages.localize = createScopedLocalize(messages[name]) - messages.localize2 = createScopedLocalize2(messages[name]) - } - messages.getConfiguredDefaultLocale = () => { - var _a - - return (_a = pluginConfig.availableLanguages) === null || _a === void 0 ? void 0 : _a['*'] - } - load(messages) - } - if (typeof pluginConfig.loadBundle === 'function') { - pluginConfig.loadBundle(name, language, (err, messages) => { - - // We have an error. Load the English default strings to not fail - if (err) { - req([\`\${name}.nls\`], messagesLoaded) - } else { - messagesLoaded(messages) - } - }) - } else if (pluginConfig.translationServiceUrl && !useDefaultLanguage) { - (async() => { - var _a - try { - const messages = await getMessagesFromTranslationsService(pluginConfig.translationServiceUrl, language, name) - - return messagesLoaded(messages) - } catch (err) { - - // Language is already as generic as it gets, so require default messages - if (!language.includes('-')) { - console.error(err) - - return req([\`\${name}.nls\`], messagesLoaded) - } - try { - - // Since there is a dash, the language configured is a specific sub-language of the same generic language. - // Since we were unable to load the specific language, try to load the generic language. Ex. we failed to find a - // Swiss German (de-CH), so try to load the generic German (de) messages instead. - const genericLanguage = language.split('-')[0] - const messages = await getMessagesFromTranslationsService(pluginConfig.translationServiceUrl, genericLanguage, name); - - // We got some messages, so we configure the configuration to use the generic language for this session. - (_a = pluginConfig.availableLanguages) !== null && _a !== void 0 ? _a : pluginConfig.availableLanguages = {} - pluginConfig.availableLanguages['*'] = genericLanguage - - return messagesLoaded(messages) - } catch (err) { - console.error(err) - - return req([\`\${name}.nls\`], messagesLoaded) - } - } - })() - } else { - req([name + suffix], messagesLoaded, err => { - if (suffix === '.nls') { - console.error('Failed trying to load default language strings', err) - - return - } - console.error(\`Failed to load message bundle for language \${language}. Falling back to the default language:\`, err) - req([\`\${name}.nls\`], messagesLoaded) - }) - } - } +/** + * Only used when built: Looks up the message in the global NLS table. + * This table is being made available as a global through bootstrapping + * depending on the target context. + */ +function lookupMessage(index, fallback) { + const message = getNLSMessages()?.[index]; + if (typeof message !== 'string') { + if (typeof fallback === 'string') { + return fallback; + } + throw new Error(\`!!! NLS MISSING: \${index} !!!\`); + } + return message; +} +/** + * @skipMangle + */ +export function localize2(data /* | number when built */, originalMessage, ...args) { + let message; + if (typeof data === 'number') { + message = lookupMessage(data, originalMessage); + } + else { + message = originalMessage; + } + const value = _format(message, args); + return { + value, + original: originalMessage === message ? value : _format(originalMessage, args) + }; +} + ` } diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index ddbf4c1..9718bb5 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -936,7 +936,7 @@ checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" [[package]] name = "eb-code" -version = "0.6.2" +version = "0.6.3" dependencies = [ "anyhow", "dirs", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b754561..a28708d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eb-code" -version = "0.6.2" +version = "0.6.3" description = "Ebook Code is a epub editor" authors = ["you"] edition = "2021" diff --git a/src/auto-imports.d.ts b/src/auto-imports.d.ts index 2b2903d..37c7171 100644 --- a/src/auto-imports.d.ts +++ b/src/auto-imports.d.ts @@ -3,6 +3,7 @@ // @ts-nocheck // noinspection JSUnusedGlobalSymbols // Generated by unplugin-auto-import +// biome-ignore lint: disable export {} declare global { const AxiosInstance: typeof import('axios')['AxiosInstance'] @@ -52,6 +53,7 @@ declare global { const onServerPrefetch: typeof import('vue')['onServerPrefetch'] const onUnmounted: typeof import('vue')['onUnmounted'] const onUpdated: typeof import('vue')['onUpdated'] + const onWatcherCleanup: typeof import('vue')['onWatcherCleanup'] const provide: typeof import('vue')['provide'] const reactive: typeof import('vue')['reactive'] const readonly: typeof import('vue')['readonly'] @@ -72,12 +74,15 @@ declare global { const useAttrs: typeof import('vue')['useAttrs'] const useCssModule: typeof import('vue')['useCssModule'] const useCssVars: typeof import('vue')['useCssVars'] + const useId: typeof import('vue')['useId'] const useLink: typeof import('vue-router')['useLink'] const useMeta: typeof import('quasar')['useMeta'] + const useModel: typeof import('vue')['useModel'] const useQuasar: typeof import('quasar')['useQuasar'] const useRoute: typeof import('vue-router')['useRoute'] const useRouter: typeof import('vue-router')['useRouter'] const useSlots: typeof import('vue')['useSlots'] + const useTemplateRef: typeof import('vue')['useTemplateRef'] const watch: typeof import('vue')['watch'] const watchEffect: typeof import('vue')['watchEffect'] const watchPostEffect: typeof import('vue')['watchPostEffect'] diff --git a/src/editor/themes.ts b/src/editor/themes.ts index 92b9556..781a2ee 100644 --- a/src/editor/themes.ts +++ b/src/editor/themes.ts @@ -10,12 +10,17 @@ const themes = [ 'dark-plus', 'dracula-soft', 'dracula', + 'everforest-dark', + 'everforest-light', 'github-dark-default', 'github-dark-dimmed', + 'github-dark-high-contrast', 'github-dark', 'github-light-default', + 'github-light-high-contrast', 'github-light', 'houston', + 'laserwave', 'light-plus', 'material-theme-darker', 'material-theme-lighter', @@ -29,6 +34,7 @@ const themes = [ 'nord', 'one-dark-pro', 'one-light', + 'plastic', 'poimandres', 'red', 'rose-pine-dawn', diff --git a/src/pages/index.vue b/src/pages/index.vue index 810be3b..3e2f674 100644 --- a/src/pages/index.vue +++ b/src/pages/index.vue @@ -1,7 +1,7 @@