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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
refactor: refactor locale service (#426)
白熱81724eae15ee
diff --git a/package.json b/package.jsonindex 15ed301b36..cb7973f4be 100644--- a/package.json+++ b/package.json@@ -10,7 +10,6 @@"dev": "turbo dev:demo --filter ./examples/univer-doc-ts --filter ./examples/univer-sheet-ts --filter ./examples/univer-slide-ts","build": "turbo esbuild","build:demo": "turbo esbuild:demo",- "clean": "npm cache clean --force && node scripts/clean.mjs && pnpm install","prepare": "husky install","pre-commit": "lint-staged","lint": "eslint --cache packages/**/src/**/*.{tsx,ts}",diff --git a/packages/base-docs/src/doc-plugin.ts b/packages/base-docs/src/doc-plugin.tsindex 25d37311f9..e27d63d8c0 100644--- a/packages/base-docs/src/doc-plugin.ts+++ b/packages/base-docs/src/doc-plugin.ts@@ -95,7 +95,7 @@ export class DocPlugin extends Plugin {}initialize(): void {- this._localeService.getLocale().load({+ this._localeService.load({enUS,});diff --git a/packages/base-render/src/basics/tools.ts b/packages/base-render/src/basics/tools.tsindex 484b026305..f7cf82f7da 100644--- a/packages/base-render/src/basics/tools.ts+++ b/packages/base-render/src/basics/tools.ts@@ -246,9 +246,10 @@ export function getFontStyleString(textStyle?: IStyleBase, localeService?: Local// };// }- const defaultFont = (localeService?.get('defaultFont') || 'Arial') as string;+ // TODO: @jikkai @DR-Univer should read default font from configuration, not from locale service+ const defaultFont = 'Arial';- const defaultFontSize = (localeService?.get('defaultFontSize') || 14) as number;+ const defaultFontSize = 14;// const { fontList, defaultFontSize } = fontLocale;diff --git a/packages/base-render/src/components/docs/block/paragraph/bullet.ts b/packages/base-render/src/components/docs/block/paragraph/bullet.tsindex 3248716cf6..e58b697c4e 100644--- a/packages/base-render/src/components/docs/block/paragraph/bullet.ts+++ b/packages/base-render/src/components/docs/block/paragraph/bullet.ts@@ -20,13 +20,13 @@ export function dealWidthBullet(const list = lists[listId];if (!list || !list.nestingLevel) {- return getDefaultBulletSke(listId, listLevelAncestors?.[nestingLevel]?.startIndexItem, localeService);+ return getDefaultBulletSke(listId, listLevelAncestors?.[nestingLevel]?.startIndexItem);}const nesting = list.nestingLevel[nestingLevel];if (!nesting) {- return getDefaultBulletSke(listId, listLevelAncestors?.[nestingLevel]?.startIndexItem, localeService);+ return getDefaultBulletSke(listId, listLevelAncestors?.[nestingLevel]?.startIndexItem);}const bulletSke = _getBulletSke(@@ -40,17 +40,14 @@ export function dealWidthBullet(return bulletSke;}-export function getDefaultBulletSke(- listId: string,- startIndex: number = 1,- localeService?: LocaleService-): IDocumentSkeletonBullet {+export function getDefaultBulletSke(listId: string, startIndex: number = 1): IDocumentSkeletonBullet {return {listId,symbol: '\u25CF', // symbol 列表的内容ts: {- ff: (localeService?.get('defaultFont') || 'Arial') as string,- fs: (localeService?.get('defaultFontSize') || 9) as number,+ // TODO: @jikkai @DR-Univer should read default font from configuration, not from locale service+ ff: 'Arial',+ fs: 9,}, // 文字样式startIndexItem: startIndex,bBox: {diff --git a/packages/base-sheets/src/base-sheets-plugin.ts b/packages/base-sheets/src/base-sheets-plugin.tsindex e0a6a6385d..aa3a05deb0 100644--- a/packages/base-sheets/src/base-sheets-plugin.ts+++ b/packages/base-sheets/src/base-sheets-plugin.ts@@ -27,7 +27,7 @@ export class SheetPlugin extends Plugin {}override onRendered(): void {- this._localeService.getLocale().load({+ this._localeService.load({enUS,});}diff --git a/packages/base-slides/src/slide-plugin.ts b/packages/base-slides/src/slide-plugin.tsindex 44eadcd043..4bd2295dcc 100644--- a/packages/base-slides/src/slide-plugin.ts+++ b/packages/base-slides/src/slide-plugin.ts@@ -31,7 +31,7 @@ export class SlidePlugin extends Plugin {}initialize(): void {- this._localeService.getLocale().load({+ this._localeService.load({enUS,});this.initCanvasEngine();diff --git a/packages/base-ui/src/base-ui-plugin.ts b/packages/base-ui/src/base-ui-plugin.tsindex 2b09b099d4..de57ad7a03 100644--- a/packages/base-ui/src/base-ui-plugin.ts+++ b/packages/base-ui/src/base-ui-plugin.ts@@ -49,7 +49,7 @@ export class UIPlugin extends Plugin {this._config = Object.assign(DEFAULT_SLIDE_PLUGIN_DATA, config);- this._localeService.getLocale().load({+ this._localeService.load({enUS,});}diff --git a/packages/base-ui/src/views/App.tsx b/packages/base-ui/src/views/App.tsxindex c3448c0e08..6eab98cb24 100644--- a/packages/base-ui/src/views/App.tsx+++ b/packages/base-ui/src/views/App.tsx@@ -76,8 +76,8 @@ export function App(props: IUniverAppProps) {messageService.setContainer(portalContainer);const subscriptions = [- localeService.getLocale().locale$.subscribe((locale) => {- locale && setLocale(localeService.getLocales() as unknown as ILocale);+ localeService.localeChanged$.subscribe(() => {+ setLocale(localeService.getLocales() as unknown as ILocale);}),themeService.currentTheme$.subscribe((theme) => {themeInstance.setTheme(mountContainer, theme);diff --git a/packages/base-ui/src/views/app.module.less b/packages/base-ui/src/views/app.module.lessindex d5cf552150..2aa2fb1116 100644--- a/packages/base-ui/src/views/app.module.less+++ b/packages/base-ui/src/views/app.module.less@@ -1,6 +1,7 @@.app {&-layout {height: 100%;+ -webkit-font-smoothing: antialiased;background-color: rgb(var(--bg-color));display: flex;flex-direction: column;diff --git a/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsx b/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsxindex a86bc7c662..6b557535f4 100644--- a/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsx+++ b/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsx@@ -5,7 +5,6 @@ import { useDependency } from '@wendellhu/redi/react-bindings';import { useEffect, useState } from 'react';import { Subscription } from 'rxjs';-import { ComponentManager } from '../../../Common';import { CustomLabel } from '../../../components/custom-label/CustomLabel';import { Menu } from '../../../components/menu/Menu';import {@@ -21,7 +20,6 @@ import styles from './index.module.less';export function ToolbarItem(props: IDisplayMenuItem<IMenuItem>) {const localeService = useDependency(LocaleService);const commandService = useDependency(ICommandService);- const componentManager = useDependency(ComponentManager);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst [value, setValue] = useState<any>();@@ -65,7 +63,7 @@ export function ToolbarItem(props: IDisplayMenuItem<IMenuItem>) {const { tooltip, shortcut, icon, title, label, id } = props;- const tooltipTitle = localeService?.t(tooltip) + (shortcut ? ` (${shortcut})` : '');+ const tooltipTitle = localeService.t(tooltip ?? '') + (shortcut ? ` (${shortcut})` : '');function renderSelectorType() {const { selections } = props as IDisplayMenuItem<IMenuSelectorItem>;diff --git a/packages/core/src/services/locale/locale.service.ts b/packages/core/src/services/locale/locale.service.tsindex 22e5881d89..953f629101 100644--- a/packages/core/src/services/locale/locale.service.ts+++ b/packages/core/src/services/locale/locale.service.ts@@ -1,4 +1,4 @@-import { BehaviorSubject, Observable } from 'rxjs';+import { Subject } from 'rxjs';import { Nullable } from '../../common/type-utils';import { Disposable, toDisposable } from '../../shared/lifecycle';@@ -14,11 +14,11 @@ import { LocaleType } from '../../types/enum/locale-type';** @private*/-function getValue(locale: ILocales[LocaleType], key: string): Nullable<string | object> {+function getValue(locale: ILocales[LocaleType], key: string): Nullable<string> {if (!locale) return;try {- if (locale[key]) return locale[key];+ if (locale[key]) return locale[key] as string;// eslint-disable-next-line @typescript-eslint/no-explicit-anyreturn key.split('.').reduce((a: any, b: string) => a[b], locale);@@ -32,68 +32,16 @@ function getValue(locale: ILocales[LocaleType], key: string): Nullable<string |* This service provides i18n and timezone / location features to other modules.*/export class LocaleService extends Disposable {- currentLocale: LocaleType = LocaleType.EN_US;+ private currentLocale: LocaleType = LocaleType.EN_US;- locales: ILocales | null = null;+ private locales: ILocales | null = null;- readonly locale$: Observable<Nullable<LocaleType>>;-- private readonly _locale$ = new BehaviorSubject<Nullable<LocaleType>>(undefined);+ localeChanged$ = new Subject<void>();constructor() {super();- this.locale$ = this._locale$.asObservable();-- this.disposeWithMe(toDisposable(() => this._locale$.complete()));- }-- t(key?: string): string | number {- return this.get(key) ?? key ?? '';- }-- setLocale(locale: LocaleType): void {- this.initialize(locale);- this._locale$.next(locale);- }-- getLocale() {- return this;- }-- initialize(locale: Nullable<LocaleType>) {- this.currentLocale = locale || LocaleType.EN_US;- }-- /**- * Get the formatted message by key- *- * @example- * ```ts- * Locale.get('name')- * ```- *- * @param key - The string representing key in Locale data file- * @returns Get the translation corresponding to the Key- */- get(key: string | undefined): Nullable<string | number> {- const { locales, currentLocale } = this;- if (!locales) {- throw new Error();- }-- if (key) {- return getValue(locales[currentLocale], key) as string;- }- }-- getObject<T>(key: string): T {- const { locales, currentLocale } = this;- if (!locales) {- throw new Error();- }-- return getValue(locales[currentLocale], key) as unknown as T;+ this.disposeWithMe(toDisposable(() => this.localeChanged$.complete()));}/**@@ -103,31 +51,22 @@ export class LocaleService extends Disposable {* @returns void**/- load(locales: ILocales): void {+ load(locales: ILocales) {this.locales = Tools.deepMerge(this.locales ?? {}, locales);}- /**- * change Locale- *- * @example- * Change to Chinese- * ```ts- * Locale.change(LocaleType.ZH)- * ```- *- * @param locale - Locale Type, see {@link LocaleType}- *- */- change(locale: LocaleType): void {- this.currentLocale = locale;+ t(key: string): string {+ if (!this.locales) throw new Error('Locale not initialized');++ return getValue(this.locales[this.currentLocale], key) ?? key;}- getCurrentLocale() {- return this.currentLocale;+ setLocale(locale: LocaleType): void {+ this.currentLocale = locale;+ this.localeChanged$.next();}getLocales() {- return this?.locales?.[this.currentLocale];+ return this.locales?.[this.currentLocale];}}diff --git a/packages/sheets-plugin-debugger/src/debugger-plugin.ts b/packages/sheets-plugin-debugger/src/debugger-plugin.tsindex d37aa5a3ee..b5bfc0a3b0 100644--- a/packages/sheets-plugin-debugger/src/debugger-plugin.ts+++ b/packages/sheets-plugin-debugger/src/debugger-plugin.ts@@ -20,7 +20,7 @@ export class DebuggerPlugin extends Plugin {}initialize(): void {- this._localeService.getLocale().load({+ this._localeService.load({enUS,});diff --git a/packages/sheets-plugin-find/src/find-plugin.ts b/packages/sheets-plugin-find/src/find-plugin.tsindex 164ac3f333..6cb57cadfb 100644--- a/packages/sheets-plugin-find/src/find-plugin.ts+++ b/packages/sheets-plugin-find/src/find-plugin.ts@@ -54,7 +54,7 @@ export class FindPlugin extends Plugin {// }initialize(): void {- this._localeService.getLocale().load({+ this._localeService.load({enUS,});diff --git a/packages/sheets-plugin-formula/src/formula-plugin.ts b/packages/sheets-plugin-formula/src/formula-plugin.tsindex e0f4e2d272..640be02ed8 100644--- a/packages/sheets-plugin-formula/src/formula-plugin.ts+++ b/packages/sheets-plugin-formula/src/formula-plugin.ts@@ -22,7 +22,7 @@ export class FormulaPlugin extends Plugin {}initialize(): void {- this._localeService.getLocale().load({+ this._localeService.load({enUS,});diff --git a/packages/sheets-plugin-import-xlsx/src/import-xlsx-plugin.tsx b/packages/sheets-plugin-import-xlsx/src/import-xlsx-plugin.tsxindex ac9aba5596..abee9b92d1 100644--- a/packages/sheets-plugin-import-xlsx/src/import-xlsx-plugin.tsx+++ b/packages/sheets-plugin-import-xlsx/src/import-xlsx-plugin.tsx@@ -25,7 +25,7 @@ export class ImportXlsxPlugin extends Plugin {/*** load more Locale object*/- this._localeService.getLocale().load({+ this._localeService.load({enUS,});diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt-modal-controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt-modal-controller.tsindex d107ebd0c3..a52faa3933 100644--- a/packages/sheets-plugin-numfmt/src/controllers/numfmt-modal-controller.ts+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt-modal-controller.ts@@ -58,7 +58,7 @@ export class NumfmtModalController {name: NUMFMT_PLUGIN_NAME + FormatContent.name,props: {data: this.resetContentData(CURRENCYDETAIL),- input: this._localeService.getLocale().get('format.decimalPlaces'),+ input: this._localeService.t('format.decimalPlaces'),onClick: (value: string) => console.dir(value),onChange: (value: string) => console.dir(value),},@@ -121,10 +121,9 @@ export class NumfmtModalController {}resetContentData(data: any[]): any[] {- const locale = this._localeService.getLocale();for (let i = 0; i < data.length; i++) {if (data[i].locale) {- data[i].label = locale.get(data[i].locale);+ data[i].label = this._localeService.t(data[i].locale);}}return data;@@ -132,12 +131,11 @@ export class NumfmtModalController {// 渲染所需数据resetModalData(): void {- const locale = this._localeService.getLocale();this._modalData.forEach((item) => {- item.title = locale.get(item.locale) as string;+ item.title = this._localeService.t(item.locale);if (item.group && item.group.length) {item.group.forEach((ele) => {- ele.label = locale.get(ele.locale) as string;+ ele.label = this._localeService.t(ele.locale);});}});diff --git a/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts b/packages/sheets-plugin-numfmt/src/numfmt-plugin.tsindex ae90066e1a..4452e3f3f9 100644--- a/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts+++ b/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts@@ -34,7 +34,7 @@ export class NumfmtPlugin extends Plugin {this.registerExtension();this._numfmtController = this._injector.get(NumfmtController);this._numfmtModalController = this._injector.get(NumfmtModalController);- this._localeService.getLocale().load({ enUS });+ this._localeService.load({ enUS });// actionRegister.add(this._numfmtActionExtensionFactory);}diff --git a/packages/ui-plugin-docs/src/controllers/app-ui-controller.ts b/packages/ui-plugin-docs/src/controllers/app-ui-controller.tsindex 3ecfba0f84..eaef603d7c 100644--- a/packages/ui-plugin-docs/src/controllers/app-ui-controller.ts+++ b/packages/ui-plugin-docs/src/controllers/app-ui-controller.ts@@ -23,7 +23,7 @@ export class AppUIController {**/changeLocale = (locale: string) => {- this._localeService.getLocale().change(locale as LocaleType);+ this._localeService.setLocale(locale as LocaleType);};getDocContainerController() {diff --git a/packages/ui-plugin-docs/src/controllers/doc-container-ui-controller.ts b/packages/ui-plugin-docs/src/controllers/doc-container-ui-controller.tsindex 1801108fa7..c56afda13c 100644--- a/packages/ui-plugin-docs/src/controllers/doc-container-ui-controller.ts+++ b/packages/ui-plugin-docs/src/controllers/doc-container-ui-controller.ts@@ -42,7 +42,7 @@ export class DocContainerUIController {**/changeLocale = (locale: string) => {- this._localeService.getLocale().change(locale as LocaleType);+ this._localeService.setLocale(locale as LocaleType);};getContentRef() {diff --git a/packages/ui-plugin-docs/src/doc-ui-plugin.ts b/packages/ui-plugin-docs/src/doc-ui-plugin.tsindex c528e7d3d6..5020cd7450 100644--- a/packages/ui-plugin-docs/src/doc-ui-plugin.ts+++ b/packages/ui-plugin-docs/src/doc-ui-plugin.ts@@ -20,7 +20,7 @@ export class DocUIPlugin extends Plugin {) {super(DOC_UI_PLUGIN_NAME);- this._localeService.getLocale().load({+ this._localeService.load({enUS,});diff --git a/packages/ui-plugin-sheets/src/controllers/clipboard/clipboard.controller.ts b/packages/ui-plugin-sheets/src/controllers/clipboard/clipboard.controller.tsindex a728616bc1..6c26e41348 100644--- a/packages/ui-plugin-sheets/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/clipboard/clipboard.controller.ts@@ -194,7 +194,7 @@ export class SheetClipboardController extends Disposable {if (maxConfig && endRow * endColumn > maxConfig) {self._messageService.show({type: MessageType.Error,- content: self._localService.get('clipboard.paste.exceedMaxCells') as string,+ content: self._localService.t('clipboard.paste.exceedMaxCells'),}); // TODO: show error inforeturn false;}diff --git a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.tsindex 03903173b4..96a726fd0c 100644--- a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts@@ -49,7 +49,7 @@ export class SheetUIPlugin extends Plugin {) {super(SHEET_UI_PLUGIN_NAME);- this._localeService.getLocale().load({+ this._localeService.load({enUS,});}diff --git a/packages/ui-plugin-slides/src/controllers/app-ui-controller.ts b/packages/ui-plugin-slides/src/controllers/app-ui-controller.tsindex 88d6a21676..2379e752ee 100644--- a/packages/ui-plugin-slides/src/controllers/app-ui-controller.ts+++ b/packages/ui-plugin-slides/src/controllers/app-ui-controller.ts@@ -29,7 +29,7 @@ export class AppUIController {**/changeLocale = (locale: string) => {- this._localeService.getLocale().change(locale as LocaleType);+ this._localeService.setLocale(locale as LocaleType);};getSlideContainerController() {diff --git a/packages/ui-plugin-slides/src/controllers/slide-container-ui-controller.ts b/packages/ui-plugin-slides/src/controllers/slide-container-ui-controller.tsindex b1f9c72877..e1c27d558e 100644--- a/packages/ui-plugin-slides/src/controllers/slide-container-ui-controller.ts+++ b/packages/ui-plugin-slides/src/controllers/slide-container-ui-controller.ts@@ -74,7 +74,7 @@ export class SlideContainerUIController {**/changeLocale = (locale: string) => {- this._localeService.getLocale().change(locale as LocaleType);+ this._localeService.setLocale(locale as LocaleType);};getContentRef() {diff --git a/packages/ui-plugin-slides/src/slide-ui-plugin.ts b/packages/ui-plugin-slides/src/slide-ui-plugin.tsindex 9d03c77296..b6a847ac8b 100644--- a/packages/ui-plugin-slides/src/slide-ui-plugin.ts+++ b/packages/ui-plugin-slides/src/slide-ui-plugin.ts@@ -35,7 +35,7 @@ export class SlideUIPlugin extends Plugin {}override onStarting(): void {- this._localeService.getLocale().load({+ this._localeService.load({enUS,});}diff --git a/scripts/clean-empty.sh b/scripts/clean-empty.shdeleted file mode 100755index 6e750989a9..0000000000--- a/scripts/clean-empty.sh+++ /dev/null@@ -1,35 +0,0 @@-#!/bin/bash--# Function to check if a directory only contains node_modules-function contains_only_node_modules {- # Check if the directory contains only one subdirectory- if [ $(find "$1" -mindepth 1 -maxdepth 1 -type d | wc -l) -eq 1 ]; then- # Check if the subdirectory is named "node_modules"- if [ -d "$1/node_modules" ]; then- return 0- fi- fi-- return 1-}--# Prompt for the parent folder path-read -p "Enter the parent folder path: " parent_folder_path--# Check if the parent folder exists-if [ ! -d "$parent_folder_path" ]; then- echo "Parent folder does not exist."- exit 1-fi--# Loop through the child folders-for child_folder in "$parent_folder_path"/*; do- if [ -d "$child_folder" ]; then- # Check if the child folder only contains node_modules- if contains_only_node_modules "$child_folder"; then- # Delete the child folder- rm -rf "$child_folder"- echo "Deleted folder: $child_folder"- fi- fi-done\ No newline at end of filediff --git a/scripts/clean.mjs b/scripts/clean.mjsdeleted file mode 100644index 7864a1409f..0000000000--- a/scripts/clean.mjs+++ /dev/null@@ -1,25 +0,0 @@-import fs from 'node:fs';-import { join, resolve } from 'node:path';-import { fileURLToPath } from 'node:url';--const __dirname = fileURLToPath(import.meta.url);--function deleteNodeModules(directory) {- const files = fs.readdirSync(directory);-- files.forEach((file) => {- const filePath = join(directory, file);- const stat = fs.statSync(filePath);-- if (stat.isDirectory()) {- if (['node_modules', 'lib', 'dist', '.turbo', 'coverage', 'local'].includes(file)) {- console.log('Deleting:', filePath);- fs.rmSync(filePath, { recursive: true });- } else {- deleteNodeModules(filePath);- }- }- });-}--deleteNodeModules(resolve(__dirname, '../'));