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
fix(sheets-formula-ui): align range selector text in RTL (#7647)
siam5f7119324339
diff --git a/packages/docs-ui/src/views/RichTextEditor.tsx b/packages/docs-ui/src/views/RichTextEditor.tsxindex b22d5d9463..c55612c34a 100644--- a/packages/docs-ui/src/views/RichTextEditor.tsx+++ b/packages/docs-ui/src/views/RichTextEditor.tsx@@ -18,14 +18,24 @@ import type { IDocumentData } from '@univerjs/core';import type { CSSProperties, ReactNode, RefObject } from 'react';import type { Editor, IEditorCanvasStyle } from '../services/editor/editor';import type { IKeyboardEventConfig } from './rich-text-editor/hooks';-import { BuildTextUtils, createInternalEditorID, generateRandomId, getPlainText, ICommandService, IUniverInstanceService } from '@univerjs/core';+import {+ BuildTextUtils,+ createInternalEditorID,+ generateRandomId,+ getPlainText,+ HorizontalAlign,+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ RichTextBuilder,+ Tools,+} from '@univerjs/core';import { borderClassName, clsx } from '@univerjs/design';import { DocSkeletonManagerService } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';import { useDependency, useEvent, useObservable } from '@univerjs/ui';import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { map, merge, startWith } from 'rxjs';-import { IEditorService } from '../services/editor/editor-manager.service';import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';import { createEditorUndoRedoKeyboardConfig, useEditorClickOutside, useIsFocusing, useKeyboardEvent, useResize } from './rich-text-editor/hooks';import { useEditor } from './rich-text-editor/hooks/use-editor';@@ -79,9 +89,10 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {noStyle,canvasStyle,} = props;- const editorService = useDependency(IEditorService);+const commandService = useDependency(ICommandService);const univerInstanceService = useDependency(IUniverInstanceService);+ const localeService = useDependency(LocaleService);const onFocusChange = useEvent(_onFocusChange);const onClickOutside = useEvent(_onClickOutside);const [height, setHeight] = useState(defaultHeight);@@ -96,6 +107,7 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {isSingle,canvasStyle,});+ const direction = useObservable(localeService.direction$, localeService.getDirection());const renderManagerService = useDependency(IRenderManagerService);const renderer = renderManagerService.getRenderUnitById(editorId);const selectionIsFocusing = useIsFocusing(editorId);@@ -147,6 +159,18 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {checkScrollBar();});+ useEffect(() => {+ if (!editor) {+ return;+ }++ const documentData = RichTextBuilder.create(Tools.deepClone(editor.getDocumentData()))+ .align({ horizontal: direction === 'rtl' ? HorizontalAlign.RIGHT : HorizontalAlign.LEFT })+ .getData();++ editor.setDocumentData(documentData, editor.getSelectionRanges());+ }, [direction, editor]);+useEffect(() => {const data = editor?.getDocumentData();onFocusChange?.(isFocusing, getPlainText(data?.body?.dataStream ?? ''));diff --git a/packages/docs-ui/src/views/__tests__/RichTextEditor.spec.tsx b/packages/docs-ui/src/views/__tests__/RichTextEditor.spec.tsxnew file mode 100644index 0000000000..03aa4137ec--- /dev/null+++ b/packages/docs-ui/src/views/__tests__/RichTextEditor.spec.tsx@@ -0,0 +1,247 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 type { Root } from 'react-dom/client';+import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ Disposable,+ DocumentDataModel,+ HorizontalAlign,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LocalUndoRedoService,+ RichTextBuilder,+ ThemeService,+ Tools,+ UniverInstanceService,+} from '@univerjs/core';+import {+ DocSelectionManagerService,+ DocSkeletonManagerService,+ DocStateEmitService,+ RichTextEditingMutation,+ SetTextSelectionsOperation,+} from '@univerjs/docs';+import { IRenderManagerService } from '@univerjs/engine-render';+import {+ IPlatformService,+ IShortcutService,+ IUIRuntimeScopeService,+ PlatformService,+ RediContext,+ ShortcutService,+ UIRuntimeScopeService,+} from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ReplaceSnapshotCommand } from '../../commands/commands/replace-content.command';+import { EditorService, IEditorService } from '../../services/editor/editor-manager.service';+import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';+import { RichTextEditor } from '../RichTextEditor';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++// Canvas layout is the platform boundary; editor state and commands use their real providers.+class TestEditorRender extends Disposable {+ readonly selection = {+ onBlur$: new Subject(),+ onFocus$: new Subject(),+ onPaste$: new Subject(),+ onInput$: new Subject(),+ onKeydown$: new Subject(),+ onCompositionupdate$: new Subject(),+ onCompositionend$: new Subject(),+ textSelectionInner$: new Subject(),+ isFocusing: false,+ };++ readonly components = new Map();+ readonly canvas = document.createElement('canvas');+ readonly engine = {+ canvasColorService: {},+ mount: (container: HTMLDivElement) => container.appendChild(this.canvas),+ getCanvas: () => ({ getCanvasEle: () => this.canvas }),+ };++ with(token: unknown) {+ if (token === DocSelectionRenderService) {+ return this.selection;+ }+ if (token === DocSkeletonManagerService) {+ return {+ getViewModel: () => undefined,+ getSkeleton: () => ({ getActualSize: () => ({ actualWidth: 100, actualHeight: 20 }) }),+ };+ }+ throw new Error(`Unexpected render service: ${String(token)}`);+ }++ override dispose() {+ Object.values(this.selection).forEach((value) => {+ if (value instanceof Subject) {+ value.complete();+ }+ });+ this.canvas.remove();+ super.dispose();+ }+}++class TestRenderManagerService extends Disposable {+ private readonly _renders = new Map<string, TestEditorRender>();++ createRender(id: string) {+ const render = new TestEditorRender();+ this._renders.set(id, render);+ this.disposeWithMe(render);+ return render;+ }++ getRenderUnitById(id: string) {+ return this._renders.get(id);+ }++ removeRender(id: string) {+ this._renders.get(id)?.dispose();+ this._renders.delete(id);+ }++ override dispose() {+ this._renders.clear();+ super.dispose();+ }+}++function createEditorTestBed() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);+ injector.add([LocaleService]);+ injector.add([ThemeService]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([IEditorService, { useClass: EditorService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ const commandService = injector.get(ICommandService);+ commandService.registerCommand(ReplaceSnapshotCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: {} });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ const initialSnapshot = {+ ...RichTextBuilder.create().insertText('A1:B2').getData(),+ id: 'rich-text-editor-test',+ };+ const model = new DocumentDataModel(Tools.deepClone(initialSnapshot));+ (injector.get(IUniverInstanceService) as UniverInstanceService).__addUnit(model);+ return { injector, localeService, model, initialSnapshot };+}++describe('RichTextEditor alignment', () => {+ let container: HTMLDivElement;+ let root: Root;+ let testBed: ReturnType<typeof createEditorTestBed>;++ beforeEach(() => {+ vi.useFakeTimers();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ testBed = createEditorTestBed();+ });++ afterEach(() => {+ act(() => root.unmount());+ testBed.injector.dispose();+ container.remove();+ vi.clearAllTimers();+ vi.useRealTimers();+ });++ function renderEditor(isSingle: boolean) {+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <RichTextEditor+ editorId={testBed.model.getUnitId()}+ initialValue={testBed.initialSnapshot}+ isSingle={isSingle}+ />+ </RediContext.Provider>+ );+ });+ }++ it.each([['ltr', HorizontalAlign.LEFT], ['rtl', HorizontalAlign.RIGHT]] as const)(+ 'aligns the document for initial %s direction without changing its input',+ (direction, alignment) => {+ const { localeService, model, initialSnapshot } = testBed;+ localeService.setDirection(direction);+ const original = Tools.deepClone(initialSnapshot);+ renderEditor(true);+ expect(model.getSnapshot().documentStyle?.renderConfig?.horizontalAlign).toBe(alignment);+ expect(model.getPlainText()).toBe('A1:B2');+ expect(initialSnapshot).toEqual(original);+ }+ );++ it.each([true, false])('updates mounted alignment through commands and retains selection (isSingle=%s)', (isSingle) => {+ const { injector, localeService, model } = testBed;+ renderEditor(isSingle);+ const editor = injector.get(IEditorService).getEditor(model.getUnitId())!;+ const selections = [{ startOffset: 1, endOffset: 3, collapsed: false, isActive: true, segmentId: '' }];+ const selectionManager = injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: editor.getEditorId(), subUnitId: editor.getEditorId() });+ selectionManager.__TEST_ONLY_add(selections);+ const previous = Tools.deepClone(model.getSnapshot());+ const beforeCommand = injector.get(ICommandService).beforeCommandExecuted((command) => {+ if (command.id === ReplaceSnapshotCommand.id) {+ // The builder must not mutate live document state before its command executes.+ expect(model.getSnapshot()).toEqual(previous);+ expect(command.params).toMatchObject({ textRanges: selections });+ }+ });+ act(() => localeService.setDirection('rtl'));+ beforeCommand.dispose();+ expect(model.getSnapshot().documentStyle?.renderConfig?.horizontalAlign).toBe(HorizontalAlign.RIGHT);+ expect(editor.getSelectionRanges()).toEqual(selections);+ act(() => localeService.setDirection('ltr'));+ expect(model.getSnapshot().documentStyle?.renderConfig?.horizontalAlign).toBe(HorizontalAlign.LEFT);+ expect(editor.getSelectionRanges()).toEqual(selections);+ expect(model.getPlainText()).toBe('A1:B2');+ });+});diff --git a/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelector.tsx b/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelector.tsxindex 359c750dfe..8f75596eaf 100644--- a/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelector.tsx+++ b/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelector.tsx@@ -20,7 +20,6 @@ import type { ISetSelectionsOperationParams } from '@univerjs/sheets';import type { LocaleKey } from '../../locale/types';import type { IRangeSelectorProps } from './index';import { ICommandService, LocaleService, RichTextBuilder } from '@univerjs/core';-import { clsx } from '@univerjs/design';import { IEditorService, RichTextEditor } from '@univerjs/docs-ui';import { SelectRangeIcon } from '@univerjs/icons';import { SetSelectionsOperation } from '@univerjs/sheets';@@ -35,6 +34,7 @@ import { verifyRange } from './utils/verify-range';export function MobileRangeSelector(props: IRangeSelectorProps) {const [editor, setEditor] = useState<Editor | null>(null);const {+ className,onVerify,selectorRef,unitId,@@ -55,9 +55,9 @@ export function MobileRangeSelector(props: IRangeSelectorProps) {const [focusing, setFocusing] = useState(autoFocus ?? false);const [popupVisible, setPopupVisible] = useState(false);const [rangeSelectorRanges, setRangeSelectorRanges] = useState<IUnitRangeName[]>([]);- const localeService = useDependency(LocaleService);const editorService = useDependency(IEditorService);const commandService = useDependency(ICommandService);+ const localeService = useDependency(LocaleService);const { sequenceNodes } = useRangesHighlight(editor, focusing, unitId, subUnitId);const sequenceNodesRef = useStateRef(sequenceNodes);const blurEditor = useEvent(() => {@@ -125,7 +125,7 @@ export function MobileRangeSelector(props: IRangeSelectorProps) {<RichTextEditorisSingle{...props}- className={clsx(props.className, 'rtl:[&>div]:univer-flex-row-reverse')}+ className={className}preserveHostFocusonFocusChange={(isFocusing, newValue) => {setFocusing(isFocusing);diff --git a/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx b/packages/sheets-formula-ui/src/views/range-selector/__tests__/index.spec.tsxsimilarity index 91%rename from packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsxrename to packages/sheets-formula-ui/src/views/range-selector/__tests__/index.spec.tsxindex 2fca8fbcab..6a9c465af3 100644--- a/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx+++ b/packages/sheets-formula-ui/src/views/range-selector/__tests__/index.spec.tsx@@ -15,6 +15,7 @@*/import type { ICommandInfo, IDisposable, IUnitRangeName } from '@univerjs/core';+import type { IRichTextEditorProps } from '@univerjs/docs-ui';import type { ISelectionWithStyle } from '@univerjs/sheets';import type { Root } from 'react-dom/client';import type { IRangeSelectorInstance } from '../index';@@ -41,9 +42,20 @@ import { GlobalRangeSelectorService } from '../../../services/range-selector.serimport { GlobalRangeSelector } from '../Global';import { RangeSelector } from '../index';import { MobileGlobalRangeSelector } from '../MobileGlobal';+import { MobileRangeSelector } from '../MobileRangeSelector';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let richTextEditorProps: IRichTextEditorProps | undefined;++vi.mock('@univerjs/docs-ui', async (importOriginal) => ({+ ...await importOriginal<typeof import('@univerjs/docs-ui')>(),+ RichTextEditor: (props: IRichTextEditorProps) => {+ richTextEditorProps = props;+ return null;+ },+}));+class TestCommandService {readonly executed: Array<{ id: string; params?: unknown }> = [];@@ -219,6 +231,7 @@ describe('GlobalRangeSelector', () => {let root: Root;beforeEach(() => {+ richTextEditorProps = undefined;container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -231,6 +244,33 @@ describe('GlobalRangeSelector', () => {container.remove();});+ it('does not override the inherited RTL item order on desktop or mobile', async () => {+ const { injector } = createGlobalRangeSelectorTestBed();+ injector.get(LocaleService).setDirection('rtl');++ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <RangeSelector unitId="book-1" subUnitId="sheet-1" />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(richTextEditorProps?.className ?? '').not.toContain('univer-flex-row-reverse');++ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <MobileRangeSelector unitId="book-1" subUnitId="sheet-1" />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(richTextEditorProps?.className ?? '').not.toContain('univer-flex-row-reverse');+ });+it('opens the global selector dialog and resolves the confirmed range', async () => {const { injector, service } = createGlobalRangeSelectorTestBed();const callbackRanges: IUnitRangeName[][] = [];diff --git a/packages/sheets-formula-ui/src/views/range-selector/index.tsx b/packages/sheets-formula-ui/src/views/range-selector/index.tsxindex e8401dd27c..761eadc338 100644--- a/packages/sheets-formula-ui/src/views/range-selector/index.tsx+++ b/packages/sheets-formula-ui/src/views/range-selector/index.tsx@@ -263,6 +263,7 @@ export function stringifyRanges(ranges: IUnitRangeName[]) {export function RangeSelector(props: IRangeSelectorProps) {const [editor, setEditor] = useState<Editor | null>(null);const {+ className,onVerify,selectorRef,unitId,@@ -283,11 +284,11 @@ export function RangeSelector(props: IRangeSelectorProps) {const [focusing, setFocusing] = useState(autoFocus ?? false);const [popupVisible, setPopupVisible] = useState(false);const [rangeSelectorRanges, setRangeSelectorRanges] = useState<IUnitRangeName[]>([]);- const localeService = useDependency(LocaleService);const editorService = useDependency(IEditorService);const { sequenceNodes } = useRangesHighlight(editor, focusing, unitId, subUnitId);const sequenceNodesRef = useStateRef(sequenceNodes);const commandService = useDependency(ICommandService);+ const localeService = useDependency(LocaleService);const blurEditor = useEvent(() => {editor?.setSelectionRanges([]);@@ -355,7 +356,7 @@ export function RangeSelector(props: IRangeSelectorProps) {<RichTextEditorisSingle{...props}- className={clsx(props.className, 'rtl:[&>div]:univer-flex-row-reverse')}+ className={className}preserveHostFocusonFocusChange={(focusing, newValue) => {setFocusing(focusing);