Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat: add string interpolation support for locale service (#1362)

白熱8f338badd297
diff --git a/packages/core/src/services/locale/__tests__/locale.service.spec.ts b/packages/core/src/services/locale/__tests__/locale.service.spec.ts
new file mode 100644
index 0000000000..8054ae7062
--- /dev/null
+++ b/packages/core/src/services/locale/__tests__/locale.service.spec.ts
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { LocaleService } from '../locale.service';
+import { LocaleType } from '../../../types/enum/locale-type';
+
+describe('LocaleService', () => {
+ let localeService: LocaleService;
+ const testLocales = {
+ [LocaleType.ZH_CN]: {
+ greeting: '你好',
+ farewell: '再见',
+ nested: {
+ welcome: '欢迎光临',
+ },
+ withParams: '你好, {0}!',
+ },
+ [LocaleType.EN_US]: {
+ greeting: 'Hello',
+ farewell: 'Goodbye',
+ nested: {
+ welcome: 'Welcome',
+ },
+ withParams: 'Hello, {0}!',
+ },
+ };
+
+ beforeEach(() => {
+ localeService = new LocaleService();
+ localeService.load(testLocales);
+ });
+
+ it('should translate simple keys', () => {
+ expect(localeService.t('greeting')).toBe('你好');
+ localeService.setLocale(LocaleType.EN_US);
+ expect(localeService.t('greeting')).toBe('Hello');
+ });
+
+ it('should translate nested keys', () => {
+ expect(localeService.t('nested.welcome')).toBe('欢迎光临');
+ localeService.setLocale(LocaleType.EN_US);
+ expect(localeService.t('nested.welcome')).toBe('Welcome');
+ });
+
+ it('should handle parameters within translations', () => {
+ expect(localeService.t('withParams', '世界')).toBe('你好, 世界!');
+ localeService.setLocale(LocaleType.EN_US);
+ expect(localeService.t('withParams', 'World')).toBe('Hello, World!');
+ });
+
+ it('should return the key if translation is not found', () => {
+ expect(localeService.t('nonExistentKey')).toBe('nonExistentKey');
+ });
+
+ it('should throw an error if locales are not initialized', () => {
+ const newLocaleService = new LocaleService();
+ const t = () => {
+ newLocaleService.t('greeting');
+ };
+ expect(t).toThrowError('Locale not initialized');
+ });
+});
diff --git a/packages/core/src/services/locale/locale.service.ts b/packages/core/src/services/locale/locale.service.ts
index 0d280cf38a..21bd9ecc0e 100644
--- a/packages/core/src/services/locale/locale.service.ts
+++ b/packages/core/src/services/locale/locale.service.ts
@@ -16,33 +16,11 @@
import { Subject } from 'rxjs';
-import type { Nullable } from '../../common/type-utils';
import { Disposable, toDisposable } from '../../shared/lifecycle';
-import type { ILocales } from '../../shared/locale';
+import type { ILanguagePack, ILocales } from '../../shared/locale';
import { Tools } from '../../shared/tools';
import { LocaleType } from '../../types/enum/locale-type';
-/**
- * get value from Locale object and key
- * @param locale - A specified language pack
- * @param key - Specify key
- * @returns Get the translation corresponding to the Key
- *
- * @private
- */
-function getValue(locale: ILocales[LocaleType], key: string): Nullable<string> {
- if (!locale) return;
-
- try {
- if (locale[key]) return locale[key] as string;
-
- return key.split('.').reduce((a: any, b: string) => a[b], locale);
- } catch (error) {
- console.warn('Key %s not found', key);
- return key;
- }
-}
-
/**
* This service provides i18n and timezone / location features to other modules.
*/
@@ -63,20 +41,69 @@ export class LocaleService extends Disposable {
* Load more locales after init
*
* @param locales - Locale object
- * @returns void
*
*/
load(locales: ILocales) {
this._locales = Tools.deepMerge(this._locales ?? {}, locales);
}
- t = (key: string): string => {
+ /**
+ * Translate a key to the current locale
+ * @param {string} key the key to translate
+ * @param {string[]} args optional arguments to replace in the translated string
+ * @returns {string} the translated string
+ * @example
+ * const locales = {
+ * [LocaleType.EN_US]: {
+ * foo: {
+ * bar: 'Hello'
+ * }
+ * }
+ * t('foo.bar') => 'Hello'
+ *
+ * @example
+ * const locales = {
+ * [LocaleType.EN_US]: {
+ * foo: {
+ * bar: 'Hello {0}'
+ * }
+ * }
+ * t('foo.bar', 'World') => 'Hello World'
+ */
+ t = (key: string, ...args: string[]): string => {
if (!this._locales) throw new Error('Locale not initialized');
- return getValue(this._locales[this._currentLocale], key) ?? key;
+ function resolveKeyPath(obj: ILanguagePack | ILanguagePack[], keys: string[]): string | ILanguagePack | ILanguagePack[] | null {
+ const currentKey = keys.shift();
+
+ if (currentKey && obj && currentKey in obj) {
+ const nextObj = (obj as ILanguagePack)[currentKey];
+
+ if (keys.length > 0 && (typeof nextObj === 'object' || Array.isArray(nextObj))) {
+ return resolveKeyPath(nextObj as ILanguagePack, keys);
+ } else {
+ return nextObj;
+ }
+ }
+
+ return null;
+ }
+
+ const keys = key.split('.');
+ const resolvedValue = resolveKeyPath(this._locales[this._currentLocale], keys);
+
+ if (typeof resolvedValue === 'string') {
+ let result = resolvedValue;
+ args.forEach((arg, index) => {
+ result = result.replace(`{${index}}`, arg);
+ });
+ return result;
+ } else {
+ return key;
+ }
};
- setLocale(locale: LocaleType): void {
+ setLocale(locale: LocaleType) {
this._currentLocale = locale;
this.localeChanged$.next();
}
@@ -84,8 +111,4 @@ export class LocaleService extends Disposable {
getLocales() {
return this._locales?.[this._currentLocale];
}
-
- getCurrentLocale() {
- return this._currentLocale;
- }
}