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): editor add selection error (#4619)
zhangwb43162975132
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaSelection.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaSelection.tsindex d087cdaa19..fa036607c1 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaSelection.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaSelection.ts@@ -20,8 +20,10 @@ import { DocSelectionManagerService } from '@univerjs/docs';import { DocSelectionRenderService } from '@univerjs/docs-ui';import { isFormulaLexerToken, LexerTreeBuilder, matchRefDrawToken, matchToken, sequenceNodeType } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';+import { useEvent } from '@univerjs/ui';import { useEffect, useRef, useState } from 'react';import { filter, map } from 'rxjs';+import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';function getCurrentBodyDataStreamAndOffset(accssor: IAccessor) {const univerInstanceService = accssor.get(IUniverInstanceService);@@ -41,17 +43,27 @@ export enum FormulaSelectingType {CAN_EDIT = 2,}-export function useFormulaSelecting(editorId: string, isFocus: boolean, disableOnClick?: boolean) {+export function useFormulaSelecting(opts: { editorId: string; isFocus: boolean; disableOnClick?: boolean; unitId: string; subUnitId: string }) {+ const { editorId, isFocus, disableOnClick, unitId } = opts;const renderManagerService = useDependency(IRenderManagerService);+ const sheetRenderer = renderManagerService.getRenderById(unitId);const renderer = renderManagerService.getRenderById(editorId);const docSelectionRenderService = renderer?.with(DocSelectionRenderService);const docSelectionManagerService = useDependency(DocSelectionManagerService);const injector = useDependency(Injector);- const [isSelecting, setIsSelecting] = useState<FormulaSelectingType>(FormulaSelectingType.NOT_SELECT);+ const [isSelecting, innerSetIsSelecting] = useState<FormulaSelectingType>(FormulaSelectingType.NOT_SELECT);const lexerTreeBuilder = useDependency(LexerTreeBuilder);const isDisabledByPointer = useRef(true);const isSelectingRef = useRef(isSelecting);isSelectingRef.current = isSelecting;+ const refSelectionsRenderService = sheetRenderer?.with(RefSelectionsRenderService);++ const setIsSelecting = useEvent((v: FormulaSelectingType) => {+ if (refSelectionsRenderService) {+ refSelectionsRenderService.setSkipLastEnabled(v === FormulaSelectingType.NEED_ADD);+ }+ innerSetIsSelecting(v);+ });useEffect(() => {const sub = docSelectionManagerService.textSelection$diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSelectionAdd.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSelectionAdd.tsdeleted file mode 100644index de7b4a51e2..0000000000--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSelectionAdd.ts+++ /dev/null@@ -1,186 +0,0 @@-/**- * 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 type { Editor } from '@univerjs/docs-ui';-import type { INode } from '../../range-selector/utils/filterReferenceNode';-import { useDependency } from '@univerjs/core';-import { compareToken, LexerTreeBuilder, matchToken, operatorToken } from '@univerjs/engine-formula';-import { IRenderManagerService } from '@univerjs/engine-render';-import { useEvent } from '@univerjs/ui';-import { useEffect, useMemo, useRef } from 'react';-import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';-import { findIndexFromSequenceNodes } from '../../range-selector/utils/findIndexFromSequenceNodes';--const createLock = (initValue: boolean, step = 300) => {- let isEnableCancel = initValue;- let time = 0 as any;- const getValue = () => isEnableCancel;- const setValue = (v: boolean) => {- clearTimeout(time);- isEnableCancel = v;- };- function reset() {- clearTimeout(time);- time = setTimeout(() => {- isEnableCancel = initValue;- }, step);- }- return {- getValue,- setValue,- reset,- };-};--const baseToken = [- compareToken.EQUALS,- compareToken.GREATER_THAN,- compareToken.GREATER_THAN_OR_EQUAL,- compareToken.LESS_THAN,- compareToken.LESS_THAN_OR_EQUAL,- compareToken.NOT_EQUAL,- operatorToken.CONCATENATE,- operatorToken.DIVIDED,- operatorToken.MINUS,- operatorToken.MULTIPLY,- operatorToken.PLUS,- operatorToken.POWER,- matchToken.COMMA,-];-const currentNodeAddToken = [- ...baseToken,- matchToken.COLON,- matchToken.OPEN_BRACKET,-];--const nextNodeAddToken = [- ...baseToken,- matchToken.CLOSE_BRACKET,-];--const getContent = (node: INode) => typeof node === 'string' ? node : node.token;-/**- * 根据输入内容,以及当前光标位置判断下一个 mouseDown 事件是不是需要新增选区- *- * @param {string} unitId- * @param {INode[]} sequenceNodes- * @param {Editor} [editor]- * @return {*}- */-// eslint-disable-next-line max-lines-per-function-export const useSelectionAdd = (unitId: string, editor?: Editor) => {- const renderManagerService = useDependency(IRenderManagerService);- const render = renderManagerService.getRenderById(unitId);- const refSelectionsRenderService = render?.with(RefSelectionsRenderService);- const isNeedAddSelection = useRef(false);- const lexerTreeBuilder = useDependency(LexerTreeBuilder);-- // 非用户行为导致的选区改变,应该屏蔽选区变更事件- const isLockSelectionEvent = useMemo(() => createLock(false, 300), []);-- const setIsAddSelection = useEvent((v: boolean) => {- if (refSelectionsRenderService) {- refSelectionsRenderService.setSkipLastEnabled(v);- }- isNeedAddSelection.current = v;- });-- const getIsNeedAddSelection = useEvent(() => isNeedAddSelection.current);-- useEffect(() => {- if (editor && refSelectionsRenderService) {- const d1 = editor.input$.subscribe((e) => {- const content = e.content as any;- if (content.length === 1 && currentNodeAddToken.includes(content)) {- setIsAddSelection(true);- isLockSelectionEvent.setValue(true);- isLockSelectionEvent.reset();- } else {- setIsAddSelection(false);- isLockSelectionEvent.setValue(false);- }- });- // sequenceNodes 的创建会在 input 事件之后,为了拿到最新的 sequenceNodes , 这里延后 100ms- const d2 = editor.selectionChange$.subscribe((e) => {- if (isLockSelectionEvent.getValue()) {- return;- }- const dataStream = editor.getDocumentData().body?.dataStream.slice(0, -2) ?? '';- const sequenceNodes = lexerTreeBuilder.sequenceNodesBuilder(dataStream);- const selections = e.textRanges;- if (!selections.length) {- return;- }- if (selections.length !== 1) {- setIsAddSelection(false);- return;- }- const range = selections[0];- if (!range.collapsed) {- setIsAddSelection(false);- return;- }- if (!sequenceNodes?.length) {- setIsAddSelection(true);- return;- }- // ‘=’不会进入 sequenceNodes ,所以需要 -1- const startOffset = range.startOffset - 1;-- if (startOffset === 0) {- const nextIndex = findIndexFromSequenceNodes(sequenceNodes, 1, false);- const nextNode = sequenceNodes[nextIndex] || '';- const nextContent = getContent(nextNode);- if (baseToken.includes(nextContent as any)) {- setIsAddSelection(true);- return;- }- }- const index = findIndexFromSequenceNodes(sequenceNodes, startOffset, false);- const currentNode = sequenceNodes[index];- if (!currentNode) {- setIsAddSelection(false);- return;- }- const nextNode = sequenceNodes[index + 1] || '';- const nextContent = getContent(nextNode) as any;- const content = getContent(currentNode) as any;- if (currentNodeAddToken.includes(content) && (!nextNode || nextNodeAddToken.includes(nextContent))) {- setIsAddSelection(true);- } else {- setIsAddSelection(false);- }- });- // 增加一个延时,外部接收到 moveEnd 事件后,再重置状态- refSelectionsRenderService.selectionMoveEnd$.subscribe(() => {- Promise.resolve().then(() => {- setIsAddSelection(false);- });- });-- return () => {- d1.unsubscribe();- d2.unsubscribe();- };- }- }, [editor, isLockSelectionEvent, lexerTreeBuilder, refSelectionsRenderService, setIsAddSelection]);-- return {- setIsAddSelection,- getIsNeedAddSelection,- isLockSelectionEvent,- };-};diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex 1cce441dca..bb31cd2c76 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -132,7 +132,7 @@ export function FormulaEditor(props: IFormulaEditorProps) {const formulaText = BuildTextUtils.transform.getPlainText(document?.getBody()?.dataStream ?? '');const formulaWithoutEqualSymbol = useMemo(() => getFormulaText(formulaText), [formulaText]);const sequenceNodes = useMemo(() => getFormulaToken(formulaWithoutEqualSymbol), [formulaWithoutEqualSymbol, getFormulaToken]);- const { isSelecting } = useFormulaSelecting(editorId, isFocus, disableSelectionOnClick);+ const { isSelecting } = useFormulaSelecting({ unitId, subUnitId, editorId, isFocus, disableOnClick: disableSelectionOnClick });const highTextRef = useRef('');const renderManagerService = useDependency(IRenderManagerService);const renderer = renderManagerService.getRenderById(editorId);diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.tsindex 99ca0fa932..33f0f93547 100644--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts@@ -16,10 +16,10 @@/* eslint-disable max-lines-per-function */-import type { DocumentDataModel, ICellData, ICommandInfo, IDisposable, IDocumentBody, IDocumentData, IDocumentStyle, IStyleData, Nullable, Styles, Workbook } from '@univerjs/core';+import type { DocumentDataModel, ICellData, ICommandInfo, IDisposable, IDocumentBody, IDocumentData, IDocumentStyle, IMutationInfo, IStyleData, Nullable, Styles, Workbook } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';-import type { WorkbookSelectionModel } from '@univerjs/sheets';+import type { MutationsAffectRange, WorkbookSelectionModel } from '@univerjs/sheets';import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';import {@@ -55,7 +55,7 @@ import {IRenderManagerService,} from '@univerjs/engine-render';-import { COMMAND_LISTENER_SKELETON_CHANGE, REF_SELECTIONS_ENABLED, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SetWorksheetActiveOperation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';+import { adjustRangeOnMutation, COMMAND_LISTENER_SKELETON_CHANGE, InsertColMutation, InsertRowMutation, MoveColsMutation, MoveRowsMutation, REF_SELECTIONS_ENABLED, RemoveColMutation, RemoveRowMutation, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SetWorksheetActiveOperation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';import { KeyCode } from '@univerjs/ui';import { distinctUntilChanged, filter } from 'rxjs';import { getEditorObject } from '../../basics/editor/get-editor-object';@@ -225,6 +225,31 @@ export class EditingRenderController extends Disposable implements IRenderModuleif (!commandList.has(commandInfo.id)) {return;}+ switch (commandInfo.id) {+ case MoveRowsMutation.id:+ case MoveColsMutation.id:+ case RemoveColMutation.id:+ case RemoveRowMutation.id:+ case InsertColMutation.id:+ case InsertRowMutation.id:+ {+ const editLocation = this._editorBridgeService.getEditLocation();+ if (!editLocation) break;+ const currentRange = {+ startRow: editLocation.row,+ startColumn: editLocation.column,+ endRow: editLocation.row,+ endColumn: editLocation.column,+ };+ const newRange = adjustRangeOnMutation(currentRange, commandInfo as IMutationInfo<MutationsAffectRange>);+ if (!newRange) break;+ const newRow = newRange.startRow;+ const newColumn = newRange.startColumn;+ this._editorBridgeService.updateEditLocation(newRow, newColumn);+ break;+ }+ }+this._sheetCellEditorResizeService.resizeCellEditor(() => {this._textSelectionManagerService.refreshSelection({unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.tsindex 0770cb5199..dc2034cf94 100644--- a/packages/sheets-ui/src/services/editor-bridge.service.ts+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts@@ -92,6 +92,7 @@ export interface IEditorBridgeService {getEditCellState(): Readonly<Nullable<IEditorBridgeServiceParam>>;getEditCellLayout(): Readonly<Nullable<ICellEditorLayout>>;getEditLocation(): Readonly<Nullable<ICellEditorState>>;+ updateEditLocation(row: number, col: number): void;// Gets the DocumentDataModel of the latest table cell based on the latest cell contentsgetLatestEditCellState(): Readonly<Nullable<IEditorBridgeServiceParam>>;/**@@ -290,6 +291,16 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServreturn this._currentEditCellState;}+ updateEditLocation(row: number, column: number) {+ if (this._currentEditCellState) {+ this._currentEditCellState = {+ ...this._currentEditCellState,+ row,+ column,+ };+ }+ }+// eslint-disable-next-line max-lines-per-functiongetLatestEditCellState() {const currentEditCell = this._currentEditCell;