Skip to content

Commit

Permalink
fix: nls plugin for monaco editor v0.52.0
Browse files Browse the repository at this point in the history
  • Loading branch information
taiyuuki committed Sep 27, 2024
1 parent 05153f2 commit 331ea8c
Show file tree
Hide file tree
Showing 10 changed files with 105 additions and 229 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`打包。
1 change: 1 addition & 0 deletions plugins/index.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down
307 changes: 82 additions & 225 deletions plugins/nls/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -164,87 +163,54 @@ function getLocalizeMapping(locale: Languages, localeData: Record<string, any> |
*/
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];
Expand All @@ -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)
};
}
`
}
2 changes: 1 addition & 1 deletion src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
Loading

0 comments on commit 331ea8c

Please sign in to comment.