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(sheet): range selector and editor (#2748)
Univer15b1d8e9fbd0
diff --git a/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.tsindex b5428bfbbc..f9fd4620da 100644--- a/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.ts@@ -15,7 +15,7 @@*/import type { DocumentDataModel, ICommandInfo } from '@univerjs/core';-import { Disposable, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { Disposable, ICommandService, isInternalEditorID, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import type { Documents, IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, RenderComponentType } from '@univerjs/engine-render';import { CURSOR_TYPE, DocumentEditArea, ITextSelectionRenderManager, PageLayoutType, Vector2 } from '@univerjs/engine-render';import { Inject } from '@wendellhu/redi';@@ -231,7 +231,8 @@ export class DocTextSelectionRenderController extends Disposable implements IRen// The initial cursor is set at the beginning of the document,// and can be set to the previous cursor position in the future.- if (!this._editorService.isEditor(unitId)) {+ // The skeleton of the editor has not been calculated at this moment, and it is determined whether it is an editor by its ID.+ if (!isInternalEditorID(unitId)) {this._textSelectionManagerService.replaceTextRanges([{startOffset: 0,diff --git a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.tsindex c71c79d68f..d1ad59e92f 100644--- a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts+++ b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts@@ -18,7 +18,7 @@ import type { IWorkbookData, Workbook } from '@univerjs/core';import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';+import { IRefSelectionsService, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';import { EditorBridgeService, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { EditorService, IEditorService } from '@univerjs/ui';import type { Dependency } from '@wendellhu/redi';@@ -90,6 +90,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);injector.add([IEditorService, { useClass: EditorService }]);injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([IRefSelectionsService, { useClass: SheetsSelectionsService }]);dependencies?.forEach((d) => injector.add(d));}diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.tsindex 696aa7b5f3..63b56dc519 100644--- a/packages/sheets-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts@@ -462,6 +462,11 @@ export class PromptController extends Disposable {let insertNodes = this._formulaPromptService.getSequenceNodes()!;const char = this._getCurrentChar()!;+ // To reset the cursor position when resetting the editor's content.+ if (insertNodes.length === 0 && this._currentInsertRefStringIndex > 0) {+ this._currentInsertRefStringIndex = -1;+ }+this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;if (!matchRefDrawToken(char) && this._focusIsOnlyRange(selections.length)) {@@ -549,7 +554,7 @@ export class PromptController extends Disposable {selectionIndex += 1;}- this._syncToEditor(lastSequenceNodes, selectionIndex, undefined, false, false);+ this._syncToEditor(lastSequenceNodes, selectionIndex, undefined, true, false);})));@@ -642,7 +647,8 @@ export class PromptController extends Disposable {}const char = this._getCurrentChar();- if (char && matchRefDrawToken(char)) {+ const dataStream = this._getCurrentDataStream();+ if (dataStream?.substring(0, 1) === '=' && char && matchRefDrawToken(char)) {this._enterSelectingMode();} else {this._quitSelectingMode();@@ -673,6 +679,11 @@ export class PromptController extends Disposable {return dataStream[startOffset - 1 + config.offset];}+ private _getCurrentDataStream() {+ const config = this._getCurrentBodyDataStreamAndOffset();+ return config?.dataStream;+ }+private _isSelectingMode = false;private _enterSelectingMode() {if (this._isSelectingMode) {@@ -1165,6 +1176,7 @@ export class PromptController extends Disposable {* @param sequenceNodes* @param textSelectionOffset*/+ // eslint-disable-next-line max-lines-per-functionprivate _syncToEditor(sequenceNodes: Array<string | ISequenceNode>,textSelectionOffset: number,@@ -1196,8 +1208,12 @@ export class PromptController extends Disposable {const editor = this._editorService.getEditor(editorUnitId);+ // You need to set a mode for single selection area or multiple selection areas, adapting to a rangeSelector that only has a single selection area.if (editor?.isSingleChoice()) {dataStream = dataStream.split(',')[0];+ this._selectionRenderService.setSingleSelectionEnabled(true);+ } else {+ this._selectionRenderService.setSingleSelectionEnabled(false);}let formulaString = dataStream;@@ -1226,6 +1242,14 @@ export class PromptController extends Disposable {segmentId: null,options: { fromSelection },});+ // The ReplaceContentCommand has canceled the selection operation, so it needs to be triggered externally once.+ this._textSelectionManagerService.replaceTextRanges([+ {+ startOffset: textSelectionOffset + 1 - offset,+ endOffset: textSelectionOffset + 1 - offset,+ style,+ },+ ], true, { fromSelection });} else {this._updateEditorModel(`${formulaString}\r\n`, textRuns);this._textSelectionManagerService.replaceTextRanges([@@ -1641,6 +1665,7 @@ export class PromptController extends Disposable {}}+ // eslint-disable-next-line max-lines-per-functionprivate _commandExecutedListener() {// Listen to document edits to refresh the size of the editor.const updateCommandList = [SelectEditorFormulaOperation.id];diff --git a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.tsindex 823e042ef1..f2a0b7f24e 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts@@ -30,6 +30,7 @@ import {} from '@univerjs/core';import {BorderStyleManagerService,+ IRefSelectionsService,RangeProtectionRuleModel,SheetInterceptorService,@@ -114,6 +115,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([WorkbookPermissionService]);injector.add([WorksheetProtectionRuleModel]);injector.add([RangeProtectionRuleModel]);+ injector.add([IRefSelectionsService, { useClass: SheetsSelectionsService }]);dependencies?.forEach((d) => injector.add(d));}diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.tsindex 537eb32292..3f07328bb7 100644--- a/packages/sheets-ui/src/services/editor-bridge.service.ts+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts@@ -20,6 +20,9 @@ import {createInterceptorKey,Disposable,DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ FOCUSING_EDITOR_STANDALONE,+ FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE,+ IContextService,InterceptorManager,IUniverInstanceService,makeCellToSelection,@@ -29,7 +32,8 @@ import {} from '@univerjs/core';import type { Engine, IDocumentLayoutObject, Scene } from '@univerjs/engine-render';import { convertTextRotation, DeviceInputEventType, getCanvasOffsetByEngine, IRenderManagerService } from '@univerjs/engine-render';-import type { ISheetLocation } from '@univerjs/sheets';+import type { ISheetLocation, SheetsSelectionsService } from '@univerjs/sheets';+import { IRefSelectionsService } from '@univerjs/sheets';import { IEditorService } from '@univerjs/ui';import type { KeyCode } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';@@ -130,7 +134,9 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(ThemeService) private readonly _themeService: ThemeService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IEditorService private readonly _editorService: IEditorService+ @IEditorService private readonly _editorService: IEditorService,+ @IRefSelectionsService private readonly _refSelectionsService: SheetsSelectionsService,+ @IContextService private readonly _contextService: IContextService) {super();@@ -165,6 +171,16 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServsetEditCell(param: ICurrentEditCellParam) {this._currentEditCell = param;+ /**+ * If there is no editor currently focused, then default to selecting the sheet editor to prevent the editorService from using the previously selected editor object.+ * todo: wzhudev: In boundless mode, it is necessary to switch to the corresponding editorId based on the host's unitId.+ */+ if (!this._editorService.getFocusEditor()) {+ this._editorService.focus(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);+ this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, false);+ this._contextService.setContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, false);+ }+const editCellState = this.getLatestEditCellState();this._currentEditCellState = editCellState;@@ -295,6 +311,15 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ}changeVisible(param: IEditorBridgeServiceVisibleParam) {+ /**+ * Non-sheetEditor and formula selection mode,+ * double-clicking cannot activate the sheet editor.+ */+ const editor = this._editorService.getFocusEditor();+ if (this._refSelectionsService.getCurrentSelections().length > 0 && editor && !editor.isSheetEditor()) {+ return;+ }+this._visible = param;// Reset the dirty status when the editor is visible.diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.tsindex 72f0f935b0..7a9884aa19 100644--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts@@ -73,6 +73,8 @@ export interface ISheetSelectionRenderService {attachPrimaryWithCoord(primary: Nullable<Partial<ISelectionCell>>): Nullable<ISelectionCellWithMergeInfo>;getSelectionCellByPosition(x: number, y: number): Nullable<ISelectionCellWithMergeInfo>; // drawing++ setSingleSelectionEnabled(enabled: boolean): void;}export const ISheetSelectionRenderService = createIdentifier<ISheetSelectionRenderService>('univer.sheet.selection-render-service');@@ -174,6 +176,10 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSelereturn this._activeViewport!;}+ setSingleSelectionEnabled(enabled: boolean = false): void {+ this._singleSelectionEnabled = enabled;+ }+/*** add a selection*diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsxindex 759f9159b7..c2855d751f 100644--- a/packages/ui/src/components/editor/TextEditor.tsx+++ b/packages/ui/src/components/editor/TextEditor.tsx@@ -21,6 +21,7 @@ import React, { useEffect, useRef, useState } from 'react';import { Popup } from '@univerjs/design';import type { Editor, IEditorCanvasStyle } from '../../services/editor/editor.service';import { IEditorService } from '../../services/editor/editor.service';+import { isElementVisible } from '../../utils/util';import styles from './index.module.less';type MyComponentProps = React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;@@ -116,13 +117,15 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onConValid,isValueValid = true,++ placeholder,} = props;const editorService = useDependency(IEditorService);const localeService = useDependency(LocaleService);- const [placeholder, placeholderSet] = useState('');+ const [placeholderValue, placeholderSet] = useState('');const [validationContent, setValidationContent] = useState<string>('');@@ -139,9 +142,9 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onC}useEffect(() => {- const editor = editorRef.current;+ const editorDom = editorRef.current;- if (!editor) {+ if (!editorDom) {return;}@@ -149,10 +152,10 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onCif (cancelDefaultResizeListener !== true) {editorService.resize(id);}- resizeCallBack && resizeCallBack(editor);+ resizeCallBack && resizeCallBack(editorDom);});- resizeObserver.observe(editor);+ resizeObserver.observe(editorDom);const registerSubscription = editorService.register({editorUnitId: id,@@ -169,7 +172,7 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onCopenForSheetUnitId,openForSheetSubUnitId,},- editor);+ editorDom);editorService.setValueNoRefresh(value || '', id);placeholderSet(placeholder || '');@@ -179,14 +182,6 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onConActive && onActive(state);}, 30);- const focusStyleSubscription = editorService.focusStyle$.subscribe((unitId: Nullable<string>) => {- let state = false;- if (unitId === id) {- state = true;- }- activeChange(state);- });-// !IMPORTANT: Set a delay of 160ms to ensure that the position is corrected after the sidebar animation ends @jikkaiconst ANIMATION_DELAY = 160;const valueChange = debounce((editor: Readonly<Editor>) => {@@ -215,6 +210,23 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onC}}, 30);+ const focusStyleSubscription = editorService.focusStyle$.subscribe((unitId: Nullable<string>) => {+ let state = false;+ if (unitId === id) {+ state = true;+ }+ activeChange(state);++ setTimeout(() => {+ if (!isElementVisible(editorDom)) {+ setValidationVisible(true);+ } else {+ const editor = editorService.getEditor(id);+ editor && valueChange(editor);+ }+ }, ANIMATION_DELAY);+ });+const valueChangeSubscription = editorService.valueChange$.subscribe((editor) => {if (editor.isSheetEditor()) {return;@@ -228,7 +240,7 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onC});return () => {- resizeObserver.unobserve(editor);+ resizeObserver.unobserve(editorDom);resizeObserver.disconnect();registerSubscription.dispose();focusStyleSubscription?.unsubscribe();@@ -295,7 +307,7 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onCreturn (<><div {...propsNew} className={className + borderStyle} ref={editorRef}>- <div style={{ display: hasValue() ? 'none' : 'unset' }} className={styles.textEditorContainerPlaceholder}>{placeholder}</div>+ <div style={{ display: hasValue() ? 'none' : 'unset' }} className={styles.textEditorContainerPlaceholder}>{placeholderValue}</div></div><Popup visible={!validationVisible} offset={validationOffset}><div className={styles.textEditorValidationError}>{validationContent}</div>diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.tsindex b93ce46355..33cb84057f 100644--- a/packages/ui/src/services/editor/editor.service.ts+++ b/packages/ui/src/services/editor/editor.service.ts@@ -747,9 +747,9 @@ export class EditorService extends Disposable implements IEditorService, IDisposverticalAlign: VerticalAlign.TOP,horizontalAlign: HorizontalAlign.LEFT,},- marginLeft: 6,- marginTop: 2,- marginRight: 6,+ marginLeft: 3,+ marginTop: 0,+ marginRight: 3,},} as IDocumentData;}diff --git a/packages/ui/src/utils/util.ts b/packages/ui/src/utils/util.tsindex 0f0e600798..f6f3d74caa 100644--- a/packages/ui/src/utils/util.ts+++ b/packages/ui/src/utils/util.ts@@ -21,3 +21,27 @@ export function textTrim(x: string): string {}return x.replace(/^\s+|\s+$/gm, '');}++export function isElementVisible(element: HTMLElement | null) {+ if (!element) return false;++ const style = window.getComputedStyle(element);++ if (style.display === 'none' ||+ style.visibility === 'hidden' ||+ style.opacity === '0') {+ return false;+ }++ const rect = element.getBoundingClientRect();+ if (rect.width === 0 || rect.height === 0) {+ return false;+ }++ if (rect.bottom < 0 || rect.top > window.innerHeight ||+ rect.right < 0 || rect.left > window.innerWidth) {+ return false;+ }++ return true;+}