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.

fix(sheets): before edit event can't cancel by formula-bar (#4569)

zhangw9fe3d2ad4a91
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 0d575a7748..c4a7c12a9d 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -175,3 +175,9 @@ declare global {
}
}
+window.univerAPI?.addEvent(window.univerAPI.Event.BeforeSheetEditStart, (params) => {
+ const { row, column } = params;
+ if (row === 0 && column === 0) {
+ params.cancel = true;
+ }
+});
diff --git a/packages/core/src/facade/f-univer.ts b/packages/core/src/facade/f-univer.ts
index 9bc6a850da..ca43e6ac62 100644
--- a/packages/core/src/facade/f-univer.ts
+++ b/packages/core/src/facade/f-univer.ts
@@ -308,7 +308,7 @@ export class FUniver extends FBaseInitialable {
* });
* ```
*/
- addEvent(event: keyof IEventParamConfig, callback: (params: IEventParamConfig[typeof event]) => void) {
+ addEvent<T extends keyof IEventParamConfig>(event: T, callback: (params: IEventParamConfig[T]) => void) {
this._ensureEventRegistry(event).add(callback);
return toDisposable(() => this._ensureEventRegistry(event).delete(callback));
}
diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.ts
index 113ece1930..b17f6e13a2 100644
--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts
+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts
@@ -57,7 +57,7 @@ export interface IEditorService {
isSheetEditor(editorUnitId: string): boolean;
blur$: Observable<unknown>;
- blur(): void;
+ blur(force?: boolean): void;
focus$: Observable<ISuccinctDocRangeParam>;
focus(editorUnitId: string): void;
@@ -135,13 +135,16 @@ export class EditorService extends Disposable implements IEditorService, IDispos
return !!(editor && editor.isSheetEditor());
}
- blur() {
- this._setFocusId(null);
- this._contextService.setContextValue(EDITOR_ACTIVATED, false);
- this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, false);
-
+ blur(force?: boolean) {
const focusingEditor = this.getFocusEditor();
+ if (force) {
+ focusingEditor?.setSelectionRanges([]);
+ }
focusingEditor?.blur();
+
+ this._contextService.setContextValue(EDITOR_ACTIVATED, false);
+ this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, false);
+ this._setFocusId(null);
this._blur$.next(null);
}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
index 91fc533da3..1cce441dca 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
@@ -73,6 +73,7 @@ export interface IFormulaEditorProps {
*/
disableSelectionOnClick?: boolean;
disableContextMenu?: boolean;
+ style?: React.CSSProperties;
}
const noop = () => { };
@@ -100,6 +101,7 @@ export function FormulaEditor(props: IFormulaEditorProps) {
isSingle = true,
disableSelectionOnClick = false,
disableContextMenu,
+ style,
} = props;
const editorService = useDependency(IEditorService);
@@ -285,8 +287,9 @@ export function FormulaEditor(props: IFormulaEditorProps) {
onFocus();
focus();
};
+
return (
- <div className={clsx(styles.sheetEmbeddingFormulaEditor, className)}>
+ <div style={style} className={clsx(styles.sheetEmbeddingFormulaEditor, className)}>
<div
className={clsx(styles.sheetEmbeddingFormulaEditorWrap, {
[styles.sheetEmbeddingFormulaEditorActive]: isFocus,
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useFocus.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFocus.ts
index f8fa3f3001..ee91c37d54 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useFocus.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFocus.ts
@@ -14,14 +14,15 @@
* limitations under the License.
*/
-import type { Editor } from '@univerjs/docs-ui';
-import { Tools } from '@univerjs/core';
+import { Tools, useDependency } from '@univerjs/core';
+import { type Editor, IEditorService } from '@univerjs/docs-ui';
import { useEvent } from '@univerjs/ui';
export const useFocus = (editor?: Editor) => {
+ const editorService = useDependency(IEditorService);
const focus = useEvent((offset?: number) => {
if (editor) {
- editor.focus();
+ editorService.focus(editor.getEditorId());
const selections = [...editor.getSelectionRanges()];
if (Tools.isDefine(offset)) {
editor.setSelectionRanges([{ startOffset: offset, endOffset: offset }]);
diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
index 1caf4eee00..e36593370f 100644
--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
@@ -18,6 +18,7 @@ import type { Nullable } from '@univerjs/core';
import type {
IRichTextEditingMutationParams } from '@univerjs/docs';
import type { RenderComponentType } from '@univerjs/engine-render';
+import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
import {
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
EDITOR_ACTIVATED,
@@ -40,6 +41,7 @@ import { CoverContentCommand, VIEWPORT_KEY as DOC_VIEWPORT_KEY, IEditorService }
import { DeviceInputEventType, IRenderManagerService, ScrollBar } from '@univerjs/engine-render';
import { combineLatest, filter, takeUntil } from 'rxjs';
import { getEditorObject } from '../../basics/editor/get-editor-object';
+import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
@@ -112,7 +114,6 @@ export class FormulaEditorController extends RxDisposable {
}
if (!this._loadedMap.has(documentComponent)) {
- this._initialMain(unitId);
this._loadedMap.add(documentComponent);
}
}
@@ -134,11 +135,14 @@ export class FormulaEditorController extends RxDisposable {
const visibleState = this._editorBridgeService.isVisible();
if (visibleState.visible === false) {
- this._editorBridgeService.changeVisible({
- visible: true,
- eventType: DeviceInputEventType.PointerDown,
- unitId: currentSheet?.getUnitId() ?? '',
- });
+ this._commandService.syncExecuteCommand(
+ SetCellEditVisibleOperation.id,
+ {
+ visible: true,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId: currentSheet?.getUnitId() ?? '',
+ } as IEditorBridgeServiceVisibleParam
+ );
}
const content = formulaEditorDataModel?.getBody()?.dataStream;
@@ -173,38 +177,6 @@ export class FormulaEditorController extends RxDisposable {
});
}
- private _initialMain(unitId: string) {
- const formulaEditorDocObject = this._renderManagerService.getRenderById(unitId);
- if (formulaEditorDocObject == null) {
- return;
- }
-
- const { mainComponent: documentComponent } = formulaEditorDocObject;
-
- if (documentComponent == null) {
- return;
- }
-
- this.disposeWithMe(
- documentComponent.onPointerDown$.subscribeEvent(() => {
- // When clicking on the formula bar, the cell editor also needs to enter the edit state
- const visibleState = this._editorBridgeService.isVisible();
- if (visibleState.visible === false) {
- this._editorBridgeService.changeVisible({
- visible: true,
- eventType: DeviceInputEventType.PointerDown,
- unitId,
- });
- this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
- }
-
- // Open the normal editor first, and then we mark formula editor as activated.
- this._contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, true);
- })
- );
- }
-
- // Listen to changes in the size of the formula editor container to set the size of the editor.
private _syncEditorSize() {
// this._univerInstanceService.
const addFOrmulaBar$ = this._univerInstanceService.unitAdded$.pipe(filter((unit) => unit.getUnitId() === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY));
diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
index 014d296e2e..b68d1a6655 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
@@ -232,7 +232,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
return;
}
- this._commandService.executeCommand(SetCellEditVisibleOperation.id, {
+ this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {
visible: true,
eventType: DeviceInputEventType.Keyboard,
keycode: event.which,
diff --git a/packages/sheets-ui/src/facade/f-univer.ts b/packages/sheets-ui/src/facade/f-univer.ts
index 42f2e382a6..fdb2f88a5b 100644
--- a/packages/sheets-ui/src/facade/f-univer.ts
+++ b/packages/sheets-ui/src/facade/f-univer.ts
@@ -102,7 +102,7 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix
if (!this._eventListend(this.Event.BeforeSheetEditStart) && !this._eventListend(this.Event.BeforeSheetEditEnd)) {
return;
}
- const target = this.getCommandSheetTarget(commandInfo);
+ const target = this.getActiveSheet();
if (!target) {
return;
}
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 0d299fc76a..69ce1bc1f6 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -15,7 +15,9 @@
*/
import type { Workbook } from '@univerjs/core';
-import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, FOCUSING_FX_BAR_EDITOR, IContextService, IPermissionService, IUniverInstanceService, UniverInstanceType, useDependency, useObservable } from '@univerjs/core';
+import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, FOCUSING_FX_BAR_EDITOR, ICommandService, IContextService, IPermissionService, IUniverInstanceService, UniverInstanceType, useDependency, useObservable } from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { CheckMarkSingle, CloseSingle, DropdownSingle, FxSingle } from '@univerjs/icons';
import { RangeProtectionCache, RangeProtectionRuleModel, SheetsSelectionsService, UnitAction, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetViewPermission } from '@univerjs/sheets';
@@ -23,6 +25,7 @@ import { ComponentContainer, ComponentManager, KeyCode, useComponentsOfPart } fr
import clsx from 'clsx';
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { EMPTY, merge, of, switchMap } from 'rxjs';
+import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY } from '../../common/keys';
import { useActiveWorkbook } from '../../components/hook';
import { SheetsUIPart } from '../../consts/ui-name';
@@ -67,6 +70,7 @@ export function FormulaBar() {
useObservable(useMemo(() => contextService.subscribeContextValue$(FOCUSING_FX_BAR_EDITOR), [contextService]));
const isFocusFxBar = contextService.getContextValue(FOCUSING_FX_BAR_EDITOR);
const ref = useRef<HTMLDivElement>(null);
+ const editorService = useDependency(IEditorService);
useLayoutEffect(() => {
const subscription = workbook.activeSheet$.pipe(
@@ -205,6 +209,43 @@ export function FormulaBar() {
// TODO Is there a need to disable an editor here?
const { viewDisable, editDisable } = disableInfo;
const disabled = editDisable || imageDisable;
+ const shouldSkipFocus = useRef(false);
+ const commandService = useDependency(ICommandService);
+ const unitId = currentWorkbook?.getUnitId() ?? '';
+
+ const handlePointerDown = () => {
+ try {
+ // When clicking on the formula bar, the cell editor also needs to enter the edit state
+ const visibleState = editorBridgeService.isVisible();
+ if (visibleState.visible === false) {
+ commandService.syncExecuteCommand(
+ SetCellEditVisibleOperation.id,
+ {
+ visible: true,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ } as IEditorBridgeServiceVisibleParam
+ );
+ // undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ }
+
+ // Open the normal editor first, and then we mark formula editor as activated.
+ contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, true);
+ } catch (e) {
+ shouldSkipFocus.current = true;
+ throw e;
+ }
+ };
+
+ const handlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
+ if (shouldSkipFocus.current) {
+ setTimeout(() => {
+ editorService.blur(true);
+ }, 30);
+ }
+ shouldSkipFocus.current = false;
+ };
+
return (
<div
className={styles.formulaBox}
@@ -241,7 +282,12 @@ export function FormulaBar() {
</div>
<div className={styles.formulaContainer}>
- <div className={styles.formulaInput} ref={ref}>
+ <div
+ className={styles.formulaInput}
+ onPointerDown={handlePointerDown}
+ onPointerUp={handlePointerUp}
+ ref={ref}
+ >
{FormulaEditor && (
<FormulaEditor
disableSelectionOnClick
diff --git a/packages/sheets-ui/src/views/formula-bar/index.module.less b/packages/sheets-ui/src/views/formula-bar/index.module.less
index 7ccaf5fdfa..ee2f027910 100644
--- a/packages/sheets-ui/src/views/formula-bar/index.module.less
+++ b/packages/sheets-ui/src/views/formula-bar/index.module.less
@@ -88,6 +88,17 @@
.formula-input {
flex: 1;
+ position: relative;
+ }
+
+ .formula-input-mask {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 100;
}
.formula-container {