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(sheets-ui): cell-editor & formula-bar-editor (#3737)
zhangw71da8aba02a0
diff --git a/packages/core/src/sheets/styles.ts b/packages/core/src/sheets/styles.tsindex b4212c3ebf..b23fa17ed0 100644--- a/packages/core/src/sheets/styles.ts+++ b/packages/core/src/sheets/styles.ts@@ -15,9 +15,9 @@*/import type { IKeyType, Nullable } from '../shared';-import { LRUMap, Tools } from '../shared';import type { IStyleData } from '../types/interfaces';import type { ICellDataForSheetInterceptor } from './typedef';+import { LRUMap, Tools } from '../shared';/*** Styles in a workbook, cells locate styles based on style IDsdiff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.tsindex 28123802a3..dfa0ee4baf 100644--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts@@ -34,6 +34,8 @@ export interface IRichTextEditingMutationParams extends IMutationCommonParams {// Do you need to compose the undo and redo of history, and compose of the change states.debounce?: boolean;options?: { [key: string]: boolean };+ // Whether this mutation is from a sync operation.+ isSync?: boolean;}const RichTextEditingMutationId = 'doc.mutation.rich-text-editing';diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.tsindex bb2dcae1da..dcbc6dc34c 100644--- a/packages/engine-render/src/components/sheets/spreadsheet.ts+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts@@ -32,6 +32,7 @@ import { BooleanNumber, sortRules, Tools } from '@univerjs/core';import { FIX_ONE_PIXEL_BLUR_OFFSET, RENDER_CLASS_TYPE } from '../../basics/const';import { getCellPositionByIndex, getColor } from '../../basics/tools';import { Documents } from '../docs/document';+import { SpreadsheetExtensionRegistry } from '../extension';import { SHEET_EXTENSION_PREFIX } from './extensions/sheet-extension';import { type IPaintForRefresh, type IPaintForScrolling, SHEET_VIEWPORT_KEY } from './interfaces';diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.tsindex cd303c5999..a43efb9c8b 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import { Disposable, generateRandomId, Inject, Injector, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';-import { ComponentManager, ISidebarService } from '@univerjs/ui';import type { IDisposable } from '@univerjs/core';import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';+import { Disposable, generateRandomId, Inject, Injector, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';+import { ComponentManager, ISidebarService } from '@univerjs/ui';import { ConditionFormattingPanel } from '../components/panel';const CF_PANEL_KEY = 'sheet.conditional.formatting.panel';diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.tsindex c284f97dc8..9246b4cbb9 100644--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.ts+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.ts@@ -14,10 +14,10 @@* limitations under the License.*/+import type { ISequenceNode } from '@univerjs/engine-formula';import { useDependency } from '@univerjs/core';import { LexerTreeBuilder } from '@univerjs/engine-formula';import { useEffect, useState } from 'react';-import type { ISequenceNode } from '@univerjs/engine-formula';export const useFormulaToken = (text: string) => {const lexerTreeBuilder = useDependency(LexerTreeBuilder);diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.tsindex 537e2dbf0e..bf422eb13e 100644--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.ts+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.ts@@ -14,11 +14,11 @@* limitations under the License.*/+import type { IRangeSelectorProps } from '../';+import type { useFormulaToken } from './useFormulaToken';import { useEffect, useRef } from 'react';import { sequenceNodeToText } from '../utils/sequenceNodeToText';import { verifyRange } from '../utils/verifyRange';-import type { IRangeSelectorProps } from '../';-import type { useFormulaToken } from './useFormulaToken';export const useVerify = (onVerify: IRangeSelectorProps['onVerify'], sequenceNodes: ReturnType<typeof useFormulaToken>['sequenceNodes']) => {const isInitRender = useRef(true);diff --git a/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.ts b/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.tsindex d6fe53f3f2..1258d28f23 100644--- a/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.ts+++ b/packages/sheets-hyper-link-ui/src/commands/commands/add-hyper-link.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICommand, IDocumentData, IMutationInfo, Workbook } from '@univerjs/core';+import type { ICellData, ICommand, IDocumentData, IMutationInfo, Workbook } from '@univerjs/core';import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';import { BuildTextUtils, CellValueType, CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, Tools, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';@@ -22,7 +22,7 @@ import { addCustomRangeBySelectionFactory } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';import { AddHyperLinkMutation, HyperLinkModel, type ICellHyperLink, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';export interface IAddHyperLinkCommandParams {unitId: string;@@ -46,7 +46,7 @@ export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {const renderManagerService = accessor.get(IRenderManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);const hyperLinkModel = accessor.get(HyperLinkModel);-+ const editorBridgeService = accessor.get(IEditorBridgeService);const { unitId, subUnitId, link } = params;const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);const currentRender = renderManagerService.getRenderById(unitId);@@ -114,15 +114,19 @@ export const AddHyperLinkCommand: ICommand<IAddHyperLinkCommandParams> = {body: newBody,};+ const newCellData: ICellData = {+ p: rangeValue,+ t: CellValueType.STRING,+ };++ const finalCellData = await editorBridgeService.beforeSetRangeValue(workbook, worksheet, row, column, newCellData);+const redoParams: ISetRangeValuesMutationParams = {unitId,subUnitId,cellValue: {[link.row]: {- [link.column]: {- p: rangeValue,- t: CellValueType.STRING,- },+ [link.column]: finalCellData,},},};diff --git a/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.ts b/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.tsindex 1c0b5d8b51..b97720c4ae 100644--- a/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.ts+++ b/packages/sheets-hyper-link-ui/src/commands/commands/update-hyper-link.command.ts@@ -14,13 +14,13 @@* limitations under the License.*/+import type { DocumentDataModel, ICellData, ICommand, IMutationInfo, Workbook } from '@univerjs/core';import { CellValueType, CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, getBodySlice, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecuteAsync, TextX, Tools, UniverInstanceType } from '@univerjs/core';import { replaceSelectionFactory } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';import { AddHyperLinkMutation, HyperLinkModel, type ICellLinkContent, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';-import type { DocumentDataModel, ICommand, IMutationInfo, Workbook } from '@univerjs/core';+import { IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';export interface IUpdateHyperLinkCommandParams {unitId: string;@@ -44,6 +44,8 @@ export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {const renderManagerService = accessor.get(IRenderManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);const hyperLinkModel = accessor.get(HyperLinkModel);+ const editorBridgeService = accessor.get(IEditorBridgeService);+const { unitId, subUnitId, payload: link, row, column, id } = params;const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);const currentRender = renderManagerService.getRenderById(unitId);@@ -105,6 +107,15 @@ export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {return false;}const newBody = TextX.apply(Tools.deepClone(snapshot.body!), replaceSelection.textX.serialize());+ const newCellData: ICellData = {+ p: {+ ...snapshot,+ body: newBody,+ },+ t: CellValueType.STRING,+ };++ const finalCellData = await editorBridgeService.beforeSetRangeValue(workbook, worksheet, row, column, newCellData);const redo = {id: SetRangeValuesMutation.id,@@ -113,13 +124,7 @@ export const UpdateHyperLinkCommand: ICommand<IUpdateHyperLinkCommandParams> = {subUnitId,cellValue: {[row]: {- [column]: {- p: {- ...snapshot,- body: newBody,- },- t: CellValueType.STRING,- },+ [column]: finalCellData,},},},diff --git a/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts b/packages/sheets-ui/src/controllers/editor/data-sync.controller.tsnew file mode 100644index 0000000000..c724208f5a--- /dev/null+++ b/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts@@ -0,0 +1,268 @@+/**+ * 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 { DocumentDataModel, ICommandInfo, IDocumentBody, IParagraph, Nullable } from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import type { DocumentViewModel } from '@univerjs/engine-render';+import type { IMoveRangeMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';+import type { ICellEditorState } from '../../services/editor-bridge.service';+import { BooleanNumber, Disposable, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, HorizontalAlign, ICommandService, Inject, IUniverInstanceService, Tools, UniverInstanceType } from '@univerjs/core';+import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';+import { MoveRangeMutation, RangeProtectionRuleModel, SetRangeValuesMutation, WorksheetProtectionRuleModel } from '@univerjs/sheets';+import { SetEditorResizeOperation } from '@univerjs/ui';+import { IEditorBridgeService } from '../../services/editor-bridge.service';+import { FormulaEditorController } from './formula-editor.controller';++/**+ * sync data between cell editor and formula editor+ */+export class EditorDataSyncController extends Disposable {+ constructor(+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(RangeProtectionRuleModel) private readonly _rangeProtectionRuleModel: RangeProtectionRuleModel,+ @Inject(WorksheetProtectionRuleModel) private readonly _worksheetProtectionRuleModel: WorksheetProtectionRuleModel,+ @Inject(FormulaEditorController) private readonly _formulaEditorController: FormulaEditorController+ ) {+ super();++ this._initialize();+ }++ private _initialize() {+ this._syncFormulaEditorContent();+ this._commandExecutedListener();+ }++ private _getEditorViewModel(unitId: string): Nullable<DocumentViewModel> {+ return this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService).getViewModel();+ }++ // Sync cell content to formula editor bar when sheet selection changed.+ private _syncFormulaEditorContent() {+ this.disposeWithMe(this._editorBridgeService.currentEditCellState$.subscribe((editCellState) => {+ if (+ editCellState == null+ || this._editorBridgeService.isForceKeepVisible()+ // If permissions are not initialized, data synchronization will not be performed.+ || !this._rangeProtectionRuleModel.getRangeRuleInitState()+ || !this._worksheetProtectionRuleModel.getSheetRuleInitState()+ ) {+ return;+ }++ this._editorSyncHandler(editCellState);+ }));+ }++ // Sync cell content to formula editor bar when sheet selection changed or visible changed.+ private _editorSyncHandler(param: ICellEditorState) {+ let body = Tools.deepClone(param.documentLayoutObject.documentModel?.getBody());++ if (+ !body || (+ param.isInArrayFormulaRange === true &&+ this._editorBridgeService.isVisible().eventType === DeviceInputEventType.Dblclick+ )+ ) {+ body = {+ dataStream: '\r\n',+ paragraphs: [+ {+ startIndex: 0,+ },+ ],+ textRuns: [],+ };+ }++ this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, body);+ }++ private _commandExecutedListener() {+ const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];++ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === RichTextEditingMutation.id || command.id === SetEditorResizeOperation.id) {+ const params = command.params as IRichTextEditingMutationParams;+ const { unitId } = params;+ if (params.isSync) {+ return;+ }+ if (INCLUDE_LIST.includes(unitId)) {+ // sync cell content to formula editor bar when edit cell editor and vice verse.+ const editorDocDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);++ const syncId =+ unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY+ ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY+ : DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;++ this._checkAndSetRenderStyleConfig(editorDocDataModel!);+ this._syncActionsAndRender(syncId, params);+ }+ }+ })+ );++ // Update formula bar content when you call SetRangeValuesMutation and MoveRangeMutation.+ const needUpdateFormulaEditorContentCommandList = [SetRangeValuesMutation.id, MoveRangeMutation.id];+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (needUpdateFormulaEditorContentCommandList.includes(command.id)) {+ const editCellState = this._editorBridgeService.getLatestEditCellState();++ if (editCellState == null) {+ return;+ }++ let needUpdate = false;++ const { row, column } = editCellState;++ if (command.id === SetRangeValuesMutation.id && command.params) {+ const params = command.params as ISetRangeValuesMutationParams;+ if (params.cellValue?.[row]?.[column]) {+ needUpdate = true;+ }+ } else if (command.id === MoveRangeMutation.id && command.params) {+ const params = command.params as IMoveRangeMutationParams;+ if (params.to.value?.[row]?.[column]) {+ needUpdate = true;+ }+ }++ if (needUpdate) {+ const body = editCellState.documentLayoutObject.documentModel?.getBody();++ if (body == null) {+ return;+ }+ this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, Tools.deepClone(body));+ }+ }+ })+ );+ }++ // Sync actions between cell editor and formula editor, and make `dataStream` and `paragraph` is the same.+ private _syncActionsAndRender(+ unitId: string,+ parmas: IRichTextEditingMutationParams+ ) {+ const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];+ const currentRender = this._renderManagerService.getRenderById(unitId);+ if (currentRender == null) {+ return;+ }++ const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();+ const docDataModel = this._univerInstanceService.getUniverDocInstance(unitId);+ const docViewModel = this._getEditorViewModel(unitId);++ if (docDataModel == null || docViewModel == null) {+ return;+ }++ this._commandService.syncExecuteCommand(RichTextEditingMutation.id, {+ ...parmas,+ isSync: true,+ unitId,+ });++ docViewModel.reset(docDataModel);++ skeleton.calculate();++ if (INCLUDE_LIST.includes(unitId)) {+ currentRender.mainComponent?.makeDirty();+ }+ }++ private _syncContentAndRender(+ unitId: string,+ body: IDocumentBody+ ) {+ const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];++ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService).getSkeleton();+ const docDataModel = this._univerInstanceService.getUniverDocInstance(unitId);+ const docViewModel = this._getEditorViewModel(unitId);++ if (docDataModel == null || docViewModel == null || skeleton == null) {+ return;+ }++ docDataModel.getSnapshot().body = body;++ this._checkAndSetRenderStyleConfig(docDataModel);++ docViewModel.reset(docDataModel);++ const currentRender = this._renderManagerService.getRenderById(unitId);++ if (currentRender == null) {+ return;+ }++ skeleton.calculate();++ if (INCLUDE_LIST.includes(unitId)) {+ currentRender.mainComponent?.makeDirty();+ }++ if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ this._formulaEditorController.autoScroll();+ }+ }++ private _checkAndSetRenderStyleConfig(documentDataModel: DocumentDataModel) {+ const snapshot = documentDataModel.getSnapshot();+ const { body } = snapshot;++ if (snapshot.id !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ return;+ }++ let renderConfig = snapshot.documentStyle.renderConfig;++ if (renderConfig == null) {+ renderConfig = {};+ snapshot.documentStyle.renderConfig = renderConfig;+ }++ if ((body?.dataStream ?? '').startsWith('=')) {+ renderConfig.isRenderStyle = BooleanNumber.TRUE;+ } else {+ renderConfig.isRenderStyle = BooleanNumber.FALSE;+ }+ }++ private _clearParagraph(paragraphs: IParagraph[]) {+ const newParagraphs = Tools.deepClone(paragraphs);+ for (const paragraph of newParagraphs) {+ if (paragraph.paragraphStyle) {+ paragraph.paragraphStyle.horizontalAlign = HorizontalAlign.UNSPECIFIED;+ }+ }++ return newParagraphs;+ }+}diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.tsindex 83d15fd64b..bdfd143e5d 100644--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts@@ -16,15 +16,19 @@/* eslint-disable max-lines-per-function */+import type { DocumentDataModel, ICellData, ICommandInfo, IDisposable, IDocumentBody, IDocumentData, IStyleData, Nullable, UnitModel, Workbook } from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';+import type { WorkbookSelections } from '@univerjs/sheets';+import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';+import {CellValueType, DEFAULT_EMPTY_DOCUMENT_VALUE, Direction, Disposable, DisposableCollection, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, EDITOR_ACTIVATED,FOCUSING_EDITOR_BUT_HIDDEN,FOCUSING_EDITOR_INPUT_FORMULA,FOCUSING_EDITOR_STANDALONE,FOCUSING_FX_BAR_EDITOR,- FOCUSING_SHEET,FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE,- HorizontalAlign,ICommandService,IContextService,Inject,@@ -36,7 +40,6 @@ import {toDisposable,Tools,UniverInstanceType,- VerticalAlign,WrapStrategy,} from '@univerjs/core';import {@@ -44,52 +47,31 @@ import {DocSkeletonManagerService,RichTextEditingMutation,} from '@univerjs/docs';-import { VIEWPORT_KEY as DOC_VIEWPORT_KEY, DOCS_COMPONENT_MAIN_LAYER_INDEX, DocSelectionRenderService, IEditorService, MoveCursorOperation, MoveSelectionOperation } from '@univerjs/docs-ui';+import { VIEWPORT_KEY as DOC_VIEWPORT_KEY, DocSelectionRenderService, IEditorService, MoveCursorOperation, MoveSelectionOperation } from '@univerjs/docs-ui';import { IFunctionService, LexerTreeBuilder, matchToken } from '@univerjs/engine-formula';import {convertTextRotation,DeviceInputEventType,- FIX_ONE_PIXEL_BLUR_OFFSET,- fixLineWidthByScale,IRenderManagerService,- Rect,- ScrollBar,} from '@univerjs/engine-render';-import { ClearSelectionFormatCommand, COMMAND_LISTENER_SKELETON_CHANGE, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetActivateCommand, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';-import { ILayoutService, KeyCode, SetEditorResizeOperation } from '@univerjs/ui';+import { COMMAND_LISTENER_SKELETON_CHANGE, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';+import { KeyCode, SetEditorResizeOperation } from '@univerjs/ui';import { distinctUntilChanged, filter } from 'rxjs';-import type { DocumentDataModel, ICellData, ICommandInfo, IDisposable, IDocumentBody, IDocumentData, IPosition, IStyleData, Nullable, UnitModel, Workbook } from '@univerjs/core';-import type { IRichTextEditingMutationParams } from '@univerjs/docs';-import type { IEditorInputConfig } from '@univerjs/docs-ui';--import type { DocumentSkeleton, IDocumentLayoutObject, IRenderContext, IRenderModule, Scene } from '@univerjs/engine-render';-import type { WorkbookSelections } from '@univerjs/sheets';import { getEditorObject } from '../../basics/editor/get-editor-object';import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';-import { SetCellEditVisibleArrowOperation, SetCellEditVisibleOperation, SetCellEditVisibleWithF2Operation } from '../../commands/operations/cell-edit.operation';+import { SetCellEditVisibleArrowOperation, SetCellEditVisibleWithF2Operation } from '../../commands/operations/cell-edit.operation';import { ScrollToRangeOperation } from '../../commands/operations/scroll-to-range.operation';import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';+import { SheetCellEditorResizeService } from '../../services/editor/cell-editor-resize.service';import { IEditorBridgeService } from '../../services/editor-bridge.service';-import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';-import styles from '../../views/sheet-container/index.module.less';import { MOVE_SELECTION_KEYCODE_LIST } from '../shortcuts/editor.shortcut';import { extractStringFromForceString, isForceString } from '../utils/cell-tools';import { normalizeString } from '../utils/char-tools';import { isRangeSelector } from './utils/isRangeSelector';-import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';const HIDDEN_EDITOR_POSITION = -1000;-const EDITOR_INPUT_SELF_EXTEND_GAP = 5;--const EDITOR_BORDER_SIZE = 2;--interface ICanvasOffset {- left: number;- top: number;-}-enum CursorChange {InitialState,StartEditor,@@ -112,7 +94,6 @@ export class EditingRenderController extends Disposable implements IRenderModuleconstructor(private readonly _context: IRenderContext<Workbook>,- @ILayoutService private readonly _layoutService: ILayoutService,@Inject(SheetsSelectionsService) selectionManagerService: SheetsSelectionsService,@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,@IContextService private readonly _contextService: IContextService,@@ -126,7 +107,7 @@ export class EditingRenderController extends Disposable implements IRenderModule@ICommandService private readonly _commandService: ICommandService,@Inject(LocaleService) protected readonly _localService: LocaleService,@IEditorService private readonly _editorService: IEditorService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService+ @Inject(SheetCellEditorResizeService) private readonly _sheetCellEditorResizeService: SheetCellEditorResizeService) {super();@@ -171,7 +152,6 @@ export class EditingRenderController extends Disposable implements IRenderModuleprivate _init(): IDisposable {const d = new DisposableCollection();this._subscribeToCurrentCell(d);- this._initialKeyboardListener(d);this._initialCursorSync(d);this._listenEditorFocus(d);this._commandExecutedListener(d);@@ -190,17 +170,19 @@ export class EditingRenderController extends Disposable implements IRenderModule}private _initEditorVisibilityListener(): void {- this.disposeWithMe(this._editorBridgeService.visible$- .pipe(distinctUntilChanged((prev, curr) => prev.visible === curr.visible))- .subscribe((param) => {- if ((param.unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY || param.unitId === this._context.unitId) && param.visible) {- this._isUnitEditing = true;- this._handleEditorVisible(param);- } else if (this._isUnitEditing) {- this._handleEditorInvisible(param);- this._isUnitEditing = false;- }- }));+ this.disposeWithMe(+ this._editorBridgeService.visible$+ .pipe(distinctUntilChanged((prev, curr) => prev.visible === curr.visible))+ .subscribe((param) => {+ if ((param.unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY || param.unitId === this._context.unitId) && param.visible) {+ this._isUnitEditing = true;+ this._handleEditorVisible(param);+ } else if (this._isUnitEditing) {+ this._handleEditorInvisible(param);+ this._isUnitEditing = false;+ }+ })+ );}private _listenEditorFocus(d: DisposableCollection) {@@ -218,23 +200,11 @@ export class EditingRenderController extends Disposable implements IRenderModulereturn;}- const skeleton = this._getEditorSkeleton(editorId);- if (!skeleton) return;-- const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;- this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);+ this._sheetCellEditorResizeService.fitTextSize();}}));}- private _getEditorSkeleton(editorId: string) {- return this._renderManagerService.getRenderById(editorId)?.with(DocSkeletonManagerService).getSkeleton();- }-- private _getEditorViewModel(editorId: string) {- return this._renderManagerService.getRenderById(editorId)?.with(DocSkeletonManagerService).getViewModel();- }-private _initialCursorSync(d: DisposableCollection) {d.add(this._cellEditorManagerService.focus$.pipe(filter((f) => !!f)).subscribe(() => {const docSelectionRenderManager = this._renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_DOC)?.with(DocSelectionRenderService);@@ -253,46 +223,13 @@ export class EditingRenderController extends Disposable implements IRenderModuleif (!commandList.has(commandInfo.id)) {return;}- this.resizeCellEditor();- }));- }-- resizeCellEditor() {- const state = this._cellEditorManagerService.getState();-- if (!state) return;- if (!this._editorBridgeService.isVisible().visible) return;- this._editorBridgeService.refreshEditCellPosition(true);- const editCellState = this._editorBridgeService.getEditCellState();- if (!editCellState) return;-- const skeleton = this._sheetSkeletonManagerService.getWorksheetSkeleton(editCellState.sheetId)?.skeleton;- if (!skeleton) return;- const { row, column, scaleX, scaleY, position, canvasOffset, documentLayoutObject } = editCellState;- const maxSize = this._getEditorMaxSize(position, canvasOffset);- if (!maxSize) return;- const { height: clientHeight, width: clientWidth, scaleAdjust } = maxSize;-- const cell = skeleton.getCellByIndex(row, column);- const height = Math.min((cell.mergeInfo.endY - cell.mergeInfo.startY) * scaleY, clientHeight) * scaleAdjust;- const width = Math.min((cell.mergeInfo.endX - cell.mergeInfo.startX) * scaleX, clientWidth) * scaleAdjust;- const currentHeight = state.endY! - state.startY!;- const currentWidth = state.endX! - state.startX!;-- if (currentHeight !== height || currentWidth !== width) {- this._editorBridgeService.refreshEditCellPosition(true);-- const docSkeleton = this._getEditorSkeleton(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);- if (!docSkeleton) {- return;- }- this._fitTextSize(position, canvasOffset, docSkeleton, documentLayoutObject, scaleX, scaleY, () => {+ this._sheetCellEditorResizeService.resizeCellEditor(() => {this._textSelectionManagerService.refreshSelection({unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,});});- }+ }));}/**@@ -307,7 +244,13 @@ export class EditingRenderController extends Disposable implements IRenderModulereturn;}- const { position, documentLayoutObject, scaleX, editorUnitId } = editCellState;+ const state = this._editorBridgeService.getEditCellState();+ if (state == null) {+ return;+ }++ const { position, documentLayoutObject, scaleX, editorUnitId } = state;+if (this._contextService.getContextValue(FOCUSING_EDITOR_STANDALONE) ||this._contextService.getContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)@@ -343,306 +286,68 @@ export class EditingRenderController extends Disposable implements IRenderModule}));}- private _fitTextSize(- actualRangeWithCoord: IPosition,- canvasOffset: ICanvasOffset,- documentSkeleton: DocumentSkeleton,- documentLayoutObject: IDocumentLayoutObject,- scaleX: number = 1,- scaleY: number = 1,- callback?: () => void- ) {- const { startX, startY, endX, endY } = actualRangeWithCoord;- const documentDataModel = documentLayoutObject.documentModel;+ /**+ * Listen to document edits to refresh the size of the sheet editor, not for normal editor.+ */+ private _commandExecutedListener(d: DisposableCollection) {+ const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];- if (documentDataModel == null) {- return;- }+ d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (updateCommandList.includes(command.id)) {+ const params = command.params as IRichTextEditingMutationParams;+ const { unitId: commandUnitId } = params;- const { actualWidth, actualHeight } = this._predictingSize(- actualRangeWithCoord,- canvasOffset,- documentSkeleton,- documentLayoutObject,- scaleX,- scaleY- );- const { verticalAlign, paddingData, fill } = documentLayoutObject;+ // Only when the sheet it attached to is focused. Maybe we should change it to the render unit sys.+ if (+ !this._isCurrentSheetFocused() ||+ !this._editorService.isSheetEditor(commandUnitId) ||+ isRangeSelector(commandUnitId)+ ) {+ return;+ }- let editorWidth = endX - startX;- let editorHeight = endY - startY;+ this._editorBridgeService.changeEditorDirty(true);- if (editorWidth < actualWidth) {- editorWidth = actualWidth;- }+ if (!this._editorBridgeService.isVisible().visible) {+ return;+ }- if (editorHeight < actualHeight) {- editorHeight = actualHeight;- // To restore the page margins for the skeleton.- documentDataModel.updateDocumentDataMargin(paddingData);- } else {- // Set the top margin under vertical alignment.- let offsetTop = 0;-- if (verticalAlign === VerticalAlign.MIDDLE) {- offsetTop = (editorHeight - actualHeight) / 2 / scaleY;- } else if (verticalAlign === VerticalAlign.TOP) {- offsetTop = paddingData.t || 0;- } else { // VerticalAlign.UNSPECIFIED follow the same rule as HorizontalAlign.BOTTOM.- offsetTop = (editorHeight - actualHeight) / scaleY - (paddingData.b || 0);+ if (commandUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {+ this._sheetCellEditorResizeService.fitTextSize();+ }}+ }));- // offsetTop /= scaleY;- offsetTop = offsetTop < (paddingData.t || 0) ? paddingData.t || 0 : offsetTop;-- documentDataModel.updateDocumentDataMargin({- t: offsetTop,- });- }-- // re-calculate skeleton(viewModel for component)- documentSkeleton.calculate();-- this._editAreaProcessing(editorWidth, editorHeight, actualRangeWithCoord, canvasOffset, fill, scaleX, scaleY, callback);- }-- /**- * Mainly used to pre-calculate the width of the editor,- * to determine whether it needs to be automatically widened.- */- private _predictingSize(- actualRangeWithCoord: IPosition,- canvasOffset: ICanvasOffset,- documentSkeleton: DocumentSkeleton,- documentLayoutObject: IDocumentLayoutObject,- scaleX: number = 1,- scaleY: number = 1- ) {- // startX and startY are the width and height after scaling.- const { startX, endX } = actualRangeWithCoord;-- const { textRotation, wrapStrategy } = documentLayoutObject;-- const documentDataModel = documentLayoutObject.documentModel;-- const { vertexAngle: angle } = convertTextRotation(textRotation);-- const clientWidth = document.body.clientWidth;-- if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {- const { actualWidth, actualHeight } = documentSkeleton.getActualSize();- // The skeleton obtains the original volume, which needs to be multiplied by the magnification factor.- return {- actualWidth: actualWidth * scaleX,- actualHeight: actualHeight * scaleY,- };- }-- documentDataModel?.updateDocumentDataPageSize((clientWidth - startX - canvasOffset.left) / scaleX);- documentSkeleton.calculate();-- const size = documentSkeleton.getActualSize();-- let editorWidth = endX - startX;-- if (editorWidth < size.actualWidth * scaleX + EDITOR_INPUT_SELF_EXTEND_GAP * scaleX) {- editorWidth = size.actualWidth * scaleX + EDITOR_INPUT_SELF_EXTEND_GAP * scaleX;- }-- // Scaling is handled by the renderer, so the skeleton only accepts the original width and height, which need to be divided by the magnification factor.- documentDataModel?.updateDocumentDataPageSize(editorWidth / scaleX);-- /**- * Do not rely on cell layout logic, depend on the document's internal alignment logic.- */- documentDataModel?.updateDocumentRenderConfig({- horizontalAlign: HorizontalAlign.UNSPECIFIED,- cellValueType: undefined,- });-- return {- actualWidth: editorWidth,- actualHeight: size.actualHeight * scaleY,- };- }-- private _getEditorMaxSize(position: IPosition, canvasOffset: ICanvasOffset) {- const editorObject = this._getEditorObject();- if (editorObject == null) {- return;- }- function pxToNum(width: string): number {- return Number.parseInt(width.replace('px', ''));- }-- const engine = this._context.engine;- const canvasElement = engine.getCanvasElement();- const canvasClientRect = canvasElement.getBoundingClientRect();-- // We should take the scale into account when canvas is scaled by CSS.- const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width- const { width } = canvasClientRect; // real width affected by scale- const scaleAdjust = width / widthOfCanvas;-- const { startX, startY } = position;-- const clientHeight =- document.body.clientHeight -- startY -- Number.parseFloat(styles.sheetFooterBarHeight) -- canvasOffset.top -- EDITOR_BORDER_SIZE * 2;-- const clientWidth = document.body.clientWidth - startX - canvasOffset.left;-- return {- height: clientHeight,- width: clientWidth,- scaleAdjust,- };- }-- /**- * Mainly used to calculate the volume of scenes and objects,- * determine whether a scrollbar appears,- * and calculate the editor's boundaries relative to the browser.- */- private _editAreaProcessing(- editorWidth: number,- editorHeight: number,- actualRangeWithCoord: IPosition,- canvasOffset: ICanvasOffset,- fill: Nullable<string>,- scaleX: number = 1,- scaleY: number = 1,- callback?: () => void- ) {- const editorObject = this._getEditorObject();- if (editorObject == null) {- return;- }-- const engine = this._context.engine;- const canvasElement = engine.getCanvasElement();-- // We should take the scale into account when canvas is scaled by CSS.-- let { startX, startY } = actualRangeWithCoord;-- const { document: documentComponent, scene: editorScene, engine: docEngine } = editorObject;- const viewportMain = editorScene.getViewport(DOC_VIEWPORT_KEY.VIEW_MAIN);-- const info = this._getEditorMaxSize(actualRangeWithCoord, canvasOffset);- if (!info) return;- const { height: clientHeight, width: clientWidth, scaleAdjust } = info;-- let physicHeight = editorHeight;-- let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;+ const closeEditorOperation = [SetCellEditVisibleArrowOperation.id];+ d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (closeEditorOperation.includes(command.id)) {+ const params = command.params as IEditorBridgeServiceVisibleParam & { isShift: boolean };+ const { keycode, isShift } = params;- if (physicHeight > clientHeight) {- physicHeight = clientHeight;+ /**+ * After the user enters the editor and actively moves the editor selection area with the mouse,+ * the up, down, left, and right keys can no longer switch editing cells,+ * but move the cursor within the editor instead.+ */+ if (keycode != null &&+ (this._cursorChange === CursorChange.CursorChange || this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR))+ ) {+ this._moveInEditor(keycode, isShift);+ return;+ }- if (scrollBar == null) {- viewportMain && new ScrollBar(viewportMain, { enableHorizontal: false, barSize: 8 });- } else {- viewportMain?.resetCanvasSizeAndUpdateScroll();+ // TODO@Jocs: After we merging editor related controllers, this seems verbose.+ // We can directly call SetRangeValues here.+ this._editorBridgeService.changeVisible(params);}- } else {- scrollBar = null;- viewportMain?.getScrollBar()?.dispose();- }-- editorWidth += scrollBar?.barSize || 0;-- if (editorWidth > clientWidth) {- editorWidth = clientWidth;- }- startX -= FIX_ONE_PIXEL_BLUR_OFFSET;- startY -= FIX_ONE_PIXEL_BLUR_OFFSET;-- this._addBackground(editorScene, editorWidth / scaleX, editorHeight / scaleY, fill);-- const { scaleX: precisionScaleX, scaleY: precisionScaleY } = editorScene.getPrecisionScale();-- editorScene.transformByState({- width: editorWidth * scaleAdjust / scaleX,- height: editorHeight * scaleAdjust / scaleY,- scaleX: scaleX * scaleAdjust,- scaleY: scaleY * scaleAdjust,- });-- documentComponent.resize(editorWidth * scaleAdjust / scaleX, editorHeight * scaleAdjust / scaleY);-- /**- * sometimes requestIdleCallback is invalid, so use setTimeout to ensure the successful execution of the resizeBySize method.- * resize canvas- * When modifying the selection area for a formula, it is necessary to add a setTimeout to ensure successful updating.- */- setTimeout(() => {- docEngine.resizeBySize(- fixLineWidthByScale(editorWidth, precisionScaleX),- fixLineWidthByScale(physicHeight, precisionScaleY)- );-- callback?.();- }, 0);-- const contentBoundingRect = this._layoutService.getContentElement().getBoundingClientRect();- const canvasBoundingRect = canvasElement.getBoundingClientRect();- startX = startX * scaleAdjust + (canvasBoundingRect.left - contentBoundingRect.left);- startY = startY * scaleAdjust + (canvasBoundingRect.top - contentBoundingRect.top);-- // Update cell editor container position and size.- this._cellEditorManagerService.setState({- startX,- startY,- endX: editorWidth * scaleAdjust + startX,- endY: physicHeight * scaleAdjust + startY,- show: true,- });- }-- /**- * Since the document does not support cell background color, an additional rect needs to be added.- */- private _addBackground(scene: Scene, editorWidth: number, editorHeight: number, fill?: Nullable<string>) {- const fillRectKey = '_backgroundRectHelperColor_';- const rect = scene.getObject(fillRectKey) as Rect;-- if (rect == null && fill == null) {- return;- }-- if (rect == null) {- scene.addObjects(- [- new Rect(fillRectKey, {- width: editorWidth,- height: editorHeight,- fill,- evented: false,- }),- ],- DOCS_COMPONENT_MAIN_LAYER_INDEX- );- } else if (fill == null) {- rect.dispose();- } else {- rect.setProps({- fill,- });-- rect.transformByState({- width: editorWidth,- height: editorHeight,- });- }+ if (command.id === SetCellEditVisibleWithF2Operation.id) {+ this._cursorChange = CursorChange.CursorChange;+ }+ }));}// You can double-click on the cell or input content by keyboard to put the cell into the edit state.-private _handleEditorVisible(param: IEditorBridgeServiceVisibleParam) {const { eventType, keycode } = param;@@ -652,7 +357,7 @@ export class EditingRenderController extends Disposable implements IRenderModule? CursorChange.CursorChange: CursorChange.StartEditor;- let editCellState = this._editorBridgeService.getEditCellState();+ const editCellState = this._editorBridgeService.getEditLocation();if (editCellState == null) {return;}@@ -667,17 +372,9 @@ export class EditingRenderController extends Disposable implements IRenderModule});this._editorBridgeService.refreshEditCellPosition(false);- editCellState = this._editorBridgeService.getEditCellState();- if (editCellState == null) {- return;- }const {- position,documentLayoutObject,- canvasOffset,- scaleX,- scaleY,editorUnitId,unitId,sheetId,@@ -702,24 +399,19 @@ export class EditingRenderController extends Disposable implements IRenderModulereturn;}- this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);+ this._sheetCellEditorResizeService.fitTextSize(() => {+ const viewMain = scene.getViewport(DOC_VIEWPORT_KEY.VIEW_MAIN);+ viewMain?.scrollToViewportPos({+ viewportScrollX: Number.POSITIVE_INFINITY,+ viewportScrollY: Number.POSITIVE_INFINITY,+ });+ });// move selectionif (eventType === DeviceInputEventType.Keyboard ||(eventType === DeviceInputEventType.Dblclick && isInArrayFormulaRange)) {- const snapshot = Tools.deepClone(documentDataModel.getSnapshot());- const documentViewModel = this._getEditorViewModel(editorUnitId);-- if (documentViewModel == null) {- return;- }-- this._resetBodyStyle(snapshot.body!, !!isInArrayFormulaRange);-- documentDataModel.reset(snapshot);- documentViewModel.reset(documentDataModel);-+ this._emptyDocumentDataModel(!!isInArrayFormulaRange);document.makeDirty();// @JOCS, Why calculate here?@@ -728,17 +420,20 @@ export class EditingRenderController extends Disposable implements IRenderModulethis._editorBridgeService.changeEditorDirty(true);}- this._textSelectionManagerService.replaceTextRanges([+ this._textSelectionManagerService.replaceDocRanges([{startOffset: 0,endOffset: 0,},]);} else if (eventType === DeviceInputEventType.Dblclick) {- // TODO: @JOCS, Get the position close to the cursor after clicking on the cell.+ if (this._contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)) {+ return;+ }+const cursor = documentDataModel.getBody()!.dataStream.length - 2 || 0;- this._textSelectionManagerService.replaceTextRanges([+ this._textSelectionManagerService.replaceDocRanges([{startOffset: cursor,endOffset: cursor,@@ -746,213 +441,9 @@ export class EditingRenderController extends Disposable implements IRenderModule]);}- const viewMain = scene.getViewport(DOC_VIEWPORT_KEY.VIEW_MAIN);- // TODO@weird94, this should be optimized.- // currently, we must wait for the resize to complete before scrolling to the selection,- setTimeout(() => {- viewMain?.scrollToViewportPos({- viewportScrollX: Number.POSITIVE_INFINITY,- viewportScrollY: Number.POSITIVE_INFINITY,- });- }, 10);this._renderManagerService.getRenderById(unitId)?.scene.resetCursor();}- private _resetBodyStyle(body: IDocumentBody, removeStyle = false) {- body.dataStream = DEFAULT_EMPTY_DOCUMENT_VALUE;-- if (body.textRuns != null) {- if (body.textRuns.length === 1 && !removeStyle) {- body.textRuns[0].st = 0;- body.textRuns[0].ed = 1;- } else {- body.textRuns = undefined;- }- }-- if (body.paragraphs != null) {- if (body.paragraphs.length === 1) {- body.paragraphs[0].startIndex = 0;- } else {- body.paragraphs = [- {- startIndex: 0,- },- ];- }- }-- if (body.sectionBreaks != null) {- body.sectionBreaks = undefined;- }-- if (body.tables != null) {- body.tables = undefined;- }-- if (body.customRanges != null) {- body.customRanges = undefined;- }-- if (body.customBlocks != null) {- body.customBlocks = undefined;- }- }-- /**- * Should activate the editor when the user inputs text.- * @param d DisposableCollection- */- private _initialKeyboardListener(d: DisposableCollection) {- const docSelectionRenderService = this._renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_DOC)?.with(DocSelectionRenderService);-- if (docSelectionRenderService) {- d.add(docSelectionRenderService.onInputBefore$.subscribe((config) => {- if (!this._isCurrentSheetFocused()) {- return;- }-- const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR);- const isFocusSheets = this._contextService.getContextValue(FOCUSING_SHEET);- // TODO@Jocs: should get editor instead of current doc- const unitId = this._instanceSrv.getCurrentUniverDocInstance()?.getUnitId();- if (unitId && isFocusSheets && !isFocusFormulaEditor && this._editorService.isSheetEditor(unitId)) {- this._showEditorByKeyboard(config);- }- }));- }- }-- private _showEditorByKeyboard(config: Nullable<IEditorInputConfig>) {- if (config == null) {- return;- }-- const event = config.event as KeyboardEvent;-- this._commandService.executeCommand(SetCellEditVisibleOperation.id, {- visible: true,- eventType: DeviceInputEventType.Keyboard,- keycode: event.which,- unitId: this._context.unitId,- });- }-- /**- * Listen to document edits to refresh the size of the sheet editor, not for normal editor.- */- private _commandExecutedListener(d: DisposableCollection) {- const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];-- d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (updateCommandList.includes(command.id)) {- const params = command.params as IRichTextEditingMutationParams;- const { unitId: commandUnitId } = params;-- // Only when the sheet it attached to is focused. Maybe we should change it to the render unit sys.- if (- !this._isCurrentSheetFocused() ||- !this._editorService.isSheetEditor(commandUnitId) ||- isRangeSelector(commandUnitId)- ) {- return;- }-- const editorId = this._editorBridgeService.getCurrentEditorId();- if (editorId == null) {- return;- }-- const skeleton = this._getEditorSkeleton(editorId);- if (skeleton == null) {- return;- }-- this._editorBridgeService.changeEditorDirty(true);-- const param = this._editorBridgeService.getEditCellState();- if (param == null) {- return;- }-- const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;-- if (!this._editorBridgeService.isVisible().visible) {- return;- }-- if (commandUnitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {- // FIXME: this should be fixed on next refactor- // currently, we need to wait util content was synced to cell-editor, than fit size- setTimeout(() => {- this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);- }, 0);- } else {- this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);- }- }- }));-- // Use fix https://github.com/dream-num/univer/issues/1231.- d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id === ClearSelectionFormatCommand.id) {- if (this._editorBridgeService.isVisible().visible) return;- this._editorBridgeService.refreshEditCellState();- }- }));-- d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id === SetRangeValuesMutation.id) {- if (this._editorBridgeService.isVisible().visible) return;- this._editorBridgeService.refreshEditCellState();- }- }));-- const closeEditorOperation = [SetCellEditVisibleArrowOperation.id];- d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (closeEditorOperation.includes(command.id)) {- const params = command.params as IEditorBridgeServiceVisibleParam & { isShift: boolean };- const { keycode, isShift } = params;-- /**- * After the user enters the editor and actively moves the editor selection area with the mouse,- * the up, down, left, and right keys can no longer switch editing cells,- * but move the cursor within the editor instead.- */- if (keycode != null &&- (this._cursorChange === CursorChange.CursorChange || this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR))- ) {- this._moveInEditor(keycode, isShift);- return;- }-- // TODO@Jocs: After we merging editor related controllers, this seems verbose.- // We can directly call SetRangeValues here.- this._editorBridgeService.changeVisible(params);- }-- if (command.id === SetCellEditVisibleWithF2Operation.id) {- this._cursorChange = CursorChange.CursorChange;- }- }));- }-- private _setOpenForCurrent(unitId: Nullable<string>, sheetId: Nullable<string>) {- const sheetEditors = this._editorService.getAllEditor();- for (const [_, sheetEditor] of sheetEditors) {- if (!sheetEditor.isSheetEditor()) {- continue;- }-- sheetEditor.setOpenForSheetUnitId(unitId);- sheetEditor.setOpenForSheetSubUnitId(sheetId);- }- }-- private _getEditorObject() {- return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);- }-private async _handleEditorInvisible(param: IEditorBridgeServiceVisibleParam) {const editCellState = this._editorBridgeService.getEditCellState();@@ -1016,6 +507,22 @@ export class EditingRenderController extends Disposable implements IRenderModulethis._moveCursor(keycode);}+ private _setOpenForCurrent(unitId: Nullable<string>, sheetId: Nullable<string>) {+ const sheetEditors = this._editorService.getAllEditor();+ for (const [_, sheetEditor] of sheetEditors) {+ if (!sheetEditor.isSheetEditor()) {+ continue;+ }++ sheetEditor.setOpenForSheetUnitId(unitId);+ sheetEditor.setOpenForSheetSubUnitId(sheetId);+ }+ }++ private _getEditorObject() {+ return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);+ }+submitCellData(documentDataModel: DocumentDataModel) {return this._submitCellData(documentDataModel);}@@ -1053,23 +560,7 @@ export class EditingRenderController extends Disposable implements IRenderModulereturn;}- const context = {- subUnitId: sheetId,- unitId,- workbook: workbook!,- worksheet,- row,- col: column,- origin: Tools.deepClone(cellData),- };- const cell = this._editorBridgeService.interceptor.fetchThroughInterceptors(- this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT- )(cellData, context);-- const finalCell = await this._editorBridgeService.interceptor.fetchThroughInterceptors(- this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT_ASYNC- )(Promise.resolve(cell), context);- // remove temp value+ const finalCell = await this._editorBridgeService.beforeSetRangeValue(workbook, worksheet, row, column, cellData);this._commandService.executeCommand(SetRangeValuesCommand.id, {subUnitId: sheetId,@@ -1188,6 +679,39 @@ export class EditingRenderController extends Disposable implements IRenderModuleprivate _isCurrentSheetFocused(): boolean {return this._instanceSrv.getFocusedUnit()?.getUnitId() === this._context.unitId;}++ private _getEditorSkeleton(editorId: string) {+ return this._renderManagerService.getRenderById(editorId)?.with(DocSkeletonManagerService).getSkeleton();+ }++ private _getEditorViewModel(editorId: string) {+ return this._renderManagerService.getRenderById(editorId)?.with(DocSkeletonManagerService).getViewModel();+ }++ private _emptyDocumentDataModel(removeStyle: boolean) {+ const editCellState = this._editorBridgeService.getEditCellState();+ if (editCellState == null) {+ return;+ }++ const { documentLayoutObject, editorUnitId } = editCellState;+ const documentDataModel = documentLayoutObject.documentModel;+ if (documentDataModel == null) {+ return;+ }++ const snapshot = Tools.deepClone(documentDataModel.getSnapshot());+ const documentViewModel = this._getEditorViewModel(editorUnitId);++ if (documentViewModel == null) {+ return;+ }++ resetBodyStyle(snapshot.body!, removeStyle);++ documentDataModel.reset(snapshot);+ documentViewModel.reset(documentDataModel);+ }}export function getCellDataByInput(@@ -1262,7 +786,7 @@ export function getCellDataByInput(cellData.t = CellValueType.NUMBER;} else {// If the data is empty, the data is set to null.- if ((newDataStream === cellData.v || (newDataStream === '' && cellData.v == null)) && cellData.p == null) {+ if (newDataStream === '' && cellData.v == null && cellData.p == null) {return null;}cellData.v = newDataStream;@@ -1319,3 +843,44 @@ export function getCellStyleBySnapshot(snapshot: IDocumentData): Nullable<IStyle}return null;}++function resetBodyStyle(body: IDocumentBody, removeStyle = false) {+ body.dataStream = DEFAULT_EMPTY_DOCUMENT_VALUE;++ if (body.textRuns != null) {+ if (body.textRuns.length === 1 && !removeStyle) {+ body.textRuns[0].st = 0;+ body.textRuns[0].ed = 1;+ } else {+ body.textRuns = undefined;+ }+ }++ if (body.paragraphs != null) {+ if (body.paragraphs.length === 1) {+ body.paragraphs[0].startIndex = 0;+ } else {+ body.paragraphs = [+ {+ startIndex: 0,+ },+ ];+ }+ }++ if (body.sectionBreaks != null) {+ body.sectionBreaks = undefined;+ }++ if (body.tables != null) {+ body.tables = undefined;+ }++ if (body.customRanges != null) {+ body.customRanges = undefined;+ }++ if (body.customBlocks != null) {+ body.customBlocks = undefined;+ }+}diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.tsindex 1ce9d0945f..a827506c95 100644--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts@@ -14,26 +14,21 @@* limitations under the License.*/-import type { DocumentDataModel, ICommandInfo, ICustomRange, IParagraph, ITextRun, JSONXActions, Nullable } from '@univerjs/core';-import type { IRichTextEditingMutationParams } from '@univerjs/docs';-import type { DocumentViewModel, RenderComponentType } from '@univerjs/engine-render';-import type { IMoveRangeMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';-import type { IEditorBridgeServiceParam } from '../../services/editor-bridge.service';+import type { Nullable } from '@univerjs/core';+import type {+ IRichTextEditingMutationParams } from '@univerjs/docs';+import type { RenderComponentType } from '@univerjs/engine-render';import {- BooleanNumber,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,EDITOR_ACTIVATED,FOCUSING_EDITOR_BUT_HIDDEN,FOCUSING_FX_BAR_EDITOR,- HorizontalAlign,ICommandService,IContextService,Inject,IUndoRedoService,IUniverInstanceService,RxDisposable,- Tools,UniverInstanceType,} from '@univerjs/core';import {@@ -44,8 +39,6 @@ import {import { CoverContentCommand, VIEWPORT_KEY as DOC_VIEWPORT_KEY } from '@univerjs/docs-ui';import { DeviceInputEventType, IRenderManagerService, ScrollBar } from '@univerjs/engine-render';-import { MoveRangeMutation, RangeProtectionRuleModel, SetRangeValuesMutation, WorksheetProtectionRuleModel } from '@univerjs/sheets';-import { SetEditorResizeOperation } from '@univerjs/ui';import { takeUntil } from 'rxjs';import { getEditorObject } from '../../basics/editor/get-editor-object';import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';@@ -62,8 +55,6 @@ export class FormulaEditorController extends RxDisposable {@IContextService private readonly _contextService: IContextService,@IFormulaEditorManagerService private readonly _formulaEditorManagerService: IFormulaEditorManagerService,@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,- @Inject(RangeProtectionRuleModel) private readonly _rangeProtectionRuleModel: RangeProtectionRuleModel,- @Inject(WorksheetProtectionRuleModel) private readonly _worksheetProtectionRuleModel: WorksheetProtectionRuleModel,@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService) {super();@@ -72,11 +63,9 @@ export class FormulaEditorController extends RxDisposable {}private _initialize() {- this._syncFormulaEditorContent();- this._commandExecutedListener();this._syncEditorSize();this._listenFxBtnClick();- this._listenFoldBtnClick();+ this._handleContentChange();this._renderManagerService.currentRender$.pipe(takeUntil(this.dispose$)).subscribe((unitId) => {this._create(unitId);@@ -97,6 +86,20 @@ export class FormulaEditorController extends RxDisposable {});}+ private _handleContentChange() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === RichTextEditingMutation.id) {+ const params = commandInfo.params as IRichTextEditingMutationParams;+ const { unitId } = params;+ if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ this.autoScroll();+ }+ }+ })+ );+ }+private _create(unitId: Nullable<string>) {if (unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {return;@@ -170,17 +173,11 @@ export class FormulaEditorController extends RxDisposable {this._commandService.executeCommand(CoverContentCommand.id, coverContentParams);- this._textSelectionManagerService.replaceTextRanges(textRanges);+ this._textSelectionManagerService.replaceDocRanges(textRanges);}});}- private _listenFoldBtnClick() {- this._formulaEditorManagerService.foldBtnStatus$.pipe(takeUntil(this.dispose$)).subscribe(() => {- this._textSelectionManagerService.refreshSelection();- });- }-private _initialMain(unitId: string) {const formulaEditorDocObject = this._renderManagerService.getRenderById(unitId);if (formulaEditorDocObject == null) {@@ -203,11 +200,11 @@ export class FormulaEditorController extends RxDisposable {eventType: DeviceInputEventType.Dblclick,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);- this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);}));}@@ -229,7 +226,7 @@ export class FormulaEditorController extends RxDisposable {const { engine } = editorObject;formulaEditorDataModel.updateDocumentDataPageSize(width);- this._autoScroll();+ this.autoScroll();this._scheduledCallback = requestIdleCallback(() => engine.resizeBySize(width, height));});}@@ -240,297 +237,7 @@ export class FormulaEditorController extends RxDisposable {this._scheduledCallback = -1;}- // Sync cell content to formula editor bar when sheet selection changed.- private _syncFormulaEditorContent() {- this._editorBridgeService.currentEditCellState$.pipe(takeUntil(this.dispose$)).subscribe((editCellState) => {- if (- editCellState == null- || this._editorBridgeService.isForceKeepVisible()- // If permissions are not initialized, data synchronization will not be performed.- || !this._rangeProtectionRuleModel.getRangeRuleInitState()- || !this._worksheetProtectionRuleModel.getSheetRuleInitState()- ) {- return;- }-- this._editorSyncHandler(editCellState);- });-- this._editorBridgeService.visible$.pipe(takeUntil(this.dispose$)).subscribe((state) => {- if (state == null || state.visible === false || this._editorBridgeService.isForceKeepVisible()) {- return;- }-- const cellEditState = this._editorBridgeService.getLatestEditCellState();-- if (cellEditState == null) {- return;- }-- this._editorSyncHandler(cellEditState);- });- }-- // Sync cell content to formula editor bar when sheet selection changed or visible changed.- private _editorSyncHandler(param: IEditorBridgeServiceParam) {- const body = param.documentLayoutObject.documentModel?.getBody();-- let dataStream = body?.dataStream;- let paragraphs = body?.paragraphs;- let textRuns = body?.textRuns;- const customRanges = body?.customRanges;-- if (dataStream == null || (!paragraphs && !customRanges)) {- return;- }-- if (- param.isInArrayFormulaRange === true &&- this._editorBridgeService.isVisible().eventType === DeviceInputEventType.Dblclick- ) {- dataStream = '\r\n';- paragraphs = [- {- startIndex: 0,- },- ];- textRuns = [];- }-- this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs ?? [], textRuns, customRanges);-- // Also need to resize document and scene after sync content.- this._autoScroll();- }-- // eslint-disable-next-line max-lines-per-function- private _commandExecutedListener() {- const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];-- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id !== RichTextEditingMutation.id) {- return;- }- const params = command.params as IRichTextEditingMutationParams;- const { unitId, actions } = params;-- if (INCLUDE_LIST.includes(unitId)) {- // sync cell content to formula editor bar when edit cell editor and vice verse.- const editorDocDataModel = this._univerInstanceService.getUniverDocInstance(unitId);- const dataStream = editorDocDataModel?.getBody()?.dataStream;- const paragraphs = editorDocDataModel?.getBody()?.paragraphs;- const textRuns = editorDocDataModel?.getBody()?.textRuns;- const customRanges = editorDocDataModel?.getBody()?.customRanges;-- const syncId =- unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY- ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY- : DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;-- if (dataStream == null || paragraphs == null) {- return;- }-- if (syncId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {- this._checkAndSetRenderStyleConfig(editorDocDataModel!);- this._syncActionsAndRender(syncId, actions);- } else {- this._syncContentAndRender(syncId, dataStream, paragraphs, textRuns, customRanges);- }-- // handle weather need to show scroll bar.- this._autoScroll();- }- })- );-- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id !== SetEditorResizeOperation.id) {- return;- }-- const params = command.params as IRichTextEditingMutationParams;- const { unitId } = params;-- if (INCLUDE_LIST.includes(unitId)) {- // sync cell content to formula editor bar when edit cell editor and vice verse.- const editorDocDataModel = this._univerInstanceService.getUniverDocInstance(unitId);- const dataStream = editorDocDataModel?.getBody()?.dataStream;- const paragraphs = editorDocDataModel?.getBody()?.paragraphs;- const textRuns = editorDocDataModel?.getBody()?.textRuns;- const customRanges = editorDocDataModel?.getBody()?.customRanges;-- const syncId =- unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY- ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY- : DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;-- if (dataStream == null || paragraphs == null) {- return;- }-- this._syncContentAndRender(syncId, dataStream, paragraphs, textRuns, customRanges);-- // handle weather need to show scroll bar.- this._autoScroll();- }- })- );-- // Update formula bar content when you call SetRangeValuesMutation and MoveRangeMutation.- const needUpdateFormulaEditorContentCommandList = [SetRangeValuesMutation.id, MoveRangeMutation.id];- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (needUpdateFormulaEditorContentCommandList.includes(command.id)) {- const editCellState = this._editorBridgeService.getLatestEditCellState();-- if (editCellState == null) {- return;- }-- let needUpdate = false;-- const { row, column } = editCellState;-- if (command.id === SetRangeValuesMutation.id && command.params) {- const params = command.params as ISetRangeValuesMutationParams;- if (params.cellValue?.[row]?.[column]) {- needUpdate = true;- }- } else if (command.id === MoveRangeMutation.id && command.params) {- const params = command.params as IMoveRangeMutationParams;- if (params.to.value?.[row]?.[column]) {- needUpdate = true;- }- }-- if (needUpdate) {- const body = editCellState.documentLayoutObject.documentModel?.getBody();-- if (body == null) {- return;- }- const { dataStream, paragraphs = [], customRanges } = body;- this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, undefined, customRanges);- // handle weather need to show scroll bar.- this._autoScroll();- }- }- })- );- }-- // Sync actions between cell editor and formula editor, and make `dataStream` and `paragraph` is the same.- private _syncActionsAndRender(- unitId: string,- actions: JSONXActions- ) {- const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];- const currentRender = this._renderManagerService.getRenderById(unitId);- if (currentRender == null) {- return;- }-- const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();- const docDataModel = this._univerInstanceService.getUniverDocInstance(unitId);- const docViewModel = this._getEditorViewModel(unitId);-- if (docDataModel == null || docViewModel == null) {- return;- }-- // Update document data model.- docDataModel.apply(actions);-- this._checkAndSetRenderStyleConfig(docDataModel);-- docViewModel.reset(docDataModel);-- skeleton.calculate();-- if (INCLUDE_LIST.includes(unitId)) {- currentRender.mainComponent?.makeDirty();- }- }-- private _syncContentAndRender(- unitId: string,- dataStream: string,- paragraphs: IParagraph[],- textRuns: ITextRun[] = [],- customRanges: ICustomRange[] | undefined- ) {- const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];-- const skeleton = this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService).getSkeleton();- const docDataModel = this._univerInstanceService.getUniverDocInstance(unitId);- const docViewModel = this._getEditorViewModel(unitId);-- if (docDataModel == null || docViewModel == null || skeleton == null) {- return;- }-- docDataModel.getBody()!.dataStream = dataStream;- docDataModel.getBody()!.paragraphs = this._clearParagraph(paragraphs);- docDataModel.getBody()!.customRanges = customRanges;-- if (textRuns.length > 0) {- docDataModel.getBody()!.textRuns = textRuns;- }-- this._checkAndSetRenderStyleConfig(docDataModel);-- docViewModel.reset(docDataModel);-- const currentRender = this._renderManagerService.getRenderById(unitId);-- if (currentRender == null) {- return;- }-- skeleton.calculate();-- if (INCLUDE_LIST.includes(unitId)) {- currentRender.mainComponent?.makeDirty();- }- }-- private _checkAndSetRenderStyleConfig(documentDataModel: DocumentDataModel) {- const snapshot = documentDataModel.getSnapshot();- const { body } = snapshot;-- if (snapshot.id !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {- return;- }-- let renderConfig = snapshot.documentStyle.renderConfig;-- if (renderConfig == null) {- renderConfig = {};- snapshot.documentStyle.renderConfig = renderConfig;- }-- if ((body?.dataStream ?? '').startsWith('=')) {- renderConfig.isRenderStyle = BooleanNumber.TRUE;- } else {- renderConfig.isRenderStyle = BooleanNumber.FALSE;- }- }-- private _clearParagraph(paragraphs: IParagraph[]) {- const newParagraphs = Tools.deepClone(paragraphs);- for (const paragraph of newParagraphs) {- if (paragraph.paragraphStyle) {- paragraph.paragraphStyle.horizontalAlign = HorizontalAlign.UNSPECIFIED;- }- }-- return newParagraphs;- }-- private _autoScroll() {+ autoScroll() {const position = this._formulaEditorManagerService.getPosition();const skeleton = this._renderManagerService.getRenderById(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)?.with(DocSkeletonManagerService).getSkeleton();@@ -554,7 +261,6 @@ export class FormulaEditorController extends RxDisposable {const { width, height } = position;const viewportMain = scene.getViewport(DOC_VIEWPORT_KEY.VIEW_MAIN);-let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;scene.transformByState({@@ -576,8 +282,4 @@ export class FormulaEditorController extends RxDisposable {viewportMain?.getScrollBar()?.dispose();}}-- private _getEditorViewModel(unitId: string): Nullable<DocumentViewModel> {- return this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService).getViewModel();- }}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.tsindex 5aa5a84d0d..5f5877fb47 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@@ -14,14 +14,17 @@* limitations under the License.*/-import type { ICommandInfo, IDisposable, IExecutionOptions, Nullable, Workbook } from '@univerjs/core';+import type { ICommandInfo, IDisposable, IExecutionOptions, ISelectionCell, Nullable, Workbook } from '@univerjs/core';+import type { IEditorInputConfig } from '@univerjs/docs-ui';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import type { ISelectionWithStyle } from '@univerjs/sheets';import type { ICurrentEditCellParam, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';-import { DisposableCollection, ICommandService, Inject, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';-import { IRangeSelectorService } from '@univerjs/docs-ui';-import { DeviceInputEventType } from '@univerjs/engine-render';+import { DisposableCollection, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET, ICommandService, IContextService, Inject, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';+import { DocSelectionRenderService, IEditorService, IRangeSelectorService } from '@univerjs/docs-ui';+import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';import {+ ClearSelectionFormatCommand,+ SetRangeValuesMutation,SetWorksheetActiveOperation,SheetsSelectionsService,} from '@univerjs/sheets';@@ -30,6 +33,7 @@ import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.commimport { SetActivateCellEditOperation } from '../../commands/operations/activate-cell-edit.operation';import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';import { IEditorBridgeService } from '../../services/editor-bridge.service';+import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';import { getSheetObject } from '../utils/component-tools';// TODO: wzhudev: this should be merged with Edit EditingRenderController.@@ -46,7 +50,11 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende// FIXME: should check if it is the current sheet, if it becomes the current sheet,// it should update cell params, otherwise it should do nothing.@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,- @IRangeSelectorService private readonly _rangeSelectorService: IRangeSelectorService+ @IRangeSelectorService private readonly _rangeSelectorService: IRangeSelectorService,+ @IContextService private readonly _contextService: IContextService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @IEditorService private readonly _editorService: IEditorService,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService) {super();@@ -66,6 +74,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendethis._initSelectionChangeListener(d);this._initEventListener(d);this._commandExecutedListener(d);+ this._initialKeyboardListener(d);return d;}@@ -92,11 +101,23 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendeconst unitId = this._context.unitId;const sheetId = this._context.unit.getActiveSheet()?.getSheetId();if (!sheetId) return;-+ const mergeInfo = this._sheetSkeletonManagerService.getWorksheetSkeleton(sheetId)?.skeleton.getCellByIndex(primary.actualRow, primary.actualColumn);+ const newPrimary: ISelectionCell = mergeInfo+ ? {+ actualRow: mergeInfo.actualRow,+ actualColumn: mergeInfo.actualColumn,+ isMerged: mergeInfo.isMerged,+ startRow: mergeInfo.mergeInfo.startRow,+ startColumn: mergeInfo.mergeInfo.startColumn,+ endRow: mergeInfo.mergeInfo.endRow,+ endColumn: mergeInfo.mergeInfo.endColumn,+ isMergedMainCell: mergeInfo.isMergedMainCell,+ }+ : primary;this._commandService.executeCommand<ICurrentEditCellParam>(SetActivateCellEditOperation.id, {scene,engine,- primary,+ primary: newPrimary,unitId,sheetId,});@@ -119,10 +140,80 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende} as IEditorBridgeServiceVisibleParam);}));- d.add(spreadsheet.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));- d.add(spreadsheetColumnHeader.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));- d.add(spreadsheetLeftTopPlaceholder.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));- d.add(spreadsheetRowHeader.onPointerDown$.subscribeEvent(this._tryHideEditor.bind(this)));+ d.add(spreadsheet.onPointerDown$.subscribeEvent({+ next: this._tryHideEditor.bind(this),+ priority: -1,+ }));+ d.add(spreadsheetColumnHeader.onPointerDown$.subscribeEvent({+ next: this._tryHideEditor.bind(this),+ priority: -1,+ }));+ d.add(spreadsheetLeftTopPlaceholder.onPointerDown$.subscribeEvent({+ next: this._tryHideEditor.bind(this),+ priority: -1,+ }));+ d.add(spreadsheetRowHeader.onPointerDown$.subscribeEvent({+ next: this._tryHideEditor.bind(this),+ priority: -1,+ }));+ }++ /**+ * Should activate the editor when the user inputs text.+ * @param d DisposableCollection+ */+ private _initialKeyboardListener(d: DisposableCollection) {+ const docSelectionRenderService = this._renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_DOC)?.with(DocSelectionRenderService);++ if (docSelectionRenderService) {+ d.add(docSelectionRenderService.onInputBefore$.subscribe((config) => {+ if (!this._isCurrentSheetFocused()) {+ return;+ }++ const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR);+ const isFocusSheets = this._contextService.getContextValue(FOCUSING_SHEET);+ // TODO@Jocs: should get editor instead of current doc+ const unitId = this._instanceSrv.getCurrentUniverDocInstance()?.getUnitId();+ if (this._editorBridgeService.isVisible().visible) return;++ if (unitId && isFocusSheets && !isFocusFormulaEditor && this._editorService.isSheetEditor(unitId)) {+ this._showEditorByKeyboard(config);+ }+ }));+ }+ }++ private _commandExecutedListener(d: DisposableCollection) {+ const refreshCommandSet = new Set([ClearSelectionFormatCommand.id, SetRangeValuesMutation.id, SetZoomRatioCommand.id]);+ d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (refreshCommandSet.has(command.id)) {+ if (this._editorBridgeService.isVisible().visible) return;+ this._editorBridgeService.refreshEditCellState();+ }+ }));++ d.add(this._commandService.beforeCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {+ if (options?.fromCollab) return;+ if (command.id === SetWorksheetActiveOperation.id) {+ this._tryHideEditor();+ }+ }));+ }++ private _showEditorByKeyboard(config: Nullable<IEditorInputConfig>) {+ if (config == null) {+ return;+ }++ const event = config.event as KeyboardEvent;++ this._commandService.executeCommand(SetCellEditVisibleOperation.id, {+ visible: true,+ eventType: DeviceInputEventType.Keyboard,+ keycode: event.which,+ unitId: this._context.unitId,+ });}private _tryHideEditor() {@@ -138,7 +229,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendeprivate _hideEditor() {if (this._editorBridgeService.isVisible().visible !== true) return;- this._commandService.executeCommand(SetCellEditVisibleOperation.id, {+ this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {visible: false,eventType: DeviceInputEventType.PointerDown,unitId: this._context.unitId,@@ -199,24 +290,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendereturn getSheetObject(this._context.unit, this._context)!;}- private _commandExecutedListener(d: DisposableCollection) {- d.add(this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {- // When the zoom ratio is changed, the editor needs to be refreshed to get the latest cell size and position.- if (command.id === SetZoomRatioCommand.id) {- this._editorBridgeService.refreshEditCellState();- }-- // if (options?.fromCollab) return;- // if (command.id !== SetWorksheetActiveOperation.id && COMMAND_LISTENER_SKELETON_CHANGE.includes(command.id)) {- // this._hideEditor();- // }- }));-- d.add(this._commandService.beforeCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {- if (options?.fromCollab) return;- if (command.id === SetWorksheetActiveOperation.id) {- this._tryHideEditor();- }- }));+ private _isCurrentSheetFocused(): boolean {+ return this._instanceSrv.getFocusedUnit()?.getUnitId() === this._context.unitId;}}diff --git a/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts b/packages/sheets-ui/src/mobile-sheets-ui-plugin.tsindex 4dad681b6a..18ba371ca6 100644--- a/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts+++ b/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts@@ -20,6 +20,7 @@ import { DependentOn, Inject, Injector, IUniverInstanceService, Plugin, UniverInimport { IRenderManagerService } from '@univerjs/engine-render';import { UniverSheetsPlugin } from '@univerjs/sheets';+import { UniverMobileUIPlugin } from '@univerjs/ui';import { filter } from 'rxjs/operators';import { ActiveWorksheetController } from './controllers/active-worksheet/active-worksheet.controller';diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.tsindex ea8de1306c..458297f02e 100644--- a/packages/sheets-ui/src/services/editor-bridge.service.ts+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, ICellDataForSheetInterceptor, IDisposable, IPosition, ISelectionCell, Nullable, Workbook } from '@univerjs/core';+import type { ICellData, ICellDataForSheetInterceptor, IDisposable, IPosition, ISelectionCell, Nullable, Workbook, Worksheet } from '@univerjs/core';import type { Engine, IDocumentLayoutObject, Scene } from '@univerjs/engine-render';import type { ISheetLocation, SheetsSelectionsService } from '@univerjs/sheets';import type { KeyCode } from '@univerjs/ui';@@ -35,13 +35,13 @@ import {makeCellToSelection,ThemeService,toDisposable,+ Tools,UniverInstanceType,} from '@univerjs/core';import { getCanvasOffsetByEngine, IEditorService } from '@univerjs/docs-ui';import { convertTextRotation, DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';import { IRefSelectionsService } from '@univerjs/sheets';--import { BehaviorSubject } from 'rxjs';+import { BehaviorSubject, map, mergeMap } from 'rxjs';import { ISheetSelectionRenderService } from './selection/base-selection-render.service';import { attachPrimaryWithCoord } from './selection/util';import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';@@ -61,18 +61,25 @@ export interface ICurrentEditCellParam {primary: ISelectionCell;}-export interface IEditorBridgeServiceParam {+export interface ICellEditorState {unitId: string;sheetId: string;row: number;column: number;+ documentLayoutObject: IDocumentLayoutObject;+ editorUnitId: string;+ isInArrayFormulaRange?: Nullable<boolean>;+}++export interface ICellEditorLayout {position: IPosition;canvasOffset: { left: number; top: number };- documentLayoutObject: IDocumentLayoutObject;scaleX: number;scaleY: number;- editorUnitId: string;- isInArrayFormulaRange?: Nullable<boolean>;+}++export interface IEditorBridgeServiceParam extends ICellEditorState, ICellEditorLayout {+}interface ISheetLocationForEditor extends ISheetLocation {@@ -84,7 +91,10 @@ const AFTER_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheeconst AFTER_CELL_EDIT_ASYNC = createInterceptorKey<Promise<Nullable<ICellDataForSheetInterceptor>>, ISheetLocationForEditor>('AFTER_CELL_EDIT_ASYNC');export interface IEditorBridgeService {- currentEditCellState$: Observable<Nullable<IEditorBridgeServiceParam>>;+ currentEditCellState$: Observable<Nullable<ICellEditorState>>;+ currentEditCellLayout$: Observable<Nullable<ICellEditorLayout>>;+ currentEditCell$: Observable<Nullable<IEditorBridgeServiceParam>>;+visible$: Observable<IEditorBridgeServiceVisibleParam>;interceptor: InterceptorManager<{BEFORE_CELL_EDIT: typeof BEFORE_CELL_EDIT;@@ -96,6 +106,8 @@ export interface IEditorBridgeService {refreshEditCellPosition(resetSizeOnly?: boolean): void;setEditCell(param: ICurrentEditCellParam): void;getEditCellState(): Readonly<Nullable<IEditorBridgeServiceParam>>;+ getEditCellLayout(): Readonly<Nullable<ICellEditorLayout>>;+ getEditLocation(): Readonly<Nullable<ICellEditorState>>;// Gets the DocumentDataModel of the latest table cell based on the latest cell contentsgetLatestEditCellState(): Readonly<Nullable<IEditorBridgeServiceParam>>;changeVisible(param: IEditorBridgeServiceVisibleParam): void;@@ -106,6 +118,8 @@ export interface IEditorBridgeService {disableForceKeepVisible(): void;isForceKeepVisible(): boolean;getCurrentEditorId(): Nullable<string>;++ beforeSetRangeValue(workbook: Workbook, worksheet: Worksheet, row: number, column: number, cellData: ICellData): Promise<Nullable<ICellData>>;}export class EditorBridgeService extends Disposable implements IEditorBridgeService, IDisposable {@@ -115,6 +129,7 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServprivate _editorIsDirty: boolean = false;+ private _isDisabled: boolean = false;private _visible: IEditorBridgeServiceVisibleParam = {visible: false,eventType: DeviceInputEventType.Dblclick,@@ -122,12 +137,20 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ};private _currentEditCell: Nullable<ICurrentEditCellParam> = null;- private _currentEditCellState: Nullable<IEditorBridgeServiceParam> = null;+ private _currentEditCellState: Nullable<ICellEditorState> = null;+ private _currentEditCellLayout: Nullable<ICellEditorLayout> = null;// TODO: @weird94 this should split into to subjects, documentDataModel & position- private readonly _currentEditCellState$ = new BehaviorSubject<Nullable<IEditorBridgeServiceParam>>(null);+ private readonly _currentEditCellState$ = new BehaviorSubject<Nullable<ICellEditorState>>(null);readonly currentEditCellState$ = this._currentEditCellState$.asObservable();+ private readonly _currentEditCellLayout$ = new BehaviorSubject<Nullable<ICellEditorLayout>>(null);+ readonly currentEditCellLayout$ = this._currentEditCellLayout$.asObservable();++ readonly currentEditCell$ = this._currentEditCellState$.pipe(+ mergeMap((editCellState) => this._currentEditCellLayout$.pipe(map((layout) => (editCellState && layout ? { ...editCellState, ...layout } : null))))+ );+private readonly _visible$ = new BehaviorSubject<IEditorBridgeServiceVisibleParam>(this._visible);readonly visible$ = this._visible$.asObservable();@@ -179,9 +202,18 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServrefreshEditCellState() {const editCellState = this.getLatestEditCellState();- this._currentEditCellState = editCellState;-- this._currentEditCellState$.next(editCellState);+ if (!editCellState) {+ this._currentEditCellState = null;+ this._currentEditCellLayout = null;+ this._currentEditCellState$.next(null);+ this._currentEditCellLayout$.next(null);+ return;+ }+ const { position, scaleX, scaleY, canvasOffset, ...rest } = editCellState;+ this._currentEditCellState = rest;+ this._currentEditCellLayout = { position, scaleX, scaleY, canvasOffset };+ this._currentEditCellState$.next(this._currentEditCellState);+ this._currentEditCellLayout$.next(this._currentEditCellLayout);}refreshEditCellPosition(resetSizeOnly?: boolean) {@@ -199,7 +231,6 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServif (!this._currentEditCellState) return;const { primary, unitId, sheetId, scene, engine } = currentEditCell;- const { startRow, startColumn } = primary;const primaryWithCoord = attachPrimaryWithCoord(primary, skeleton);if (primaryWithCoord == null) {return;@@ -218,38 +249,29 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServendX = skeleton.convertTransformToOffsetX(endX, scaleX, scrollXY);endY = skeleton.convertTransformToOffsetY(endY, scaleY, scrollXY);- if (resetSizeOnly && this._currentEditCellState) {- endX = endX - startX + this._currentEditCellState.position.startX;- endY = endY - startY + this._currentEditCellState.position.startY;- startX = this._currentEditCellState.position.startX;- startY = this._currentEditCellState.position.startY;+ if (resetSizeOnly && this._currentEditCellLayout) {+ endX = endX - startX + this._currentEditCellLayout.position.startX;+ endY = endY - startY + this._currentEditCellLayout.position.startY;+ startX = this._currentEditCellLayout.position.startX;+ startY = this._currentEditCellLayout.position.startY;}this._editorService.setOperationSheetUnitId(unitId);this._editorService.setOperationSheetSubUnitId(sheetId);- const editCellState = {+ this._currentEditCellLayout = {position: {startX,startY,endX,endY,},+ canvasOffset,scaleX,scaleY,- canvasOffset,- row: startRow,- column: startColumn,- unitId,- sheetId,- documentLayoutObject: this._currentEditCellState.documentLayoutObject,- editorUnitId: this._editorUnitId,- isInArrayFormulaRange: this._currentEditCellState?.isInArrayFormulaRange,};-- this._currentEditCellState = editCellState;- this._currentEditCellState$.next(editCellState);+ this._currentEditCellLayout$.next(this._currentEditCellLayout);}setEditCell(param: ICurrentEditCellParam) {@@ -278,9 +300,23 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServprivate _clearCurrentEditCellState() {this._currentEditCellState = null;this._currentEditCellState$.next(null);+ this._currentEditCellLayout = null;+ this._currentEditCellLayout$.next(null);}getEditCellState(): Readonly<Nullable<IEditorBridgeServiceParam>> {+ if (this._currentEditCellState == null || this._currentEditCellLayout == null) {+ return null;+ }++ return { ...this._currentEditCellState, ...this._currentEditCellLayout };+ }++ getEditCellLayout(): Readonly<Nullable<ICellEditorLayout>> {+ return this._currentEditCellLayout;+ }++ getEditLocation(): Readonly<Nullable<ICellEditorState>> {return this._currentEditCellState;}@@ -332,14 +368,15 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServorigin: worksheet.getCellRaw(startRow, startColumn),};+ let documentLayoutObject: Nullable<IDocumentLayoutObject>;const cell = this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().BEFORE_CELL_EDIT)(worksheet.getCell(startRow, startColumn),location);- let documentLayoutObject = cell && skeleton.getCellDocumentModelWithFormula(cell);+ documentLayoutObject = cell && skeleton.getCellDocumentModelWithFormula(cell);- // Rewrite the cellValueType to STRING to avoid render the value on the right side when number type.+ // Rewrite the cellValueType to STRING to avoid render the value on the right side when number type.const renderConfig = documentLayoutObject?.documentModel?.documentStyle.renderConfig;if (renderConfig != null) {renderConfig.cellValueType = CellValueType.STRING;@@ -357,7 +394,7 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ}documentLayoutObject = blankModel;}- // background of canvas is set to transparent, so if no bgcolor sepcified in curr cell, set it to white.+ // background of canvas is set to transparent, so if no bgcolor sepcified in curr cell, set it to white.documentLayoutObject.fill = documentLayoutObject.fill || '#fff';documentLayoutObject.documentModel?.setZoomRatio(Math.max(scaleX, scaleY));@@ -450,6 +487,28 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServgetEditorDirty() {return this._editorIsDirty;}++ async beforeSetRangeValue(workbook: Workbook, worksheet: Worksheet, row: number, column: number, cellData: ICellData) {+ const context = {+ subUnitId: worksheet.getSheetId(),+ unitId: workbook.getUnitId(),+ workbook: workbook!,+ worksheet,+ row,+ col: column,+ origin: Tools.deepClone(cellData),+ };+ const cell = this.interceptor.fetchThroughInterceptors(+ this.interceptor.getInterceptPoints().AFTER_CELL_EDIT+ )(cellData, context);++ const finalCell = await this.interceptor.fetchThroughInterceptors(+ this.interceptor.getInterceptPoints().AFTER_CELL_EDIT_ASYNC+ )(Promise.resolve(cell), context);++ // remove temp value+ return finalCell;+ }}export const IEditorBridgeService = createIdentifier<EditorBridgeService>('univer.sheet-editor-bridge.service');diff --git a/packages/sheets-ui/src/services/editor/cell-editor-manager.service.ts b/packages/sheets-ui/src/services/editor/cell-editor-manager.service.tsindex b500c9bc51..dcb1c86d7e 100644--- a/packages/sheets-ui/src/services/editor/cell-editor-manager.service.ts+++ b/packages/sheets-ui/src/services/editor/cell-editor-manager.service.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import { createIdentifier } from '@univerjs/core';-import { BehaviorSubject } from 'rxjs';import type { IDisposable, IPosition, Nullable } from '@univerjs/core';import type { Observable } from 'rxjs';+import { createIdentifier } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';export interface ICellEditorManagerParam extends Partial<IPosition> {show: boolean;diff --git a/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.tsnew file mode 100644index 0000000000..d41ce2db62--- /dev/null+++ b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts@@ -0,0 +1,389 @@+/**+ * 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 { IPosition, Nullable, Workbook } from '@univerjs/core';+import type { DocumentSkeleton, IDocumentLayoutObject, IRenderContext, IRenderModule, Scene } from '@univerjs/engine-render';+import { Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, HorizontalAlign, Inject, VerticalAlign, WrapStrategy } from '@univerjs/core';+import { DocSkeletonManagerService } from '@univerjs/docs';+import { VIEWPORT_KEY as DOC_VIEWPORT_KEY, DOCS_COMPONENT_MAIN_LAYER_INDEX } from '@univerjs/docs-ui';+import { convertTextRotation, FIX_ONE_PIXEL_BLUR_OFFSET, fixLineWidthByScale, IRenderManagerService, Rect, ScrollBar } from '@univerjs/engine-render';+import { ILayoutService } from '@univerjs/ui';+import { getEditorObject } from '../../basics/editor/get-editor-object';+import styles from '../../views/sheet-container/index.module.less';+import { IEditorBridgeService } from '../editor-bridge.service';+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';+import { ICellEditorManagerService } from './cell-editor-manager.service';++const EDITOR_INPUT_SELF_EXTEND_GAP = 5;++const EDITOR_BORDER_SIZE = 2;++interface ICanvasOffset {+ left: number;+ top: number;+}++export class SheetCellEditorResizeService extends Disposable implements IRenderModule {+ constructor(+ private readonly _context: IRenderContext<Workbook>,+ @ILayoutService private readonly _layoutService: ILayoutService,+ @ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService+ ) {+ super();+ }++ fitTextSize(callback?: () => void) {+ const param = this._editorBridgeService.getEditCellState();+ if (!param) return;+ const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;++ const { startX, startY, endX, endY } = position;+ const documentDataModel = documentLayoutObject.documentModel;++ if (documentDataModel == null) {+ return;+ }++ const documentSkeleton = this._getEditorSkeleton();+ if (!documentSkeleton) return;++ const { actualWidth, actualHeight } = this._predictingSize(+ position,+ canvasOffset,+ documentSkeleton,+ documentLayoutObject,+ scaleX,+ scaleY+ );+ const { verticalAlign, paddingData, fill } = documentLayoutObject;++ let editorWidth = endX - startX;+ let editorHeight = endY - startY;++ if (editorWidth < actualWidth) {+ editorWidth = actualWidth;+ }++ if (editorHeight < actualHeight) {+ editorHeight = actualHeight;+ // To restore the page margins for the skeleton.+ documentDataModel.updateDocumentDataMargin(paddingData);+ } else {+ // Set the top margin under vertical alignment.+ let offsetTop = 0;++ if (verticalAlign === VerticalAlign.MIDDLE) {+ offsetTop = (editorHeight - actualHeight) / 2 / scaleY;+ } else if (verticalAlign === VerticalAlign.TOP) {+ offsetTop = paddingData.t || 0;+ } else { // VerticalAlign.UNSPECIFIED follow the same rule as HorizontalAlign.BOTTOM.+ offsetTop = (editorHeight - actualHeight) / scaleY - (paddingData.b || 0);+ }++ // offsetTop /= scaleY;+ offsetTop = offsetTop < (paddingData.t || 0) ? paddingData.t || 0 : offsetTop;++ documentDataModel.updateDocumentDataMargin({+ t: offsetTop,+ });+ }++ // re-calculate skeleton(viewModel for component)+ documentSkeleton.calculate();++ this._editAreaProcessing(editorWidth, editorHeight, position, canvasOffset, fill, scaleX, scaleY, callback);+ }++ /**+ * Mainly used to pre-calculate the width of the editor,+ * to determine whether it needs to be automatically widened.+ */+ private _predictingSize(+ actualRangeWithCoord: IPosition,+ canvasOffset: ICanvasOffset,+ documentSkeleton: DocumentSkeleton,+ documentLayoutObject: IDocumentLayoutObject,+ scaleX: number = 1,+ scaleY: number = 1+ ) {+ // startX and startY are the width and height after scaling.+ const { startX, endX } = actualRangeWithCoord;++ const { textRotation, wrapStrategy } = documentLayoutObject;++ const documentDataModel = documentLayoutObject.documentModel;++ const { vertexAngle: angle } = convertTextRotation(textRotation);++ const clientWidth = document.body.clientWidth;++ if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {+ const { actualWidth, actualHeight } = documentSkeleton.getActualSize();+ // The skeleton obtains the original volume, which needs to be multiplied by the magnification factor.+ return {+ actualWidth: actualWidth * scaleX,+ actualHeight: actualHeight * scaleY,+ };+ }++ documentDataModel?.updateDocumentDataPageSize((clientWidth - startX - canvasOffset.left) / scaleX);+ documentSkeleton.calculate();++ const size = documentSkeleton.getActualSize();++ let editorWidth = endX - startX;++ if (editorWidth < size.actualWidth * scaleX + EDITOR_INPUT_SELF_EXTEND_GAP * scaleX) {+ editorWidth = size.actualWidth * scaleX + EDITOR_INPUT_SELF_EXTEND_GAP * scaleX;+ }++ // Scaling is handled by the renderer, so the skeleton only accepts the original width and height, which need to be divided by the magnification factor.+ documentDataModel?.updateDocumentDataPageSize(editorWidth / scaleX);++ /**+ * Do not rely on cell layout logic, depend on the document's internal alignment logic.+ */+ documentDataModel?.updateDocumentRenderConfig({+ horizontalAlign: HorizontalAlign.UNSPECIFIED,+ cellValueType: undefined,+ });++ return {+ actualWidth: editorWidth,+ actualHeight: size.actualHeight * scaleY,+ };+ }++ private _getEditorMaxSize(position: IPosition, canvasOffset: ICanvasOffset) {+ const editorObject = this._getEditorObject();+ if (editorObject == null) {+ return;+ }+ function pxToNum(width: string): number {+ return Number.parseInt(width.replace('px', ''));+ }++ const engine = this._context.engine;+ const canvasElement = engine.getCanvasElement();+ const canvasClientRect = canvasElement.getBoundingClientRect();++ // We should take the scale into account when canvas is scaled by CSS.+ const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width+ const { width } = canvasClientRect; // real width affected by scale+ const scaleAdjust = width / widthOfCanvas;++ const { startX, startY } = position;++ const clientHeight =+ document.body.clientHeight -+ startY -+ Number.parseFloat(styles.sheetFooterBarHeight) -+ canvasOffset.top -+ EDITOR_BORDER_SIZE * 2;++ const clientWidth = document.body.clientWidth - startX - canvasOffset.left;++ return {+ height: clientHeight,+ width: clientWidth,+ scaleAdjust,+ };+ }++ /**+ * Mainly used to calculate the volume of scenes and objects,+ * determine whether a scrollbar appears,+ * and calculate the editor's boundaries relative to the browser.+ */+ // eslint-disable-next-line max-lines-per-function+ private _editAreaProcessing(+ editorWidth: number,+ editorHeight: number,+ actualRangeWithCoord: IPosition,+ canvasOffset: ICanvasOffset,+ fill: Nullable<string>,+ scaleX: number = 1,+ scaleY: number = 1,+ callback?: () => void+ ) {+ const editorObject = this._getEditorObject();+ if (editorObject == null) {+ return;+ }++ const engine = this._context.engine;+ const canvasElement = engine.getCanvasElement();++ // We should take the scale into account when canvas is scaled by CSS.++ let { startX, startY } = actualRangeWithCoord;++ const { document: documentComponent, scene: editorScene, engine: docEngine } = editorObject;+ const viewportMain = editorScene.getViewport(DOC_VIEWPORT_KEY.VIEW_MAIN);++ const info = this._getEditorMaxSize(actualRangeWithCoord, canvasOffset);+ if (!info) return;+ const { height: clientHeight, width: clientWidth, scaleAdjust } = info;++ let physicHeight = editorHeight;++ let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;++ if (physicHeight > clientHeight) {+ physicHeight = clientHeight;++ if (scrollBar == null) {+ viewportMain && new ScrollBar(viewportMain, { enableHorizontal: false, barSize: 8 });+ } else {+ viewportMain?.resetCanvasSizeAndUpdateScroll();+ }+ } else {+ scrollBar = null;+ viewportMain?.getScrollBar()?.dispose();+ }++ editorWidth += scrollBar?.barSize || 0;++ if (editorWidth > clientWidth) {+ editorWidth = clientWidth;+ }++ startX -= FIX_ONE_PIXEL_BLUR_OFFSET;+ startY -= FIX_ONE_PIXEL_BLUR_OFFSET;++ this._addBackground(editorScene, editorWidth / scaleX, editorHeight / scaleY, fill);++ const { scaleX: precisionScaleX, scaleY: precisionScaleY } = editorScene.getPrecisionScale();++ editorScene.transformByState({+ width: editorWidth * scaleAdjust / scaleX,+ height: editorHeight * scaleAdjust / scaleY,+ scaleX: scaleX * scaleAdjust,+ scaleY: scaleY * scaleAdjust,+ });++ documentComponent.resize(editorWidth * scaleAdjust / scaleX, editorHeight * scaleAdjust / scaleY);++ /**+ * sometimes requestIdleCallback is invalid, so use setTimeout to ensure the successful execution of the resizeBySize method.+ * resize canvas+ * When modifying the selection area for a formula, it is necessary to add a setTimeout to ensure successful updating.+ */+ setTimeout(() => {+ docEngine.resizeBySize(+ fixLineWidthByScale(editorWidth, precisionScaleX),+ fixLineWidthByScale(physicHeight, precisionScaleY)+ );++ callback?.();+ }, 0);++ const contentBoundingRect = this._layoutService.getContentElement().getBoundingClientRect();+ const canvasBoundingRect = canvasElement.getBoundingClientRect();+ startX = startX * scaleAdjust + (canvasBoundingRect.left - contentBoundingRect.left);+ startY = startY * scaleAdjust + (canvasBoundingRect.top - contentBoundingRect.top);++ // Update cell editor container position and size.+ this._cellEditorManagerService.setState({+ startX,+ startY,+ endX: editorWidth * scaleAdjust + startX,+ endY: physicHeight * scaleAdjust + startY,+ show: true,+ });+ }++ /**+ * Since the document does not support cell background color, an additional rect needs to be added.+ */+ private _addBackground(scene: Scene, editorWidth: number, editorHeight: number, fill?: Nullable<string>) {+ const fillRectKey = '_backgroundRectHelperColor_';+ const rect = scene.getObject(fillRectKey) as Rect;++ if (rect == null && fill == null) {+ return;+ }++ if (rect == null) {+ scene.addObjects(+ [+ new Rect(fillRectKey, {+ width: editorWidth,+ height: editorHeight,+ fill,+ evented: false,+ }),+ ],+ DOCS_COMPONENT_MAIN_LAYER_INDEX+ );+ } else if (fill == null) {+ rect.dispose();+ } else {+ rect.setProps({+ fill,+ });++ rect.transformByState({+ width: editorWidth,+ height: editorHeight,+ });+ }+ }++ resizeCellEditor(callback?: () => void) {+ const state = this._cellEditorManagerService.getState();++ if (!state) return;+ if (!this._editorBridgeService.isVisible().visible) return;+ this._editorBridgeService.refreshEditCellPosition(true);+ const editCellState = this._editorBridgeService.getEditCellState();+ if (!editCellState) return;++ const skeleton = this._sheetSkeletonManagerService.getWorksheetSkeleton(editCellState.sheetId)?.skeleton;+ if (!skeleton) return;+ const { row, column, scaleX, scaleY, position, canvasOffset } = editCellState;+ const maxSize = this._getEditorMaxSize(position, canvasOffset);+ if (!maxSize) return;+ const { height: clientHeight, width: clientWidth, scaleAdjust } = maxSize;++ const cell = skeleton.getCellByIndex(row, column);+ const height = Math.min((cell.mergeInfo.endY - cell.mergeInfo.startY) * scaleY, clientHeight) * scaleAdjust;+ const width = Math.min((cell.mergeInfo.endX - cell.mergeInfo.startX) * scaleX, clientWidth) * scaleAdjust;+ const currentHeight = state.endY! - state.startY!;+ const currentWidth = state.endX! - state.startX!;++ if (currentHeight !== height || currentWidth !== width) {+ this._editorBridgeService.refreshEditCellPosition(true);++ const docSkeleton = this._getEditorSkeleton();+ if (!docSkeleton) {+ return;+ }+ this.fitTextSize(callback);+ }+ }++ private _getEditorObject() {+ return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);+ }++ private _getEditorSkeleton() {+ return this._renderManagerService.getRenderById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.with(DocSkeletonManagerService).getSkeleton();+ }+}diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.tsindex 29ddfd042f..8958ce5e99 100644--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts@@ -14,21 +14,21 @@* limitations under the License.*/+import type { IDisposable, Nullable, Workbook } from '@univerjs/core';+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';+import type { ISelectionWithCoordAndStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';+import type { ISheetObjectParam } from '../../controllers/utils/component-tools';import { ICommandService, IContextService, ILogService, Inject, Injector, RANGE_TYPE, ThemeService, toDisposable } from '@univerjs/core';import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';import { convertSelectionDataToRange, DISABLE_NORMAL_SELECTIONS, SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';import { IShortcutService } from '@univerjs/ui';import { distinctUntilChanged, merge, startWith } from 'rxjs';-import type { IDisposable, Nullable, Workbook } from '@univerjs/core';-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';-import type { ISelectionWithCoordAndStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';import { isThisColSelected, isThisRowSelected } from '../../controllers/utils/selections-tools';import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';-import { attachSelectionWithCoord } from './util';-import type { ISheetObjectParam } from '../../controllers/utils/component-tools';+import { attachSelectionWithCoord } from './util';/*** This services controls rendering of normal selections in a render unit.diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.tsindex 03dacaf02d..9ce9feb176 100644--- a/packages/sheets-ui/src/sheets-ui-plugin.ts+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts@@ -32,6 +32,7 @@ import { SheetClipboardController } from './controllers/clipboard/clipboard.contimport { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.schema';import { SheetsDefinedNameController } from './controllers/defined-name/defined-name.controller';import { DragRenderController } from './controllers/drag-render.controller';+import { EditorDataSyncController } from './controllers/editor/data-sync.controller';import { EditingRenderController } from './controllers/editor/editing.render-controller';import { FormulaEditorController } from './controllers/editor/formula-editor.controller';import { ForceStringAlertRenderController } from './controllers/force-string-alert-render.controller';@@ -65,6 +66,7 @@ import { CellAlertManagerService } from './services/cell-alert-manager.service';import { ISheetClipboardService, SheetClipboardService } from './services/clipboard/clipboard.service';import { DragManagerService } from './services/drag-manager.service';import { CellEditorManagerService, ICellEditorManagerService } from './services/editor/cell-editor-manager.service';+import { SheetCellEditorResizeService } from './services/editor/cell-editor-resize.service';import {FormulaEditorManagerService,IFormulaEditorManagerService,@@ -141,6 +143,7 @@ export class UniverSheetsUIPlugin extends Plugin {[AutoFillController],[FormatPainterController],[SheetsDefinedNameController],+ [EditorDataSyncController],[SheetCheckboxController],// permission@@ -183,6 +186,7 @@ export class UniverSheetsUIPlugin extends Plugin {[SheetsDefinedNameController],[StatusBarController],[AutoHeightController],+ [EditorDataSyncController],[SheetCheckboxController],]);}@@ -217,6 +221,7 @@ export class UniverSheetsUIPlugin extends Plugin {[SheetsScrollRenderController],[HeaderFreezeRenderController],[SheetsZoomRenderController],+ [SheetCellEditorResizeService],[FormatPainterRenderController],[CellAlertRenderController],