Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat: basic use of fx editor (#581)

Ran Luo7c63d26ec06f
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 9263f86013..c15e63e89b 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -12,6 +12,7 @@
"Bandings",
"Catmull",
"clazz",
+ "clsx",
"codelf",
"commitlint",
"compositionend",
diff --git a/packages/base-docs/src/basics/component-tools.ts b/packages/base-docs/src/basics/component-tools.ts
index 1ba68a8561..4777367288 100644
--- a/packages/base-docs/src/basics/component-tools.ts
+++ b/packages/base-docs/src/basics/component-tools.ts
@@ -1,5 +1,5 @@
-import { Documents, Engine, IRenderManagerService, Scene } from '@univerjs/base-render';
-import { IUniverInstanceService, Nullable } from '@univerjs/core';
+import type { Documents, Engine, IRenderManagerService, Scene } from '@univerjs/base-render';
+import type { IUniverInstanceService, Nullable } from '@univerjs/core';
export interface IDocObjectParam {
document: Documents;
diff --git a/packages/base-docs/src/commands/commands/__tests__/replace-content.command.spec.ts b/packages/base-docs/src/commands/commands/__tests__/replace-content.command.spec.ts
index 70969e7ac8..605285e835 100644
--- a/packages/base-docs/src/commands/commands/__tests__/replace-content.command.spec.ts
+++ b/packages/base-docs/src/commands/commands/__tests__/replace-content.command.spec.ts
@@ -15,7 +15,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../../../basics/docs-view-key';
import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
-import { ReplaceContentCommand } from '../replace-content.command';
+import { CoverContentCommand, ReplaceContentCommand } from '../replace-content.command';
import { createCommandTestBed } from './create-command-test-bed';
const TEST_DOCUMENT_DATA_EN: IDocumentData = {
@@ -35,7 +35,7 @@ const TEST_DOCUMENT_DATA_EN: IDocumentData = {
},
};
-describe('replace content of document', () => {
+describe('replace or cover content of document', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
@@ -58,6 +58,7 @@ describe('replace content of document', () => {
commandService = get(ICommandService);
commandService.registerCommand(ReplaceContentCommand);
+ commandService.registerCommand(CoverContentCommand);
commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
const selectionManager = get(TextSelectionManagerService);
@@ -102,6 +103,35 @@ describe('replace content of document', () => {
await commandService.executeCommand(RedoCommand.id);
expect(getDataStream().length).toBe(17);
+
+ // recovery the doc.
+ await commandService.executeCommand(UndoCommand.id);
+ });
+ });
+
+ describe('cover content of document and clear undo and redo stack', () => {
+ it('Should pass the test case when cover content', async () => {
+ expect(getDataStream().length).toBe(13);
+ const commandParams = {
+ unitId: 'test-doc',
+ body: {
+ dataStream: '=AVERAGE(A4:B8)',
+ }, // Do not contain `\r\n` at the end.
+ textRanges: [],
+ segmentId: '',
+ };
+
+ await commandService.executeCommand(CoverContentCommand.id, commandParams);
+
+ expect(getDataStream().length).toBe(17);
+
+ await commandService.executeCommand(UndoCommand.id);
+
+ expect(getDataStream().length).toBe(17);
+
+ await commandService.executeCommand(RedoCommand.id);
+
+ expect(getDataStream().length).toBe(17);
});
});
});
diff --git a/packages/base-docs/src/commands/commands/core-editing.command.ts b/packages/base-docs/src/commands/commands/core-editing.command.ts
index 55d2163876..ab2f07428c 100644
--- a/packages/base-docs/src/commands/commands/core-editing.command.ts
+++ b/packages/base-docs/src/commands/commands/core-editing.command.ts
@@ -1,19 +1,18 @@
-import { ITextRangeWithStyle } from '@univerjs/base-render';
-import {
- CommandType,
+import type { ITextRangeWithStyle } from '@univerjs/base-render';
+import type {
ICommand,
- ICommandService,
IDocumentBody,
IDocumentData,
IMutationInfo,
ITextRange,
- IUndoRedoService,
UpdateDocsAttributeType,
} from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';
import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
-import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
+import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
// TODO: @JOCS, do not use command as event bus.
export const DeleteLeftCommand: ICommand = {
diff --git a/packages/base-docs/src/commands/commands/inline-format.command.ts b/packages/base-docs/src/commands/commands/inline-format.command.ts
index ade6742cd5..4c7467768e 100644
--- a/packages/base-docs/src/commands/commands/inline-format.command.ts
+++ b/packages/base-docs/src/commands/commands/inline-format.command.ts
@@ -1,21 +1,19 @@
-import { TextRange } from '@univerjs/base-render';
+import type { TextRange } from '@univerjs/base-render';
+import type { ICommand, IDocumentBody, IMutationInfo, IStyleBase, ITextDecoration, ITextRun } from '@univerjs/core';
import {
BooleanNumber,
CommandType,
- ICommand,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ICommandService,
- IDocumentBody,
- IMutationInfo,
- IStyleBase,
- ITextDecoration,
- ITextRun,
IUndoRedoService,
IUniverInstanceService,
MemoryCursor,
} from '@univerjs/core';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
-import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
+import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
export interface ISetInlineFormatCommandParams {
segmentId: string;
@@ -81,8 +79,15 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
return false;
}
- const docsModel = currentUniverService.getCurrentUniverDocInstance();
- const unitId = docsModel.getUnitId();
+ let docsModel = currentUniverService.getCurrentUniverDocInstance();
+ let unitId = docsModel.getUnitId();
+
+ // When setting the formula bar style, the effect will be displayed in the cell editor,
+ // and the formula bar only displays plain text.
+ if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ docsModel = currentUniverService.getUniverDocInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!;
+ unitId = docsModel.getUnitId();
+ }
let formatValue;
diff --git a/packages/base-docs/src/commands/commands/replace-content.command.ts b/packages/base-docs/src/commands/commands/replace-content.command.ts
index 3cf5bfb4e6..20fbd59eb3 100644
--- a/packages/base-docs/src/commands/commands/replace-content.command.ts
+++ b/packages/base-docs/src/commands/commands/replace-content.command.ts
@@ -1,16 +1,10 @@
-import { ITextRangeWithStyle } from '@univerjs/base-render';
-import {
- CommandType,
- ICommand,
- ICommandService,
- IDocumentBody,
- IMutationInfo,
- IUndoRedoService,
- IUniverInstanceService,
-} from '@univerjs/core';
+import type { ITextRangeWithStyle } from '@univerjs/base-render';
+import type { ICommand, IDocumentBody, IMutationInfo } from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
-import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
+import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
interface IReplaceContentCommandParams {
unitId: string;
@@ -32,7 +26,7 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const undoRedoService = accessor.get(IUndoRedoService);
- const prevBody = univerInstanceService.getCurrentUniverDocInstance().getSnapshot().body;
+ const prevBody = univerInstanceService.getUniverDocInstance(unitId)?.getSnapshot().body;
const selections = textSelectionManagerService.getSelections();
if (prevBody == null) {
@@ -43,28 +37,7 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {
return false;
}
- const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
- id: RichTextEditingMutation.id,
- params: {
- unitId,
- mutations: [],
- },
- };
-
- doMutation.params.mutations.push({
- t: 'd',
- len: prevBody?.dataStream.length - 2,
- line: 0,
- segmentId,
- });
-
- doMutation.params.mutations.push({
- t: 'i',
- body,
- len: body.dataStream.length,
- line: 0,
- segmentId,
- });
+ const doMutation = getMutationParams(unitId, segmentId, prevBody, body);
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
@@ -100,3 +73,72 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {
return false;
},
};
+
+interface ICoverContentCommandParams {
+ unitId: string;
+ body: IDocumentBody; // Do not contain `\r\n` at the end.
+ segmentId?: string;
+}
+
+// Cover all content with new body, and clear undo/redo stack.
+export const CoverContentCommand: ICommand<ICoverContentCommandParams> = {
+ id: 'doc.command-cover-content',
+
+ type: CommandType.COMMAND,
+
+ handler: async (accessor, params: ICoverContentCommandParams) => {
+ const { unitId, body, segmentId = '' } = params;
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const prevBody = univerInstanceService.getUniverDocInstance(unitId)?.getSnapshot().body;
+
+ if (prevBody == null) {
+ return false;
+ }
+
+ const doMutation = getMutationParams(unitId, segmentId, prevBody, body);
+
+ commandService.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(
+ doMutation.id,
+ doMutation.params
+ );
+
+ undoRedoService.clearUndoRedo(unitId);
+
+ return true;
+ },
+};
+
+function getMutationParams(unitId: string, segmentId: string, prevBody: IDocumentBody, body: IDocumentBody) {
+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId,
+ mutations: [],
+ },
+ };
+
+ const deleteLen = prevBody?.dataStream.length - 2;
+ if (deleteLen > 0) {
+ doMutation.params.mutations.push({
+ t: 'd',
+ len: deleteLen,
+ line: 0,
+ segmentId,
+ });
+ }
+
+ if (body.dataStream.length > 0) {
+ doMutation.params.mutations.push({
+ t: 'i',
+ body,
+ len: body.dataStream.length,
+ line: 0,
+ segmentId,
+ });
+ }
+
+ return doMutation;
+}
diff --git a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
index 50942c5e62..729ffbd800 100644
--- a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
@@ -1,4 +1,10 @@
-import { CommandType, type DocMutationParams, IMutation, IUniverInstanceService, MemoryCursor } from '@univerjs/core';
+import {
+ CommandType,
+ type DocMutationParams,
+ type IMutation,
+ IUniverInstanceService,
+ MemoryCursor,
+} from '@univerjs/core';
import { DocViewModelManagerService } from '../../services/doc-view-model-manager.service';
diff --git a/packages/base-docs/src/commands/operations/text-selection.operation.ts b/packages/base-docs/src/commands/operations/text-selection.operation.ts
index d58d05181e..e193b5e8b8 100644
--- a/packages/base-docs/src/commands/operations/text-selection.operation.ts
+++ b/packages/base-docs/src/commands/operations/text-selection.operation.ts
@@ -1,7 +1,8 @@
// This file provide operations to change selection of sheets.
-import { TextRange } from '@univerjs/base-render';
-import { CommandType, IOperation } from '@univerjs/core';
+import type { TextRange } from '@univerjs/base-render';
+import type { IOperation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
diff --git a/packages/base-docs/src/controllers/doc-render.controller.ts b/packages/base-docs/src/controllers/doc-render.controller.ts
index 7e431f2770..41f0382d2d 100644
--- a/packages/base-docs/src/controllers/doc-render.controller.ts
+++ b/packages/base-docs/src/controllers/doc-render.controller.ts
@@ -1,16 +1,18 @@
-import { Documents, DocumentSkeleton, IRender, IRenderManagerService, PageLayoutType } from '@univerjs/base-render';
+import type { Documents, DocumentSkeleton, IRender } from '@univerjs/base-render';
+import { IRenderManagerService, PageLayoutType } from '@univerjs/base-render';
+import type { ICommandInfo } from '@univerjs/core';
import {
Disposable,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- ICommandInfo,
ICommandService,
LifecycleStages,
OnLifecycle,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
+import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
+import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
@OnLifecycle(LifecycleStages.Rendered, DocRenderController)
@@ -102,13 +104,12 @@ export class DocRenderController extends Disposable {
const docsComponent = mainComponent as Documents;
- const data = skeleton.getSkeletonData();
+ const pages = skeleton.getSkeletonData()?.pages;
- if (data == null) {
+ if (pages == null) {
return;
}
- const pages = data.pages;
let width = 0;
let height = 0;
@@ -120,6 +121,7 @@ export class DocRenderController extends Disposable {
if (i !== len - 1) {
height += docsComponent.pageMarginTop;
}
+
width = Math.max(width, pageWidth);
} else if (docsComponent.pageLayoutType === PageLayoutType.HORIZONTAL) {
width += pageWidth;
@@ -142,19 +144,15 @@ export class DocRenderController extends Disposable {
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (updateCommandList.includes(command.id)) {
const params = command.params as IRichTextEditingMutationParams;
- const { unitId: commandUnitId } = params;
+ const { unitId } = params;
- const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+ const docsSkeletonObject = this._docSkeletonManagerService.getSkeletonByUnitId(unitId);
if (docsSkeletonObject == null) {
return;
}
- const { unitId, skeleton } = docsSkeletonObject;
-
- if (commandUnitId !== unitId) {
- return;
- }
+ const { skeleton } = docsSkeletonObject;
const currentRender = this._renderManagerService.getRenderById(unitId);
diff --git a/packages/base-docs/src/controllers/line-break-input.controller.ts b/packages/base-docs/src/controllers/line-break-input.controller.ts
index d8cf25e210..b2a21528a4 100644
--- a/packages/base-docs/src/controllers/line-break-input.controller.ts
+++ b/packages/base-docs/src/controllers/line-break-input.controller.ts
@@ -1,17 +1,15 @@
import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import type { ICommandInfo, IParagraph, Nullable } from '@univerjs/core';
import {
DataStreamTreeTokenType,
Disposable,
- ICommandInfo,
ICommandService,
- IParagraph,
IUniverInstanceService,
LifecycleStages,
- Nullable,
OnLifecycle,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { Subscription } from 'rxjs';
+import type { Subscription } from 'rxjs';
import { getDocObject } from '../basics/component-tools';
import { BreakLineCommand, InsertCommand } from '../commands/commands/core-editing.command';
@@ -70,12 +68,12 @@ export class LineBreakInputController extends Disposable {
return;
}
- this._breakLineFunction();
+ this._handleBreakLine();
})
);
}
- private _breakLineFunction() {
+ private _handleBreakLine() {
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
const activeRange = this._textSelectionRenderManager.getActiveRange();
@@ -84,8 +82,8 @@ export class LineBreakInputController extends Disposable {
return;
}
- const docsModel = this._currentUniverService.getCurrentUniverDocInstance();
- const unitId = docsModel.getUnitId();
+ const docDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const unitId = docDataModel.getUnitId();
const { startOffset, segmentId, style } = activeRange;
// move selection
diff --git a/packages/base-docs/src/controllers/page-render.controller.ts b/packages/base-docs/src/controllers/page-render.controller.ts
index a5291dfde3..f51d3ca22c 100644
--- a/packages/base-docs/src/controllers/page-render.controller.ts
+++ b/packages/base-docs/src/controllers/page-render.controller.ts
@@ -6,9 +6,6 @@ import {
LifecycleStages,
OnLifecycle,
} from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
-
-import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
const PAGE_STROKE_COLOR = 'rgba(198,198,198, 1)';
@@ -16,10 +13,7 @@ const PAGE_FILL_COLOR = 'rgba(255,255,255, 1)';
@OnLifecycle(LifecycleStages.Rendered, PageRenderController)
export class PageRenderController extends Disposable {
- constructor(
- @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
- ) {
+ constructor(@IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {
super();
this._initialize();
@@ -32,13 +26,11 @@ export class PageRenderController extends Disposable {
}
private _initialRenderRefresh() {
- this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
- if (param == null) {
+ this._renderManagerService.currentRender$.subscribe((unitId) => {
+ if (unitId == null) {
return;
}
- const { unitId } = param;
-
const currentRender = this._renderManagerService.getRenderById(unitId);
if (currentRender == null) {
diff --git a/packages/base-docs/src/controllers/text-selection.controller.ts b/packages/base-docs/src/controllers/text-selection.controller.ts
index f0959f860f..ca565376f1 100644
--- a/packages/base-docs/src/controllers/text-selection.controller.ts
+++ b/packages/base-docs/src/controllers/text-selection.controller.ts
@@ -1,28 +1,13 @@
-import {
- CURSOR_TYPE,
- IMouseEvent,
- IPointerEvent,
- IRenderManagerService,
- ITextSelectionRenderManager,
-} from '@univerjs/base-render';
-import {
- Disposable,
- ICommandInfo,
- ICommandService,
- IUniverInstanceService,
- LifecycleStages,
- Nullable,
- Observer,
- OnLifecycle,
-} from '@univerjs/core';
+import type { Documents, IMouseEvent, IPointerEvent } from '@univerjs/base-render';
+import { CURSOR_TYPE, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import type { ICommandInfo, Nullable, Observer } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { getDocObjectById } from '../basics/component-tools';
import { NORMAL_TEXT_SELECTION_PLUGIN_NAME, VIEWPORT_KEY } from '../basics/docs-view-key';
-import {
- ISetDocZoomRatioOperationParams,
- SetDocZoomRatioOperation,
-} from '../commands/operations/set-doc-zoom-ratio.operation';
+import type { ISetDocZoomRatioOperationParams } from '../commands/operations/set-doc-zoom-ratio.operation';
+import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';
import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@@ -119,6 +104,8 @@ export class TextSelectionController extends Disposable {
});
this._downObserver = document?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+ this._currentUniverService.setCurrentUniverDocInstance(unitId);
+
this._textSelectionRenderManager.eventTrigger(evt, document.getOffsetConfig(), viewportMain);
if (evt.button !== 2) {
@@ -207,6 +194,7 @@ export class TextSelectionController extends Disposable {
}
private _skeletonListener() {
+ // Change text selection runtime(skeleton, scene) and update text selection manager current selection.
this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
if (param == null) {
return;
@@ -219,9 +207,15 @@ export class TextSelectionController extends Disposable {
return;
}
- const { scene } = currentRender;
+ const { scene, mainComponent } = currentRender;
+ const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
- this._textSelectionRenderManager.changeRuntime(skeleton, scene);
+ this._textSelectionRenderManager.changeRuntime(
+ skeleton,
+ scene,
+ viewportMain,
+ (mainComponent as Documents).getOffsetConfig()
+ );
this._textSelectionManagerService.setCurrentSelectionNotRefresh({
pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
diff --git a/packages/base-docs/src/doc-plugin.ts b/packages/base-docs/src/doc-plugin.ts
index 80301c9348..f0c05be9e1 100644
--- a/packages/base-docs/src/doc-plugin.ts
+++ b/packages/base-docs/src/doc-plugin.ts
@@ -1,7 +1,7 @@
import { ITextSelectionRenderManager, TextSelectionRenderManager } from '@univerjs/base-render';
import { IShortcutService } from '@univerjs/base-ui';
+import type { ICommand } from '@univerjs/core';
import {
- ICommand,
ICommandService,
IConfigService,
IUniverInstanceService,
@@ -10,7 +10,8 @@ import {
PLUGIN_NAMES,
PluginType,
} from '@univerjs/core';
-import { Dependency, Inject, Injector } from '@wendellhu/redi';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
import {
BreakLineCommand,
@@ -31,7 +32,7 @@ import {
SetInlineFormatTextColorCommand,
SetInlineFormatUnderlineCommand,
} from './commands/commands/inline-format.command';
-import { ReplaceContentCommand } from './commands/commands/replace-content.command';
+import { CoverContentCommand, ReplaceContentCommand } from './commands/commands/replace-content.command';
import { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
import { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/cursor.operation';
@@ -127,6 +128,7 @@ export class DocPlugin extends Plugin {
IMEInputCommand,
RichTextEditingMutation,
ReplaceContentCommand,
+ CoverContentCommand,
SetDocZoomRatioCommand,
SetDocZoomRatioOperation,
SetTextSelectionsOperation,
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index 00a9528c4f..7ef1cdf6e1 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -2,7 +2,9 @@ export { getDocObject } from './basics/component-tools';
export * from './basics/docs-view-key';
export { DocCopyCommand, DocCutCommand, DocPasteCommand } from './commands/commands/clipboard.command';
export {
+ BreakLineCommand,
DeleteCommand,
+ DeleteLeftCommand,
type ICoverCommandParams,
type IDeleteCommandParams,
type IInsertCommandParams,
@@ -10,7 +12,6 @@ export {
type IUpdateCommandParams,
UpdateCommand,
} from './commands/commands/core-editing.command';
-export { BreakLineCommand, DeleteLeftCommand } from './commands/commands/core-editing.command';
export { type IIMEInputCommandParams, IMEInputCommand } from './commands/commands/ime-input.command';
export {
SetInlineFormatBoldCommand,
@@ -22,12 +23,16 @@ export {
SetInlineFormatTextColorCommand,
SetInlineFormatUnderlineCommand,
} from './commands/commands/inline-format.command';
-export { ReplaceContentCommand } from './commands/commands/replace-content.command';
+export { CoverContentCommand, ReplaceContentCommand } from './commands/commands/replace-content.command';
export {
type IRichTextEditingMutationParams,
RichTextEditingMutation,
} from './commands/mutations/core-editing.mutation';
export { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/cursor.operation';
+export {
+ type ISetTextSelectionsOperationParams,
+ SetTextSelectionsOperation,
+} from './commands/operations/text-selection.operation';
export { DocPlugin, type IDocPluginConfig } from './doc-plugin';
export { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
export { DocViewModelManagerService } from './services/doc-view-model-manager.service';
diff --git a/packages/base-docs/src/services/doc-skeleton-manager.service.ts b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
index 5543c93ac8..467a6b97af 100644
--- a/packages/base-docs/src/services/doc-skeleton-manager.service.ts
+++ b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
@@ -1,5 +1,5 @@
import { DocumentSkeleton, DocumentViewModel } from '@univerjs/base-render';
-import { LocaleService, Nullable } from '@univerjs/core';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, LocaleService, Nullable } from '@univerjs/core';
import { IDisposable, Inject } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
@@ -54,7 +54,7 @@ export class DocSkeletonManagerService implements IDisposable {
}
getCurrent(): Nullable<IDocSkeletonManagerParam> {
- return this._getCurrentByUnitId(this._currentSkeletonUnitId);
+ return this.getSkeletonByUnitId(this._currentSkeletonUnitId);
}
makeDirtyCurrent(state: boolean = true) {
@@ -62,7 +62,7 @@ export class DocSkeletonManagerService implements IDisposable {
}
makeDirty(unitId: string, state: boolean = true) {
- const param = this._getCurrentByUnitId(unitId);
+ const param = this.getSkeletonByUnitId(unitId);
if (param == null) {
return;
}
@@ -73,15 +73,24 @@ export class DocSkeletonManagerService implements IDisposable {
private _setCurrent(docViewModelParam: IDocumentViewModelManagerParam): Nullable<IDocSkeletonManagerParam> {
const { unitId } = docViewModelParam;
- const skeleton = this._buildSkeleton(docViewModelParam.docViewModel);
+ // Only cell editor need to rebuild skeleton when edit cell content every time.
+ const REBUILD_SKELETON_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
- skeleton.calculate();
+ if (REBUILD_SKELETON_LIST.includes(unitId) || !this._docSkeletonMap.has(unitId)) {
+ const skeleton = this._buildSkeleton(docViewModelParam.docViewModel);
- this._docSkeletonMap.set(unitId, {
- unitId,
- skeleton,
- dirty: false,
- });
+ skeleton.calculate();
+
+ this._docSkeletonMap.set(unitId, {
+ unitId,
+ skeleton,
+ dirty: false,
+ });
+ } else {
+ const skeletonParam = this.getSkeletonByUnitId(unitId)!;
+ skeletonParam.skeleton.calculate();
+ skeletonParam.dirty = true;
+ }
this._currentSkeletonUnitId = unitId;
@@ -92,7 +101,7 @@ export class DocSkeletonManagerService implements IDisposable {
return this.getCurrent();
}
- private _getCurrentByUnitId(unitId: string): Nullable<IDocSkeletonManagerParam> {
+ getSkeletonByUnitId(unitId: string): Nullable<IDocSkeletonManagerParam> {
return this._docSkeletonMap.get(unitId);
}
diff --git a/packages/base-docs/src/services/doc-view-model-manager.service.ts b/packages/base-docs/src/services/doc-view-model-manager.service.ts
index 785b962914..3c85183374 100644
--- a/packages/base-docs/src/services/doc-view-model-manager.service.ts
+++ b/packages/base-docs/src/services/doc-view-model-manager.service.ts
@@ -1,5 +1,5 @@
import { DocumentViewModel } from '@univerjs/base-render';
-import { DocumentDataModel, IUniverInstanceService, Nullable } from '@univerjs/core';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentDataModel, IUniverInstanceService, Nullable } from '@univerjs/core';
import { IDisposable } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
@@ -45,12 +45,17 @@ export class DocViewModelManagerService implements IDisposable {
return;
}
- const docViewModel = this._buildDocViewModel(documentDataModel);
+ // Only cell editor need to rebuild view model when edit cell content every time.
+ const REBUILD_VIEW_MODEL_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
- this._docViewModelMap.set(unitId, {
- unitId,
- docViewModel,
- });
+ if (REBUILD_VIEW_MODEL_LIST.includes(unitId) || !this._docViewModelMap.has(unitId)) {
+ const docViewModel = this._buildDocViewModel(documentDataModel);
+
+ this._docViewModelMap.set(unitId, {
+ unitId,
+ docViewModel,
+ });
+ }
this._currentViewModelUnitId = unitId;
diff --git a/packages/base-docs/src/services/text-selection-manager.service.ts b/packages/base-docs/src/services/text-selection-manager.service.ts
index fce9215355..f6c4bc268d 100644
--- a/packages/base-docs/src/services/text-selection-manager.service.ts
+++ b/packages/base-docs/src/services/text-selection-manager.service.ts
@@ -1,6 +1,6 @@
-import { ITextRangeWithStyle, TextRange } from '@univerjs/base-render';
-import { ISelectionCell, Nullable } from '@univerjs/core';
-import { IDisposable } from '@wendellhu/redi';
+import type { ITextRangeWithStyle, TextRange } from '@univerjs/base-render';
+import type { ISelectionCell, Nullable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../basics/docs-view-key';
diff --git a/packages/base-docs/src/views/doc-canvas-view.ts b/packages/base-docs/src/views/doc-canvas-view.ts
index 85217f5231..dbb7316f91 100644
--- a/packages/base-docs/src/views/doc-canvas-view.ts
+++ b/packages/base-docs/src/views/doc-canvas-view.ts
@@ -1,23 +1,12 @@
/* eslint-disable no-magic-numbers */
+import type { IRender, IWheelEvent, RenderManagerService, Scene } from '@univerjs/base-render';
+import { Documents, EVENT_TYPE, IRenderManagerService, Layer, ScrollBar, Viewport } from '@univerjs/base-render';
+import type { DocumentDataModel, EventState, Nullable } from '@univerjs/core';
import {
- Documents,
- EVENT_TYPE,
- IRender,
- IRenderManagerService,
- IWheelEvent,
- Layer,
- RenderManagerService,
- Scene,
- ScrollBar,
- Viewport,
-} from '@univerjs/base-render';
-import {
- DocumentDataModel,
- EventState,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
IConfigService,
IUniverInstanceService,
LifecycleStages,
- Nullable,
OnLifecycle,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
@@ -134,7 +123,8 @@ export class DocCanvasView {
});
const hasScroll = this._configService.getConfig('hasScroll') as Nullable<boolean>;
- if (hasScroll !== false) {
+ // TODO: @JOCS, do not show scroll bar when initialize formula editor, any better way?
+ if (hasScroll !== false && unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
new ScrollBar(viewMain);
}
diff --git a/packages/base-render/src/base-object.ts b/packages/base-render/src/base-object.ts
index c719592551..549883c165 100644
--- a/packages/base-render/src/base-object.ts
+++ b/packages/base-render/src/base-object.ts
@@ -1,11 +1,14 @@
-import { EventState, IKeyValue, Nullable, Observable, Observer } from '@univerjs/core';
-
-import { CURSOR_TYPE, EVENT_TYPE, RENDER_CLASS_TYPE } from './basics/const';
-import { IMouseEvent, IPointerEvent, IWheelEvent } from './basics/i-events';
-import { IObjectFullState, ITransformChangeState, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './basics/interfaces';
+import type { EventState, IKeyValue, Nullable, Observer } from '@univerjs/core';
+import { Observable } from '@univerjs/core';
+
+import type { EVENT_TYPE } from './basics/const';
+import { CURSOR_TYPE, RENDER_CLASS_TYPE } from './basics/const';
+import type { IMouseEvent, IPointerEvent, IWheelEvent } from './basics/i-events';
+import type { IObjectFullState, ITransformChangeState } from './basics/interfaces';
+import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './basics/interfaces';
import { generateRandomKey, toPx } from './basics/tools';
import { Transform } from './basics/transform';
-import { IBoundRect, Vector2 } from './basics/vector2';
+import type { IBoundRect, Vector2 } from './basics/vector2';
export const BASE_OBJECT_ARRAY = [
'top',
@@ -338,6 +341,7 @@ export abstract class BaseObject {
if (state) {
this.parent?.makeDirty(state);
}
+
return this;
}
@@ -662,6 +666,7 @@ export abstract class BaseObject {
this.onPointerOverObserver.clear();
this.onPointerEnterObserver.clear();
this.onDblclickObserver.clear();
+ this.onTripleClickObserver.clear();
this.onIsAddedToParentObserver.clear();
this.parent?.removeObject(this);
@@ -676,6 +681,7 @@ export abstract class BaseObject {
props[key] = this[key as keyof BaseObject];
}
});
+
return props;
}
diff --git a/packages/base-render/src/canvas.ts b/packages/base-render/src/canvas.ts
index 10a7e0641d..5f42d6f1c5 100644
--- a/packages/base-render/src/canvas.ts
+++ b/packages/base-render/src/canvas.ts
@@ -82,6 +82,7 @@ export class Canvas {
// this.setWidth(width || 0);
// this.setHeight(height || 0);
this._pixelRatio = pixelRatioParam || getDevicePixelRatio();
+
if (width) {
this._width = width;
this._canvasEle.width = width * this._pixelRatio;
diff --git a/packages/base-render/src/components/component.ts b/packages/base-render/src/components/component.ts
index ee35c2ec28..aaf53b4293 100644
--- a/packages/base-render/src/components/component.ts
+++ b/packages/base-render/src/components/component.ts
@@ -1,8 +1,8 @@
import { sortRules } from '@univerjs/core';
import { BaseObject } from '../base-object';
-import { IBoundRect } from '../basics/vector2';
-import { ComponentExtension } from './extension';
+import type { IBoundRect } from '../basics/vector2';
+import type { ComponentExtension } from './extension';
export class RenderComponent<T, U> extends BaseObject {
private _extensions = new Map<string, ComponentExtension<T, U>>();
diff --git a/packages/base-render/src/components/docs/common/column.ts b/packages/base-render/src/components/docs/common/column.ts
index 5c55ab13ff..79a7c4ff5c 100644
--- a/packages/base-render/src/components/docs/common/column.ts
+++ b/packages/base-render/src/components/docs/common/column.ts
@@ -1,53 +1,54 @@
-import { ColumnSeparatorType, ISectionColumnProperties } from '@univerjs/core';
-
-import { IDocumentSkeletonColumn } from '../../../basics/i-document-skeleton-cached';
-
-export function createSkeletonColumn(
- columnIndex: number = 0,
- columnProperties: ISectionColumnProperties[],
- columnSeparatorType: ColumnSeparatorType = ColumnSeparatorType.NONE,
- pageWidth: number = Infinity
-): IDocumentSkeletonColumn {
- const { left, width, spaceWidth } = _calculateColumnSize(columnIndex, columnProperties, pageWidth);
-
- return {
- lines: [],
- // column坐标系相对于section
- left,
- width,
- height: 0,
- spaceWidth,
- separator: columnSeparatorType,
- st: 0,
- ed: 0,
- drawingLRIds: [],
- isFull: false,
- };
-}
-
-function _calculateColumnSize(
- columnIndex: number = 0,
- columnProperties: ISectionColumnProperties[],
- pageWidth: number
-) {
- let colWidth = 0;
- let spaceWidth = 0;
- let left = 0;
- for (let i = 0; i <= columnIndex; i++) {
- const { width, paddingEnd } = columnProperties[i];
- if (i === columnProperties.length - 1) {
- colWidth = pageWidth === Infinity ? pageWidth - colWidth : width;
- spaceWidth = 0;
- } else {
- spaceWidth = paddingEnd;
- colWidth = width;
- left += colWidth + spaceWidth;
- }
- }
-
- return {
- width: colWidth,
- spaceWidth,
- left: left - colWidth - spaceWidth,
- };
-}
+import type { ISectionColumnProperties } from '@univerjs/core';
+import { ColumnSeparatorType } from '@univerjs/core';
+
+import type { IDocumentSkeletonColumn } from '../../../basics/i-document-skeleton-cached';
+
+export function createSkeletonColumn(
+ columnIndex: number = 0,
+ columnProperties: ISectionColumnProperties[],
+ columnSeparatorType: ColumnSeparatorType = ColumnSeparatorType.NONE,
+ pageWidth: number = Infinity
+): IDocumentSkeletonColumn {
+ const { left, width, spaceWidth } = _calculateColumnSize(columnIndex, columnProperties, pageWidth);
+
+ return {
+ lines: [],
+ // column坐标系相对于section
+ left,
+ width,
+ height: 0,
+ spaceWidth,
+ separator: columnSeparatorType,
+ st: 0,
+ ed: 0,
+ drawingLRIds: [],
+ isFull: false,
+ };
+}
+
+function _calculateColumnSize(
+ columnIndex: number = 0,
+ columnProperties: ISectionColumnProperties[],
+ pageWidth: number
+) {
+ let colWidth = 0;
+ let spaceWidth = 0;
+ let left = 0;
+ for (let i = 0; i <= columnIndex; i++) {
+ const { width, paddingEnd } = columnProperties[i];
+ if (i === columnProperties.length - 1) {
+ colWidth = pageWidth === Infinity ? pageWidth - colWidth : width;
+ spaceWidth = 0;
+ } else {
+ spaceWidth = paddingEnd;
+ colWidth = width;
+ left += colWidth + spaceWidth;
+ }
+ }
+
+ return {
+ width: colWidth,
+ spaceWidth,
+ left: left - colWidth - spaceWidth,
+ };
+}
diff --git a/packages/base-render/src/components/docs/common/convert-cursor.ts b/packages/base-render/src/components/docs/common/convert-cursor.ts
index fde54f1c48..068e12918f 100644
--- a/packages/base-render/src/components/docs/common/convert-cursor.ts
+++ b/packages/base-render/src/components/docs/common/convert-cursor.ts
@@ -1,17 +1,17 @@
-import { IPosition, ITextRange, Nullable } from '@univerjs/core';
+import type { IPosition, ITextRange, Nullable } from '@univerjs/core';
-import {
+import type {
IDocumentSkeletonColumn,
IDocumentSkeletonDivide,
IDocumentSkeletonLine,
IDocumentSkeletonPage,
IDocumentSkeletonSection,
- SpanType,
} from '../../../basics/i-document-skeleton-cached';
-import { INodePosition } from '../../../basics/interfaces';
-import { IPoint } from '../../../basics/vector2';
-import { DocumentSkeleton } from '../doc-skeleton';
-import { IDocumentOffsetConfig } from '../document';
+import { SpanType } from '../../../basics/i-document-skeleton-cached';
+import type { INodePosition } from '../../../basics/interfaces';
+import type { IPoint } from '../../../basics/vector2';
+import type { DocumentSkeleton } from '../doc-skeleton';
+import type { IDocumentOffsetConfig } from '../document';
import { Liquid } from './liquid';
export enum NodePositionStateType {
diff --git a/packages/base-render/src/components/docs/common/line.ts b/packages/base-render/src/components/docs/common/line.ts
index 946525e065..a8fb0b22e9 100644
--- a/packages/base-render/src/components/docs/common/line.ts
+++ b/packages/base-render/src/components/docs/common/line.ts
@@ -1,6 +1,7 @@
-import { IDrawing, Nullable, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
+import type { IDrawing, Nullable } from '@univerjs/core';
+import { PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
-import {
+import type {
IDocumentSkeletonDivide,
IDocumentSkeletonDrawing,
IDocumentSkeletonDrawingAnchor,
diff --git a/packages/base-render/src/components/docs/common/liquid.ts b/packages/base-render/src/components/docs/common/liquid.ts
index bbfc5e3799..21c5d43680 100644
--- a/packages/base-render/src/components/docs/common/liquid.ts
+++ b/packages/base-render/src/components/docs/common/liquid.ts
@@ -1,12 +1,12 @@
-import {
+import type {
IDocumentSkeletonColumn,
IDocumentSkeletonDivide,
IDocumentSkeletonLine,
IDocumentSkeletonPage,
IDocumentSkeletonSection,
IDocumentSkeletonSpan,
- PageLayoutType,
} from '../../../basics/i-document-skeleton-cached';
+import { PageLayoutType } from '../../../basics/i-document-skeleton-cached';
export class Liquid {
private _translateX: number = 0;
diff --git a/packages/base-render/src/components/docs/common/page.ts b/packages/base-render/src/components/docs/common/page.ts
index 23b963344c..7bd8e71bc4 100644
--- a/packages/base-render/src/components/docs/common/page.ts
+++ b/packages/base-render/src/components/docs/common/page.ts
@@ -1,16 +1,17 @@
-import { Nullable, PageOrientType } from '@univerjs/core';
+import type { Nullable } from '@univerjs/core';
+import { PageOrientType } from '@univerjs/core';
-import {
- BreakType,
+import type {
IDocumentSkeletonFooter,
IDocumentSkeletonHeader,
IDocumentSkeletonPage,
ISkeletonResourceReference,
} from '../../../basics/i-document-skeleton-cached';
-import { ISectionBreakConfig } from '../../../basics/interfaces';
+import { BreakType } from '../../../basics/i-document-skeleton-cached';
+import type { ISectionBreakConfig } from '../../../basics/interfaces';
// eslint-disable-next-line import/no-cycle
import { dealWithSections } from '../block/section';
-import { DocumentViewModel } from '../view-model/document-view-model';
+import type { DocumentViewModel } from '../view-model/document-view-model';
import { createSkeletonSection } from './section';
import { updateBlockIndex } from './tools';
diff --git a/packages/base-render/src/components/docs/common/range.ts b/packages/base-render/src/components/docs/common/range.ts
index 55b6fa1232..0402305e60 100644
--- a/packages/base-render/src/components/docs/common/range.ts
+++ b/packages/base-render/src/components/docs/common/range.ts
@@ -1,21 +1,18 @@
-import { ITextRange, Nullable, Tools } from '@univerjs/core';
+import type { ITextRange, Nullable } from '@univerjs/core';
+import { Tools } from '@univerjs/core';
import { COLORS } from '../../../basics/const';
-import { INodePosition } from '../../../basics/interfaces';
-import {
- ITextRangeWithStyle,
- ITextSelectionStyle,
- NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
- RANGE_DIRECTION,
-} from '../../../basics/range';
+import type { INodePosition } from '../../../basics/interfaces';
+import type { ITextRangeWithStyle, ITextSelectionStyle } from '../../../basics/range';
+import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RANGE_DIRECTION } from '../../../basics/range';
import { getColor } from '../../../basics/tools';
-import { IPoint } from '../../../basics/vector2';
-import { Scene } from '../../../scene';
+import type { IPoint } from '../../../basics/vector2';
+import type { Scene } from '../../../scene';
import { Rect } from '../../../shape/rect';
import { RegularPolygon } from '../../../shape/regular-polygon';
-import { ThinScene } from '../../../thin-scene';
-import { DocumentSkeleton } from '../doc-skeleton';
-import { IDocumentOffsetConfig } from '../document';
+import type { ThinScene } from '../../../thin-scene';
+import type { DocumentSkeleton } from '../doc-skeleton';
+import type { IDocumentOffsetConfig } from '../document';
import {
compareNodePosition,
compareNodePositionLogic,
diff --git a/packages/base-render/src/components/docs/common/section.ts b/packages/base-render/src/components/docs/common/section.ts
index 6485e4c2cc..403929748c 100644
--- a/packages/base-render/src/components/docs/common/section.ts
+++ b/packages/base-render/src/components/docs/common/section.ts
@@ -1,76 +1,77 @@
-import { ColumnSeparatorType, ISectionColumnProperties } from '@univerjs/core';
-
-import { IDocumentSkeletonColumn, IDocumentSkeletonSection } from '../../../basics/i-document-skeleton-cached';
-
-export function createSkeletonSection(
- columnProperties: ISectionColumnProperties[] = [],
- columnSeparatorType: ColumnSeparatorType = ColumnSeparatorType.NONE,
- top: number = 0,
- left: number = 0,
- sectionWidth: number = Infinity,
- sectionHeight: number = Infinity
-): IDocumentSkeletonSection {
- const columns: IDocumentSkeletonColumn[] = [];
- let colWidth = 0;
- let spaceWidth = 0;
-
- if (columnProperties.length === 0) {
- columns.push(_getSkeletonColumn(left, sectionWidth, 0, ColumnSeparatorType.NONE));
- } else {
- for (let i = 0; i < columnProperties.length; i++) {
- const { width, paddingEnd } = columnProperties[i];
-
- spaceWidth = paddingEnd;
- colWidth = width;
-
- columns.push(_getSkeletonColumn(left, colWidth, spaceWidth, columnSeparatorType));
-
- left += colWidth + spaceWidth;
-
- if (i === columnProperties.length - 1) {
- colWidth = sectionWidth !== Infinity ? sectionWidth - colWidth : width;
- spaceWidth = 0;
- columns.push(_getSkeletonColumn(left, colWidth, spaceWidth, columnSeparatorType));
- }
- }
- }
- const newSection = {
- columns,
- colCount: columnProperties?.length || 1,
- height: sectionHeight,
- top,
- st: 0,
- ed: 0,
- };
-
- columns.forEach((column) => {
- column.parent = newSection;
- });
-
- return newSection;
-}
-
-export function setColumnFullState(column: IDocumentSkeletonColumn, state: boolean) {
- column.isFull = state;
-}
-
-function _getSkeletonColumn(
- left: number,
- width: number,
- spaceWidth: number,
- columnSeparatorType: ColumnSeparatorType
-): IDocumentSkeletonColumn {
- return {
- lines: [],
- // column坐标系相对于section
- left,
- width,
- height: 0,
- spaceWidth,
- separator: columnSeparatorType,
- st: 0,
- ed: 0,
- drawingLRIds: [],
- isFull: false,
- };
-}
+import type { ISectionColumnProperties } from '@univerjs/core';
+import { ColumnSeparatorType } from '@univerjs/core';
+
+import type { IDocumentSkeletonColumn, IDocumentSkeletonSection } from '../../../basics/i-document-skeleton-cached';
+
+export function createSkeletonSection(
+ columnProperties: ISectionColumnProperties[] = [],
+ columnSeparatorType: ColumnSeparatorType = ColumnSeparatorType.NONE,
+ top: number = 0,
+ left: number = 0,
+ sectionWidth: number = Infinity,
+ sectionHeight: number = Infinity
+): IDocumentSkeletonSection {
+ const columns: IDocumentSkeletonColumn[] = [];
+ let colWidth = 0;
+ let spaceWidth = 0;
+
+ if (columnProperties.length === 0) {
+ columns.push(_getSkeletonColumn(left, sectionWidth, 0, ColumnSeparatorType.NONE));
+ } else {
+ for (let i = 0; i < columnProperties.length; i++) {
+ const { width, paddingEnd } = columnProperties[i];
+
+ spaceWidth = paddingEnd;
+ colWidth = width;
+
+ columns.push(_getSkeletonColumn(left, colWidth, spaceWidth, columnSeparatorType));
+
+ left += colWidth + spaceWidth;
+
+ if (i === columnProperties.length - 1) {
+ colWidth = sectionWidth !== Infinity ? sectionWidth - colWidth : width;
+ spaceWidth = 0;
+ columns.push(_getSkeletonColumn(left, colWidth, spaceWidth, columnSeparatorType));
+ }
+ }
+ }
+ const newSection = {
+ columns,
+ colCount: columnProperties?.length || 1,
+ height: sectionHeight,
+ top,
+ st: 0,
+ ed: 0,
+ };
+
+ columns.forEach((column) => {
+ column.parent = newSection;
+ });
+
+ return newSection;
+}
+
+export function setColumnFullState(column: IDocumentSkeletonColumn, state: boolean) {
+ column.isFull = state;
+}
+
+function _getSkeletonColumn(
+ left: number,
+ width: number,
+ spaceWidth: number,
+ columnSeparatorType: ColumnSeparatorType
+): IDocumentSkeletonColumn {
+ return {
+ lines: [],
+ // column坐标系相对于section
+ left,
+ width,
+ height: 0,
+ spaceWidth,
+ separator: columnSeparatorType,
+ st: 0,
+ ed: 0,
+ drawingLRIds: [],
+ isFull: false,
+ };
+}
diff --git a/packages/base-render/src/components/docs/common/span.ts b/packages/base-render/src/components/docs/common/span.ts
index 61832129f9..7dc566d82c 100644
--- a/packages/base-render/src/components/docs/common/span.ts
+++ b/packages/base-render/src/components/docs/common/span.ts
@@ -1,13 +1,13 @@
import { BooleanNumber, BulletAlignment, DataStreamTreeTokenType as DT, GridType } from '@univerjs/core';
import { FontCache } from '../../../basics/font-cache';
-import {
+import type {
IDocumentSkeletonBullet,
IDocumentSkeletonDivide,
IDocumentSkeletonSpan,
- SpanType,
} from '../../../basics/i-document-skeleton-cached';
-import { IFontCreateConfig } from '../../../basics/interfaces';
+import { SpanType } from '../../../basics/i-document-skeleton-cached';
+import type { IFontCreateConfig } from '../../../basics/interfaces';
import { hasCJK } from '../../../basics/tools';
import { validationGrid } from './tools';
diff --git a/packages/base-render/src/components/docs/common/tools.ts b/packages/base-render/src/components/docs/common/tools.ts
index f09abc2147..dc7ccd93ee 100644
--- a/packages/base-render/src/components/docs/common/tools.ts
+++ b/packages/base-render/src/components/docs/common/tools.ts
@@ -1,34 +1,36 @@
+import type {
+ INumberUnit,
+ IParagraphStyle,
+ ITextStyle,
+ Nullable,
+ ObjectPositionH,
+ ObjectPositionV,
+} from '@univerjs/core';
import {
AlignTypeH,
AlignTypeV,
BooleanNumber,
GridType,
- INumberUnit,
- IParagraphStyle,
- ITextStyle,
- Nullable,
NumberUnitType,
ObjectMatrix,
- ObjectPositionH,
- ObjectPositionV,
ObjectRelativeFromH,
ObjectRelativeFromV,
SpacingRule,
} from '@univerjs/core';
import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';
-import {
+import type {
IDocumentSkeletonColumn,
IDocumentSkeletonDivide,
IDocumentSkeletonLine,
IDocumentSkeletonPage,
IDocumentSkeletonSpan,
- SpanType,
} from '../../../basics/i-document-skeleton-cached';
-import { IParagraphConfig, ISectionBreakConfig } from '../../../basics/interfaces';
+import { SpanType } from '../../../basics/i-document-skeleton-cached';
+import type { IParagraphConfig, ISectionBreakConfig } from '../../../basics/interfaces';
import { getFontStyleString, isFunction } from '../../../basics/tools';
-import { DataStreamTreeNode } from '../view-model/data-stream-tree-node';
-import { DocumentViewModel } from '../view-model/document-view-model';
+import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';
+import type { DocumentViewModel } from '../view-model/document-view-model';
export function getLastPage(pages: IDocumentSkeletonPage[]) {
return pages?.[pages.length - 1];
diff --git a/packages/base-render/src/components/docs/doc-component.ts b/packages/base-render/src/components/docs/doc-component.ts
index e82f5918a6..84c22d9b74 100644
--- a/packages/base-render/src/components/docs/doc-component.ts
+++ b/packages/base-render/src/components/docs/doc-component.ts
@@ -1,14 +1,15 @@
-import { Nullable } from '@univerjs/core';
+import type { Nullable } from '@univerjs/core';
import { RENDER_CLASS_TYPE } from '../../basics/const';
-import { IDocumentSkeletonLine, IDocumentSkeletonSpan, PageLayoutType } from '../../basics/i-document-skeleton-cached';
-import { INodeInfo, ITransformChangeState } from '../../basics/interfaces';
-import { IBoundRect } from '../../basics/vector2';
+import type { IDocumentSkeletonLine, IDocumentSkeletonSpan } from '../../basics/i-document-skeleton-cached';
+import { PageLayoutType } from '../../basics/i-document-skeleton-cached';
+import type { INodeInfo, ITransformChangeState } from '../../basics/interfaces';
+import type { IBoundRect } from '../../basics/vector2';
import { Canvas } from '../../canvas';
-import { Scene } from '../../scene';
+import type { Scene } from '../../scene';
import { RenderComponent } from '../component';
-import { DOCS_EXTENSION_TYPE } from './doc-extension';
-import { DocumentSkeleton } from './doc-skeleton';
+import type { DOCS_EXTENSION_TYPE } from './doc-extension';
+import type { DocumentSkeleton } from './doc-skeleton';
export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE> {
pageMarginLeft: number = 0;
diff --git a/packages/base-render/src/components/docs/doc-extension.ts b/packages/base-render/src/components/docs/doc-extension.ts
index bc77b0162f..c50de71a81 100644
--- a/packages/base-render/src/components/docs/doc-extension.ts
+++ b/packages/base-render/src/components/docs/doc-extension.ts
@@ -1,4 +1,4 @@
-import { IDocumentSkeletonLine, IDocumentSkeletonSpan } from '../../basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonLine, IDocumentSkeletonSpan } from '../../basics/i-document-skeleton-cached';
import { ComponentExtension } from '../extension';
export enum DOCS_EXTENSION_TYPE {
diff --git a/packages/base-render/src/components/docs/doc-skeleton.ts b/packages/base-render/src/components/docs/doc-skeleton.ts
index 25c42daaf6..3a8d514c83 100644
--- a/packages/base-render/src/components/docs/doc-skeleton.ts
+++ b/packages/base-render/src/components/docs/doc-skeleton.ts
@@ -1,36 +1,31 @@
/* eslint-disable no-magic-numbers */
+import type { ISectionBreak, ISectionColumnProperties, LocaleService, Nullable } from '@univerjs/core';
import {
ColumnSeparatorType,
GridType,
HorizontalAlign,
- ISectionBreak,
- ISectionColumnProperties,
- LocaleService,
- Nullable,
PageOrientType,
SectionType,
VerticalAlign,
WrapStrategy,
} from '@univerjs/core';
-import {
+import type {
IDocumentSkeletonCached,
IDocumentSkeletonPage,
IDocumentSkeletonSpan,
ISkeletonResourceReference,
- LineType,
- PageLayoutType,
- SpanType,
} from '../../basics/i-document-skeleton-cached';
-import { IDocsConfig, INodeInfo, INodePosition, INodeSearch, ISectionBreakConfig } from '../../basics/interfaces';
-import { IBoundRect, Vector2 } from '../../basics/vector2';
+import { LineType, PageLayoutType, SpanType } from '../../basics/i-document-skeleton-cached';
+import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch, ISectionBreakConfig } from '../../basics/interfaces';
+import type { IBoundRect, Vector2 } from '../../basics/vector2';
import { Skeleton } from '../skeleton';
import { dealWithSections } from './block/section';
import { Liquid } from './common/liquid';
import { createSkeletonPage } from './common/page';
import { createSkeletonSection } from './common/section';
import { getLastPage, updateBlockIndex } from './common/tools';
-import { DocumentViewModel } from './view-model/document-view-model';
+import type { DocumentViewModel } from './view-model/document-view-model';
const DEFAULT_SECTION_BREAK: ISectionBreak = {
columnProperties: [],
diff --git a/packages/base-render/src/components/docs/document.ts b/packages/base-render/src/components/docs/document.ts
index 937297b50f..e4b4bf449f 100644
--- a/packages/base-render/src/components/docs/document.ts
+++ b/packages/base-render/src/components/docs/document.ts
@@ -1,31 +1,22 @@
import './extensions';
-import {
- BooleanNumber,
- HorizontalAlign,
- Nullable,
- Observable,
- Observer,
- VerticalAlign,
- WrapStrategy,
-} from '@univerjs/core';
+import type { Nullable, Observer } from '@univerjs/core';
+import { BooleanNumber, HorizontalAlign, Observable, VerticalAlign, WrapStrategy } from '@univerjs/core';
import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';
-import {
- IDocumentSkeletonCached,
- IDocumentSkeletonPage,
- LineType,
- PageLayoutType,
-} from '../../basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonCached, IDocumentSkeletonPage } from '../../basics/i-document-skeleton-cached';
+import { LineType, PageLayoutType } from '../../basics/i-document-skeleton-cached';
import { degToRad, fixLineWidthByScale, getScale } from '../../basics/tools';
-import { Transform } from '../../basics/transform';
-import { IBoundRect, Vector2 } from '../../basics/vector2';
-import { Scene } from '../../scene';
-import { DocumentsSpanAndLineExtensionRegistry, IExtensionConfig } from '../extension';
+import type { Transform } from '../../basics/transform';
+import type { IBoundRect } from '../../basics/vector2';
+import { Vector2 } from '../../basics/vector2';
+import type { Scene } from '../../scene';
+import type { IExtensionConfig } from '../extension';
+import { DocumentsSpanAndLineExtensionRegistry } from '../extension';
import { Liquid } from './common/liquid';
import { DocComponent } from './doc-component';
import { DOCS_EXTENSION_TYPE } from './doc-extension';
-import { DocumentSkeleton } from './doc-skeleton';
+import type { DocumentSkeleton } from './doc-skeleton';
interface IPageMarginLayout {
pageMarginLeft: number;
@@ -232,12 +223,14 @@ export class Documents extends DocComponent {
pagePaddingRight * scale,
horizontalAlign
);
+
const verticalOffsetNoAngle = this._verticalHandler(
actualHeight * scale,
pagePaddingTop * scale,
pagePaddingBottom * scale,
verticalAlign
);
+
const alignOffsetNoAngle = Vector2.create(horizontalOffsetNoAngle / scale, verticalOffsetNoAngle / scale);
const centerAngle = degToRad(centerAngleDeg);
diff --git a/packages/base-render/src/components/docs/extensions/background.ts b/packages/base-render/src/components/docs/extensions/background.ts
index 4375128a62..33b45a7282 100644
--- a/packages/base-render/src/components/docs/extensions/background.ts
+++ b/packages/base-render/src/components/docs/extensions/background.ts
@@ -1,6 +1,7 @@
-import { getColorStyle, IScale } from '@univerjs/core';
+import type { IScale } from '@univerjs/core';
+import { getColorStyle } from '@univerjs/core';
-import { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
import { Vector2 } from '../../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
import { docExtension } from '../doc-extension';
diff --git a/packages/base-render/src/components/docs/extensions/border.ts b/packages/base-render/src/components/docs/extensions/border.ts
index 16b0a94741..ba478df8fe 100644
--- a/packages/base-render/src/components/docs/extensions/border.ts
+++ b/packages/base-render/src/components/docs/extensions/border.ts
@@ -1,8 +1,9 @@
-import { BorderStyleTypes, getColorStyle, IBorderData, IBorderStyleData, IScale, Nullable } from '@univerjs/core';
+import type { BorderStyleTypes, IBorderData, IBorderStyleData, IScale, Nullable } from '@univerjs/core';
+import { getColorStyle } from '@univerjs/core';
import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../../basics/const';
import { drawLineByBorderType, getLineWidth, setLineType } from '../../../basics/draw';
-import { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
import { Vector2 } from '../../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
import { docExtension } from '../doc-extension';
diff --git a/packages/base-render/src/components/docs/extensions/font-and-base-line.ts b/packages/base-render/src/components/docs/extensions/font-and-base-line.ts
index 07909b51ae..09e47d8aed 100644
--- a/packages/base-render/src/components/docs/extensions/font-and-base-line.ts
+++ b/packages/base-render/src/components/docs/extensions/font-and-base-line.ts
@@ -1,7 +1,8 @@
-import { BaselineOffset, getColorStyle, IScale } from '@univerjs/core';
+import type { IScale } from '@univerjs/core';
+import { BaselineOffset, getColorStyle } from '@univerjs/core';
import { COLOR_BLACK_RGB } from '../../../basics/const';
-import { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
import { Vector2 } from '../../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
import { docExtension } from '../doc-extension';
diff --git a/packages/base-render/src/components/docs/extensions/line.ts b/packages/base-render/src/components/docs/extensions/line.ts
index 1ba4151590..4a536b49a0 100644
--- a/packages/base-render/src/components/docs/extensions/line.ts
+++ b/packages/base-render/src/components/docs/extensions/line.ts
@@ -1,8 +1,9 @@
-import { BooleanNumber, getColorStyle, IScale, TextDecoration } from '@univerjs/core';
+import type { IScale } from '@univerjs/core';
+import { BooleanNumber, getColorStyle, TextDecoration } from '@univerjs/core';
import { COLOR_BLACK_RGB, DEFAULT_OFFSET_SPACING } from '../../../basics/const';
import { calculateRectRotate } from '../../../basics/draw';
-import { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';
import { fixLineWidthByScale, getScale } from '../../../basics/tools';
import { Vector2 } from '../../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
diff --git a/packages/base-render/src/components/docs/text-selection-render-manager.ts b/packages/base-render/src/components/docs/text-selection-render-manager.ts
index 55608aeaf7..71c3ad3927 100644
--- a/packages/base-render/src/components/docs/text-selection-render-manager.ts
+++ b/packages/base-render/src/components/docs/text-selection-render-manager.ts
@@ -1,29 +1,28 @@
-import { DataStreamTreeTokenType, Nullable, Observer, RxDisposable } from '@univerjs/core';
+import type { Nullable, Observer } from '@univerjs/core';
+import { DataStreamTreeTokenType, RxDisposable } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject } from 'rxjs';
import { CURSOR_TYPE } from '../../basics/const';
-import { IDocumentSkeletonSpan, PageLayoutType } from '../../basics/i-document-skeleton-cached';
-import { IMouseEvent, IPointerEvent } from '../../basics/i-events';
-import { INodeInfo, INodePosition } from '../../basics/interfaces';
+import type { IDocumentSkeletonSpan } from '../../basics/i-document-skeleton-cached';
+import { PageLayoutType } from '../../basics/i-document-skeleton-cached';
+import type { IMouseEvent, IPointerEvent } from '../../basics/i-events';
+import type { INodeInfo, INodePosition } from '../../basics/interfaces';
import { getOffsetRectForDom, transformBoundingCoord } from '../../basics/position';
-import {
- ITextRangeWithStyle,
- ITextSelectionStyle,
- NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
- RANGE_DIRECTION,
-} from '../../basics/range';
+import type { ITextRangeWithStyle, ITextSelectionStyle, RANGE_DIRECTION } from '../../basics/range';
+import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '../../basics/range';
import { getCurrentScrollXY } from '../../basics/scroll-xy';
import { checkStyle, injectStyle } from '../../basics/tools';
import { Transform } from '../../basics/transform';
import { Vector2 } from '../../basics/vector2';
-import { Engine } from '../../engine';
-import { Scene } from '../../scene';
+import type { Engine } from '../../engine';
+import type { Scene } from '../../scene';
import { ScrollTimer } from '../../scroll-timer';
-import { IScrollObserverParam, Viewport } from '../../viewport';
+import type { IScrollObserverParam, Viewport } from '../../viewport';
import { cursorConvertToTextRange, TextRange } from './common/range';
-import { DocumentSkeleton } from './doc-skeleton';
-import { IDocumentOffsetConfig } from './document';
+import type { DocumentSkeleton } from './doc-skeleton';
+import type { IDocumentOffsetConfig } from './document';
export function getCanvasOffsetByEngine(engine: Nullable<Engine>) {
const canvas = engine?.getCanvasElement();
@@ -126,7 +125,12 @@ export interface ITextSelectionRenderManager {
deactivate(): void;
- changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene): void;
+ changeRuntime(
+ docSkeleton: DocumentSkeleton,
+ scene: Scene,
+ viewport?: Nullable<Viewport>,
+ documentOffsetConfig?: IDocumentOffsetConfig
+ ): void;
dispose(): void;
@@ -352,6 +356,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._scrollToSelection();
}
+ // Sync canvas selection to dom selection.
sync() {
this._syncDomToSelection();
}
@@ -392,6 +397,11 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
) {
// this._docSkeleton?.onRecalculateChangeObservable.remove(this._skeletonObserver);
+ // Need to empty text ranges when change doc.
+ if (docSkeleton !== this._docSkeleton) {
+ this.removeAllTextRanges();
+ }
+
this._docSkeleton = docSkeleton;
this._scene = scene;
@@ -871,27 +881,27 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
// top *= scaleY;
const { tl, tr, bl } = this._activeViewport.getBounding();
- const constantOffsetWidth = (width * 2) / scaleX;
- const constantOffsetHeight = (height * 2) / scaleY;
+ const constantOffsetWidth = width / scaleX;
+ const constantOffsetHeight = height / scaleY;
let offsetY = 0;
let offsetX = 0;
const boundTop = tl.y;
const boundBottom = bl.y;
- if (top < boundTop + constantOffsetHeight) {
- offsetY = top - boundTop - constantOffsetHeight * 2;
+ if (top < boundTop) {
+ offsetY = top - boundTop;
} else if (top > boundBottom - constantOffsetHeight) {
- offsetY = top - boundBottom + constantOffsetHeight * 2;
+ offsetY = top - boundBottom + constantOffsetHeight;
}
const boundLeft = tl.x;
const boundRight = tr.x;
- if (left < boundLeft + constantOffsetWidth) {
- offsetX = left - boundLeft - constantOffsetWidth * 2;
+ if (left < boundLeft) {
+ offsetX = left - boundLeft;
} else if (left > boundRight - constantOffsetWidth) {
- offsetX = left - boundRight + constantOffsetWidth * 2;
+ offsetX = left - boundRight + constantOffsetWidth;
}
const config = this._activeViewport.getBarScroll(offsetX, offsetY);
diff --git a/packages/base-render/src/components/docs/view-model/data-stream-tree-node.ts b/packages/base-render/src/components/docs/view-model/data-stream-tree-node.ts
index b0713b1f56..def3c4d891 100644
--- a/packages/base-render/src/components/docs/view-model/data-stream-tree-node.ts
+++ b/packages/base-render/src/components/docs/view-model/data-stream-tree-node.ts
@@ -1,10 +1,10 @@
+import type { Nullable } from '@univerjs/core';
import {
DataStreamTreeNodeType,
DataStreamTreeTokenType,
deleteContent,
horizontalLineSegmentsSubtraction,
insertTextToContent,
- Nullable,
} from '@univerjs/core';
export class DataStreamTreeNode {
diff --git a/packages/base-render/src/components/docs/view-model/document-view-model.ts b/packages/base-render/src/components/docs/view-model/document-view-model.ts
index 6d0b06db5d..2bdf9470c6 100644
--- a/packages/base-render/src/components/docs/view-model/document-view-model.ts
+++ b/packages/base-render/src/components/docs/view-model/document-view-model.ts
@@ -1,12 +1,6 @@
-import {
- DataStreamTreeNodeType,
- DataStreamTreeTokenType,
- DocumentDataModel,
- IDocumentBody,
- ITextRun,
- Nullable,
-} from '@univerjs/core';
-import { IDisposable } from '@wendellhu/redi';
+import type { IDocumentBody, ITextRun, Nullable } from '@univerjs/core';
+import { DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentDataModel } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
import { DataStreamTreeNode } from './data-stream-tree-node';
diff --git a/packages/base-render/src/engine.ts b/packages/base-render/src/engine.ts
index 718a00ae66..bb664ac0cc 100644
--- a/packages/base-render/src/engine.ts
+++ b/packages/base-render/src/engine.ts
@@ -147,6 +147,7 @@ export class Engine extends ThinEngine<Scene> {
}
const { width, height } = getSizeForDom(this._container);
+
this.resizeBySize(width, height);
}
diff --git a/packages/base-render/src/render-manager.service.ts b/packages/base-render/src/render-manager.service.ts
index b5b231bf53..7446e4a379 100644
--- a/packages/base-render/src/render-manager.service.ts
+++ b/packages/base-render/src/render-manager.service.ts
@@ -1,11 +1,12 @@
-import { Nullable } from '@univerjs/core';
+import type { Nullable } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject } from 'rxjs';
-import { BaseObject } from './base-object';
-import { DocComponent } from './components/docs/doc-component';
-import { SheetComponent } from './components/sheets/sheet-component';
-import { Slide } from './components/slides/slide';
+import type { BaseObject } from './base-object';
+import type { DocComponent } from './components/docs/doc-component';
+import type { SheetComponent } from './components/sheets/sheet-component';
+import type { Slide } from './components/slides/slide';
import { Engine } from './engine';
import { Scene } from './scene';
import { SceneViewer } from './scene-viewer';
diff --git a/packages/base-render/src/scene.ts b/packages/base-render/src/scene.ts
index b6fa55ceed..8fc58460a3 100644
--- a/packages/base-render/src/scene.ts
+++ b/packages/base-render/src/scene.ts
@@ -247,6 +247,7 @@ export class Scene extends ThinScene {
if (optionKeys.length === 0) {
return;
}
+
optionKeys.forEach((pKey) => {
if (state[pKey as keyof ISceneTransformState] !== undefined) {
(preKeys as IKeyValue)[pKey] = this[pKey as keyof Scene];
diff --git a/packages/base-render/src/viewport.ts b/packages/base-render/src/viewport.ts
index d139e97767..41c74843f5 100644
--- a/packages/base-render/src/viewport.ts
+++ b/packages/base-render/src/viewport.ts
@@ -1,13 +1,16 @@
-import { EventState, IPosition, Nullable, Observable } from '@univerjs/core';
+import type { EventState, IPosition, Nullable } from '@univerjs/core';
+import { Observable } from '@univerjs/core';
import { RENDER_CLASS_TYPE } from './basics/const';
-import { IWheelEvent, PointerInput } from './basics/i-events';
+import type { IWheelEvent } from './basics/i-events';
+import { PointerInput } from './basics/i-events';
import { toPx } from './basics/tools';
import { Transform } from './basics/transform';
-import { IBoundRect, Vector2 } from './basics/vector2';
+import type { IBoundRect } from './basics/vector2';
+import { Vector2 } from './basics/vector2';
import { Canvas } from './canvas';
-import { BaseScrollBar } from './shape/base-scroll-bar';
-import { ThinScene } from './thin-scene';
+import type { BaseScrollBar } from './shape/base-scroll-bar';
+import type { ThinScene } from './thin-scene';
interface IViewPosition {
top?: number;
@@ -382,6 +385,7 @@ export class Viewport {
getBarScroll(actualX: number, actualY: number) {
let x = actualX - this._paddingStartX;
let y = actualY - this._paddingStartY;
+
if (this._scrollBar) {
x *= this._scrollBar.ratioScrollX; // convert to scroll coord
y *= this._scrollBar.ratioScrollY;
@@ -397,6 +401,7 @@ export class Viewport {
y = this.scrollY;
}
}
+
return {
x,
y,
diff --git a/packages/base-sheets/src/commands/operations/selection.operation.ts b/packages/base-sheets/src/commands/operations/selection.operation.ts
index 4cc14f63f9..f807502ea6 100644
--- a/packages/base-sheets/src/commands/operations/selection.operation.ts
+++ b/packages/base-sheets/src/commands/operations/selection.operation.ts
@@ -1,6 +1,7 @@
-import { CommandType, IOperation } from '@univerjs/core';
+import type { IOperation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
-import { ISelectionWithStyle } from '../../basics/selection';
+import type { ISelectionWithStyle } from '../../basics/selection';
import { SelectionManagerService } from '../../services/selection-manager.service';
export interface ISetSelectionsOperationParams {
diff --git a/packages/base-ui/src/views/App.tsx b/packages/base-ui/src/views/App.tsx
index 8435260639..2d17f74c38 100644
--- a/packages/base-ui/src/views/App.tsx
+++ b/packages/base-ui/src/views/App.tsx
@@ -2,7 +2,6 @@ import { LocaleService, ThemeService } from '@univerjs/core';
import type { ILocale } from '@univerjs/design';
import { ConfigProvider, defaultTheme, themeInstance } from '@univerjs/design';
import { useDependency } from '@wendellhu/redi/react-bindings';
-import clsx from 'clsx';
import type { ComponentType } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
@@ -93,30 +92,28 @@ export function App(props: IUniverAppProps) {
{/* content */}
<section className={styles.appContainer}>
- <section
- className={clsx(styles.appContainerMain, { [styles.appContainerMainCollapsed]: mainCollapsed })}
- >
- <header className={styles.appContainerHeader}>
- {props.toolbar && <Toolbar />}
-
- <ComponentContainer components={headerComponents} />
- </header>
-
- {/* <ComponentContainer components={sidebarComponents} /> */}
-
- <section
- ref={contentRef}
- className={styles.appContainerContent}
- data-range-selector
- onContextMenu={(e) => e.preventDefault()}
- >
- <ComponentContainer components={contentComponents} />
+ <header className={styles.appContainerHeader}>{props.toolbar && <Toolbar />}</header>
+
+ <section className={styles.appContainerWrapper}>
+ <section className={styles.appContainerContent}>
+ <header>
+ <ComponentContainer components={headerComponents} />
+ </header>
+
+ <section
+ className={styles.appContainerCanvas}
+ ref={contentRef}
+ data-range-selector
+ onContextMenu={(e) => e.preventDefault()}
+ >
+ <ComponentContainer components={contentComponents} />
+ </section>
</section>
- </section>
- <aside className={styles.appContainerSidebar}>
- <Sidebar />
- </aside>
+ <aside className={styles.appContainerSidebar}>
+ <Sidebar />
+ </aside>
+ </section>
</section>
{/* footer */}
diff --git a/packages/base-ui/src/views/app.module.less b/packages/base-ui/src/views/app.module.less
index 9f6f7eb6df..5d65a983e6 100644
--- a/packages/base-ui/src/views/app.module.less
+++ b/packages/base-ui/src/views/app.module.less
@@ -18,24 +18,9 @@
}
&-container {
- display: grid;
- grid-template-columns: 1fr auto;
+ display: flex;
flex: 1;
-
- &-main {
- overflow: hidden;
- display: grid;
- grid-template-rows: auto 1fr;
-
- border-top: 1px solid rgb(var(--border-color));
- border-bottom: 1px solid rgb(var(--border-color));
-
- &&-collapsed {
- border-right: 1px solid rgb(var(--border-color));
- border-top-right-radius: var(--border-radius-lg);
- border-bottom-right-radius: var(--border-radius-lg);
- }
- }
+ flex-direction: column;
&-header {
position: relative;
@@ -43,9 +28,26 @@
width: 100%;
}
+ &-wrapper {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ height: 100%;
+ }
+
&-content {
position: relative;
+
+ overflow: hidden;
+ display: grid;
+ grid-template-rows: auto 1fr;
+ flex: 1;
+
background-color: rgb(var(--bg-color-secondary));
+ border-bottom: 1px solid rgb(var(--border-color));
+ }
+
+ &-canvas {
+ position: relative;
}
&-sidebar {
diff --git a/packages/base-ui/src/views/components/doc-bars/index.module.less b/packages/base-ui/src/views/components/doc-bars/index.module.less
index 5b138edc15..fcc3b08d2a 100644
--- a/packages/base-ui/src/views/components/doc-bars/index.module.less
+++ b/packages/base-ui/src/views/components/doc-bars/index.module.less
@@ -85,6 +85,7 @@
color: rgb(var(--text-color));
background-color: rgb(var(--bg-color-secondary));
+ border-bottom: 1px solid rgb(var(--border-color));
&-container {
display: flex;
@@ -95,8 +96,6 @@
box-sizing: border-box;
width: 100%;
height: 100%;
-
- border-bottom: 1px solid rgb(var(--border-color));
}
&-group {
diff --git a/packages/base-ui/src/views/components/sidebar/index.module.less b/packages/base-ui/src/views/components/sidebar/index.module.less
index d850b55010..8b0ba82045 100644
--- a/packages/base-ui/src/views/components/sidebar/index.module.less
+++ b/packages/base-ui/src/views/components/sidebar/index.module.less
@@ -13,7 +13,6 @@
&&-open {
transform: translateX(0);
width: 380px;
- padding: 0 var(--margin-xs);
}
&-container {
@@ -28,8 +27,8 @@
margin: auto;
background-color: rgb(var(--bg-color-secondary));
- border: 1px solid rgb(var(--border-color));
- border-radius: var(--border-radius-lg);
+ border-bottom: 1px solid rgb(var(--border-color));
+ border-left: 1px solid rgb(var(--border-color));
}
&-header {
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index 65548bbea4..3a75be7081 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -1,13 +1,14 @@
import { MemoryCursor } from '../../common/memory-cursor';
-import { getDocsUpdateBody, Nullable } from '../../shared';
+import type { Nullable } from '../../shared';
+import { getDocsUpdateBody } from '../../shared';
import { UpdateDocsAttributeType } from '../../shared/command-enum';
import { Tools } from '../../shared/tools';
-import { IDocumentBody, IDocumentData, IDocumentRenderConfig } from '../../types/interfaces/i-document-data';
-import { IPaddingData } from '../../types/interfaces/i-style-data';
+import type { IDocumentBody, IDocumentData, IDocumentRenderConfig } from '../../types/interfaces/i-document-data';
+import { type IPaddingData } from '../../types/interfaces/i-style-data';
import { updateAttributeByDelete } from './apply-utils/delete-apply';
import { updateAttributeByInsert } from './apply-utils/insert-apply';
import { updateAttribute } from './apply-utils/update-apply';
-import { DocMutationParams } from './mutation-types';
+import { type DocMutationParams } from './mutation-types';
export const DEFAULT_DOC = {
id: 'default_doc',
@@ -117,6 +118,7 @@ class DocumentDataModelSimple {
if (!documentStyle.pageSize) {
width = width ?? Infinity;
height = height ?? Infinity;
+
documentStyle.pageSize = {
width,
height,
diff --git a/packages/core/src/docs/data-model/mutation-types.ts b/packages/core/src/docs/data-model/mutation-types.ts
index ef1dce0b6f..712b900b63 100644
--- a/packages/core/src/docs/data-model/mutation-types.ts
+++ b/packages/core/src/docs/data-model/mutation-types.ts
@@ -1,5 +1,5 @@
-import { UpdateDocsAttributeType } from '../../shared/command-enum';
-import { IDocumentBody } from '../../types/interfaces/i-document-data';
+import type { UpdateDocsAttributeType } from '../../shared/command-enum';
+import type { IDocumentBody } from '../../types/interfaces/i-document-data';
/**
* Retain mutation is used to move the cursor or to update properties of the text in the given range.
@@ -7,9 +7,9 @@ import { IDocumentBody } from '../../types/interfaces/i-document-data';
export interface IRetainMutationParams {
t: 'r';
len: number;
- segmentId?: string;
body?: IDocumentBody;
coverType?: UpdateDocsAttributeType;
+ segmentId?: string;
}
/**
diff --git a/packages/core/src/services/context/context.ts b/packages/core/src/services/context/context.ts
index 4dc59d670f..4ceb6ec289 100644
--- a/packages/core/src/services/context/context.ts
+++ b/packages/core/src/services/context/context.ts
@@ -4,3 +4,4 @@ export const FOCUSING_SLIDE = 'FOCUSING_SLIDE';
export const FOCUSING_EDITOR_BUT_HIDDEN = 'FOCUSING_EDITOR_BUT_HIDDEN';
export const FOCUSING_EDITOR = 'FOCUSING_EDITOR';
export const FOCUSING_EDITOR_INPUT_FORMULA = 'FOCUSING_EDITOR_INPUT_FORMULA';
+export const FOCUSING_FORMULA_EDITOR = 'FOCUSING_FORMULA_EDITOR';
diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.ts
index 7199555e07..7c6859cbaa 100644
--- a/packages/core/src/services/undoredo/undoredo.service.ts
+++ b/packages/core/src/services/undoredo/undoredo.service.ts
@@ -1,10 +1,13 @@
-import { createIdentifier, IAccessor, IDisposable } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import type { IAccessor, IDisposable } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject } from 'rxjs';
import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '../../common/const';
import { Disposable, toDisposable } from '../../shared/lifecycle';
-import { CommandType, ICommand, ICommandService, IMutationInfo, sequenceExecute } from '../command/command.service';
-import { FOCUSING_EDITOR, FOCUSING_EDITOR_INPUT_FORMULA } from '../context/context';
+import type { ICommand, IMutationInfo } from '../command/command.service';
+import { CommandType, ICommandService, sequenceExecute } from '../command/command.service';
+import { FOCUSING_EDITOR, FOCUSING_FORMULA_EDITOR } from '../context/context';
import { IContextService } from '../context/context.service';
import { IUniverInstanceService } from '../instance/instance.service';
@@ -206,10 +209,10 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
private _getFocusedUniverInstanceId() {
let unitID: string = '';
- if (this._contextService.getContextValue(FOCUSING_EDITOR)) {
- unitID = DOCS_NORMAL_EDITOR_UNIT_ID_KEY;
- } else if (this._contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)) {
+ if (this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR)) {
unitID = DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
+ } else if (this._contextService.getContextValue(FOCUSING_EDITOR)) {
+ unitID = DOCS_NORMAL_EDITOR_UNIT_ID_KEY;
} else {
unitID = this._univerInstanceService.getFocusedUniverInstance()?.getUnitId() ?? '';
}
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 6bc7daeeef..73e1a98173 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -19,12 +19,14 @@ export function makeCellToSelection(cellInfo: Nullable<ISelectionCellWithCoord>)
if (!cellInfo) {
return;
}
+
const { actualRow, actualColumn, isMerged, isMergedMainCell, mergeInfo } = cellInfo;
let { startY, endY, startX, endX } = cellInfo;
let startRow = actualRow;
let startColumn = actualColumn;
let endRow = actualRow;
let endColumn = actualColumn;
+
if (isMerged && mergeInfo) {
const {
startRow: mergeStartRow,
diff --git a/packages/core/src/shared/lifecycle.ts b/packages/core/src/shared/lifecycle.ts
index 6f7f43dcfc..5db90ec525 100644
--- a/packages/core/src/shared/lifecycle.ts
+++ b/packages/core/src/shared/lifecycle.ts
@@ -1,9 +1,11 @@
-import { IDisposable } from '@wendellhu/redi';
-import { Subject, Subscription, SubscriptionLike } from 'rxjs';
+import type { IDisposable } from '@wendellhu/redi';
+import type { Subscription, SubscriptionLike } from 'rxjs';
+import { Subject } from 'rxjs';
import { isSubscription } from 'rxjs/internal/Subscription';
-import { Nullable } from '../common/type-utils';
-import { isObserver, Observer } from '../observer/observable';
+import type { Nullable } from '../common/type-utils';
+import type { Observer } from '../observer/observable';
+import { isObserver } from '../observer/observable';
export function toDisposable(observer: Nullable<Observer<any>>): IDisposable;
export function toDisposable(subscription: SubscriptionLike): IDisposable;
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index e13533792c..33f698ed8d 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -1,7 +1,7 @@
-import { ISize } from '../../services/floating-object/floating-object-interfaces';
-import { BooleanNumber, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../enum';
-import { IExtraModelData } from './i-extra-model-data';
-import { IColorStyle, IStyleBase } from './i-style-data';
+import type { ISize } from '../../services/floating-object/floating-object-interfaces';
+import type { BooleanNumber, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../enum';
+import type { IExtraModelData } from './i-extra-model-data';
+import type { IColorStyle, IStyleBase } from './i-style-data';
// 注意:所有的尺寸单位,若无特殊说明,都是指pt,1 pt = 1 / 72 in
/**
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
index 448df030f3..3569231f3b 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
@@ -4,67 +4,61 @@ import {
ReplaceContentCommand,
TextSelectionManagerService,
} from '@univerjs/base-docs';
+import type { ISequenceNode } from '@univerjs/base-formula-engine';
import {
FormulaEngineService,
generateStringWithSequence,
includeFormulaLexerToken,
- ISequenceNode,
isFormulaLexerToken,
matchToken,
normalizeSheetName,
sequenceNodeType,
} from '@univerjs/base-formula-engine';
import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import type { ISelectionWithStyle } from '@univerjs/base-sheets';
import {
convertSelectionDataToRange,
getNormalSelectionStyle,
- ISelectionWithStyle,
NORMAL_SELECTION_PLUGIN_NAME,
SelectionManagerService,
} from '@univerjs/base-sheets';
import { KeyCode, MetaKeys } from '@univerjs/base-ui';
+import type { ICommandInfo, IRange, IRangeWithCoord, ITextRun, Nullable } from '@univerjs/core';
import {
deserializeRangeWithSheet,
Direction,
Disposable,
DisposableCollection,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
FOCUSING_EDITOR_INPUT_FORMULA,
- ICommandInfo,
ICommandService,
IContextService,
- IDocumentBody,
- IRange,
- IRangeWithCoord,
isFormulaString,
- ITextRun,
IUniverInstanceService,
LifecycleStages,
LocaleService,
- Nullable,
OnLifecycle,
serializeRangeToRefString,
ThemeService,
toDisposable,
Tools,
} from '@univerjs/core';
+import type { EditorBridgeService, SelectionShape } from '@univerjs/ui-plugin-sheets';
import {
- EditorBridgeService,
ExpandSelectionCommand,
getEditorObject,
IEditorBridgeService,
ISelectionRenderService,
JumpOver,
MoveSelectionCommand,
- SelectionShape,
SetEditorResizeOperation,
SheetSkeletonManagerService,
} from '@univerjs/ui-plugin-sheets';
import { Inject } from '@wendellhu/redi';
-import {
- ISelectEditorFormulaOperationParam,
- SelectEditorFormulaOperation,
-} from '../commands/operations/editor-formula.operation';
+import type { ISelectEditorFormulaOperationParam } from '../commands/operations/editor-formula.operation';
+import { SelectEditorFormulaOperation } from '../commands/operations/editor-formula.operation';
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
import { SearchFunctionOperation } from '../commands/operations/search-function.operation';
import { META_KEY_CTRL_AND_SHIFT } from '../common/prompt';
@@ -237,7 +231,7 @@ export class PromptController extends Disposable {
return;
}
- this._highlightFormula(currentBody);
+ this._highlightFormula();
// if (this._isLockedOnSelectionInsertRefString) {
// return;
@@ -679,6 +673,16 @@ export class PromptController extends Disposable {
return documentModel?.snapshot?.body;
}
+ private _getFormulaAndCellEditorBody() {
+ const unitIds = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
+
+ return unitIds.map((unitId) => {
+ const dataModel = this._currentUniverService.getUniverDocInstance(unitId);
+
+ return dataModel?.getBody();
+ });
+ }
+
/**
* Detect whether the user's input content is a formula. If it is a formula,
* serialize the current input content into a sequenceNode;
@@ -752,12 +756,10 @@ export class PromptController extends Disposable {
}
/**
- *
- * @param body the body object of the current input box
- * @returns
+ * Highlight cell editor and formula bar editor.
*/
- private _highlightFormula(body: Nullable<IDocumentBody>) {
- if (body == null || this._getContextState() === false) {
+ private _highlightFormula() {
+ if (this._getContextState() === false) {
return;
}
@@ -768,20 +770,21 @@ export class PromptController extends Disposable {
// );
const sequenceNodes = this._formulaInputService.getSequenceNodes();
+ const bodyList = this._getFormulaAndCellEditorBody().filter((b) => !!b);
this._selectionManagerService.clear();
if (sequenceNodes == null || sequenceNodes.length === 0) {
- body.textRuns = [];
+ bodyList.forEach((body) => (body!.textRuns = []));
} else {
// this._lastSequenceNodes = sequenceNodes;
const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
- body.textRuns = textRuns;
+ bodyList.forEach((body) => (body!.textRuns = textRuns));
this._refreshSelectionForReference(refSelections);
}
- this._refreshEditorObject();
+ this._refreshFormulaAndCellEditor();
}
/**
@@ -1271,14 +1274,22 @@ export class PromptController extends Disposable {
controlSelection.update(toRange);
}
- private _refreshEditorObject() {
- const editorObject = this._getEditorObject();
+ private _refreshFormulaAndCellEditor() {
+ const unitIds = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
- const documentComponent = editorObject?.document;
+ for (const unitId of unitIds) {
+ const editorObject = getEditorObject(unitId, this._renderManagerService);
- documentComponent?.getSkeleton()?.calculate();
+ const documentComponent = editorObject?.document;
- documentComponent?.makeDirty();
+ if (documentComponent == null) {
+ continue;
+ }
+
+ documentComponent.getSkeleton()?.calculate();
+
+ documentComponent.makeDirty();
+ }
}
private _cursorStateListener() {
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx
index 68ad6a7eec..7d45273cc8 100644
--- a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx
@@ -1,8 +1,8 @@
import type { IFunctionInfo, IFunctionParam } from '@univerjs/base-formula-engine';
-import { LocaleService } from '@univerjs/core';
+import { FOCUSING_FORMULA_EDITOR, IContextService, LocaleService } from '@univerjs/core';
import { Popup } from '@univerjs/design';
import { CloseSingle, DetailsSingle, MoreSingle } from '@univerjs/icons';
-import { ICellEditorManagerService } from '@univerjs/ui-plugin-sheets';
+import { ICellEditorManagerService, IFormulaEditorManagerService } from '@univerjs/ui-plugin-sheets';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useState } from 'react';
@@ -21,22 +21,31 @@ export function HelpFunction() {
const promptService = useDependency(IFormulaPromptService);
const cellEditorManagerService = useDependency(ICellEditorManagerService);
const localeService = useDependency(LocaleService);
+ const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
+ const contextService = useDependency(IContextService);
const required = localeService.t('formula.prompt.required');
const optional = localeService.t('formula.prompt.optional');
useEffect(() => {
const subscription = promptService.help$.subscribe((params: IHelpFunctionOperationParams) => {
- const rect = cellEditorManagerService.getRect();
- if (!rect) return;
- const selection = cellEditorManagerService.getState();
- if (!selection) return;
-
const { visible, paramIndex, functionInfo } = params;
if (!visible) {
setVisible(visible);
return;
}
+ const isFocusFormulaEditor = contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
+
+ const position = isFocusFormulaEditor
+ ? formulaEditorManagerService.getPosition()
+ : cellEditorManagerService.getRect();
+
+ if (position == null) {
+ return;
+ }
+
+ const { left, top, height } = position;
+
const localeInfo: IFunctionInfo = {
functionName: functionInfo.functionName,
functionType: functionInfo.functionType,
@@ -50,12 +59,11 @@ export function HelpFunction() {
repeat: item.repeat,
})),
};
- const { left, top, height } = rect;
- const { startX = 0, startY = 0 } = selection;
+
setOffset([left, top + height]);
setParamIndex(paramIndex);
setFunctionInfo(localeInfo);
- setDecoratorPosition({ left: startX, top: startY });
+ setDecoratorPosition({ left, top });
setVisible(visible);
});
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less
index 7a335c8164..0e740038f9 100644
--- a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less
@@ -98,7 +98,8 @@
.formula-help-decorator {
cursor: pointer;
- position: absolute;
+ position: fixed;
+ z-index: 10;
display: flex;
align-items: center;
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx b/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx
index 6f2c4a4780..336c72dd5f 100644
--- a/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx
@@ -1,6 +1,6 @@
-import { Direction } from '@univerjs/core';
+import { Direction, FOCUSING_FORMULA_EDITOR, IContextService } from '@univerjs/core';
import { Popup } from '@univerjs/design';
-import { ICellEditorManagerService } from '@univerjs/ui-plugin-sheets';
+import { ICellEditorManagerService, IFormulaEditorManagerService } from '@univerjs/ui-plugin-sheets';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useState } from 'react';
@@ -17,22 +17,31 @@ export function SearchFunction() {
const [searchText, setSearchText] = useState<string>('');
const promptService = useDependency(IFormulaPromptService);
const cellEditorManagerService = useDependency(ICellEditorManagerService);
+ const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
+ const contextService = useDependency(IContextService);
useEffect(() => {
// TODO@Dushusir: How to get updated values in subscribe callback better
let updatedSearchList: ISearchItem[] = [];
let updatedActive = 0;
const subscribeSearch = promptService.search$.subscribe((params: ISearchFunctionOperationParams) => {
- const rect = cellEditorManagerService.getRect();
- if (!rect) return;
-
const { visible, searchText, searchList } = params;
if (!visible) {
setVisible(visible);
return;
}
- const { left, top, height } = rect;
+ const isFocusFormulaEditor = contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
+
+ const position = isFocusFormulaEditor
+ ? formulaEditorManagerService.getPosition()
+ : cellEditorManagerService.getRect();
+
+ if (position == null) {
+ return;
+ }
+
+ const { left, top, height } = position;
setSearchText(searchText);
setSearchList(searchList);
diff --git a/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts b/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts
index af8e32d8a8..4d0b10334a 100644
--- a/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts
+++ b/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts
@@ -1,5 +1,5 @@
-import { Documents, Engine, IRenderManagerService, Scene } from '@univerjs/base-render';
-import { Nullable } from '@univerjs/core';
+import type { Documents, Engine, IRenderManagerService, Scene } from '@univerjs/base-render';
+import type { Nullable } from '@univerjs/core';
export interface IDocObjectParam {
document: Documents;
@@ -21,7 +21,7 @@ export function getEditorObject(
return;
}
- const { components, mainComponent, scene, engine } = currentRender;
+ const { mainComponent, scene, engine } = currentRender;
const document = mainComponent as Documents;
diff --git a/packages/ui-plugin-sheets/src/commands/commands/inline-format.command.ts b/packages/ui-plugin-sheets/src/commands/commands/inline-format.command.ts
index c065968566..161e6309dc 100644
--- a/packages/ui-plugin-sheets/src/commands/commands/inline-format.command.ts
+++ b/packages/ui-plugin-sheets/src/commands/commands/inline-format.command.ts
@@ -16,7 +16,8 @@ import {
SetTextColorCommand,
SetUnderlineCommand,
} from '@univerjs/base-sheets';
-import { CommandType, FOCUSING_EDITOR, ICommand, ICommandService, IContextService } from '@univerjs/core';
+import type { ICommand } from '@univerjs/core';
+import { CommandType, FOCUSING_EDITOR, ICommandService, IContextService } from '@univerjs/core';
/**
* It is used to set the bold style of selections or one cell, need to distinguish between
diff --git a/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts b/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts
index 43218c822f..f4b459da34 100644
--- a/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts
+++ b/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts
@@ -1,8 +1,10 @@
// This file provide operations to change selection of sheets.
-import { CommandType, IOperation } from '@univerjs/core';
+import type { IOperation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
-import { IEditorBridgeService, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+import { IEditorBridgeService } from '../../services/editor-bridge.service';
export const SetCellEditVisibleOperation: IOperation<IEditorBridgeServiceVisibleParam> = {
id: 'sheet.operation.set-cell-edit-visible',
diff --git a/packages/ui-plugin-sheets/src/commands/operations/set-editor-resize.operation.ts b/packages/ui-plugin-sheets/src/commands/operations/set-editor-resize.operation.ts
index b2a02d3238..573c96ad73 100644
--- a/packages/ui-plugin-sheets/src/commands/operations/set-editor-resize.operation.ts
+++ b/packages/ui-plugin-sheets/src/commands/operations/set-editor-resize.operation.ts
@@ -1,6 +1,7 @@
// This file provide operations to change selection of sheets.
-import { CommandType, IOperation } from '@univerjs/core';
+import type { IOperation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
export const SetEditorResizeOperation: IOperation = {
id: 'sheet.operation.set-editor-resize',
diff --git a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
index 8ab6c0de53..afb752cfce 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
@@ -64,15 +64,15 @@ export class EditorBridgeController extends Disposable {
return;
}
- const currentSkeletonManager = this._sheetSkeletonManagerService.getCurrent();
+ const currentSkeleton = this._sheetSkeletonManagerService.getCurrent();
const sheetObject = this._getSheetObject();
- if (currentSkeletonManager == null || sheetObject == null) {
+ if (currentSkeleton == null || sheetObject == null) {
return;
}
- const { skeleton, unitId, sheetId } = currentSkeletonManager;
+ const { skeleton, unitId, sheetId } = currentSkeleton;
const { scene, engine } = sheetObject;
@@ -105,6 +105,7 @@ export class EditorBridgeController extends Disposable {
let { startX, startY, endX, endY } = actualRangeWithCoord;
const { scaleX, scaleY } = scene.getAncestorScale();
+
const scrollXY = scene.getScrollXY(this._selectionRenderService.getViewPort());
startX = skeleton.convertTransformToOffsetX(startX, scaleX, scrollXY);
@@ -114,8 +115,11 @@ export class EditorBridgeController extends Disposable {
endX = skeleton.convertTransformToOffsetX(endX, scaleX, scrollXY);
endY = skeleton.convertTransformToOffsetY(endY, scaleY, scrollXY);
+
const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+
const worksheet = workbook.getActiveSheet();
+
const location = {
workbook,
worksheet,
@@ -124,6 +128,7 @@ export class EditorBridgeController extends Disposable {
row: startRow,
col: startColumn,
};
+
const cell = this._sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.BEFORE_CELL_EDIT)(
worksheet.getCell(startRow, startColumn),
location
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
index f7b40aa5fd..abf919a3cf 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
@@ -1,18 +1,19 @@
import { MoveCursorOperation, MoveSelectionOperation } from '@univerjs/base-docs';
import { FormulaEngineService, matchToken } from '@univerjs/base-formula-engine';
-import { IMouseEvent, IPointerEvent, IRenderManagerService } from '@univerjs/base-render';
-import { SetRangeValuesCommand } from '@univerjs/base-sheets';
+import type { IMouseEvent, IPointerEvent } from '@univerjs/base-render';
+import { DeviceInputEventType, IRenderManagerService } from '@univerjs/base-render';
+import { SelectionManagerService, SetRangeValuesCommand, SetSelectionsOperation } from '@univerjs/base-sheets';
import { KeyCode } from '@univerjs/base-ui';
+import type { DocumentDataModel, ICellData, ICommandInfo, Nullable, Observer } from '@univerjs/core';
import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
Direction,
Disposable,
- DocumentDataModel,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
FOCUSING_EDITOR,
FOCUSING_EDITOR_BUT_HIDDEN,
FOCUSING_EDITOR_INPUT_FORMULA,
- ICellData,
- ICommandInfo,
+ FOCUSING_FORMULA_EDITOR,
ICommandService,
IContextService,
INTERCEPTOR_POINT,
@@ -20,20 +21,19 @@ import {
IUndoRedoService,
IUniverInstanceService,
LifecycleStages,
- Nullable,
- Observer,
OnLifecycle,
SheetInterceptorService,
Tools,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { Subscription } from 'rxjs';
+import type { Subscription } from 'rxjs';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';
import { SetCellEditVisibleArrowOperation } from '../../commands/operations/cell-edit.operation';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
-import { IEditorBridgeService, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { MOVE_SELECTION_KEYCODE_LIST } from '../shortcuts/editor.shortcut';
enum CursorChange {
@@ -64,7 +64,8 @@ export class EndEditController extends Disposable {
@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
@IUndoRedoService private _undoRedoService: IUndoRedoService,
- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService
+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
) {
super();
@@ -94,7 +95,7 @@ export class EndEditController extends Disposable {
private _initialExitInput() {
this._onInputSubscription = this._editorBridgeService.visible$.subscribe((param) => {
- const { visible, keycode } = param;
+ const { visible, keycode, eventType } = param;
if (visible === this._editorVisiblePrevious) {
return;
@@ -103,15 +104,36 @@ export class EndEditController extends Disposable {
this._editorVisiblePrevious = visible;
if (visible === true) {
- this._isCursorChange = CursorChange.StartEditor;
+ // Change `CursorChange` to changed status, when formula bar clicked.
+ this._isCursorChange =
+ eventType === DeviceInputEventType.PointerDown
+ ? CursorChange.CursorChange
+ : CursorChange.StartEditor;
return;
}
this._isCursorChange = CursorChange.InitialState;
+ const selections = this._selectionManagerService.getSelections();
+ const currentSelection = this._selectionManagerService.getCurrent();
+
+ if (currentSelection == null) {
+ return;
+ }
+
+ const { unitId: workbookId, sheetId: worksheetId, pluginName } = currentSelection;
+
this._exitInput(param);
if (keycode === KeyCode.ESC) {
+ // Reselect the current selections, when exist cell editor by press ESC.
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ workbookId,
+ worksheetId,
+ pluginName,
+ selections,
+ });
+
return;
}
@@ -205,6 +227,8 @@ export class EndEditController extends Disposable {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
this._contextService.setContextValue(FOCUSING_EDITOR, false);
this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, false);
+ this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, false);
+
this._cellEditorManagerService.setState({
show: param.visible,
});
@@ -213,6 +237,7 @@ export class EndEditController extends Disposable {
return;
}
this._undoRedoService.clearUndoRedo(editorUnitId);
+ this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
}
private _moveCursor(keycode?: KeyCode) {
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/formula-editor.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/formula-editor.controller.ts
new file mode 100644
index 0000000000..d64a797ec3
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/controllers/editor/formula-editor.controller.ts
@@ -0,0 +1,343 @@
+import type { IRichTextEditingMutationParams, ISetTextSelectionsOperationParams } from '@univerjs/base-docs';
+import {
+ CoverContentCommand,
+ DocSkeletonManagerService,
+ DocViewModelManagerService,
+ RichTextEditingMutation,
+ SetTextSelectionsOperation,
+ TextSelectionManagerService,
+ VIEWPORT_KEY,
+} from '@univerjs/base-docs';
+import type { ITextRangeWithStyle } from '@univerjs/base-render';
+import { DeviceInputEventType, IRenderManagerService, ScrollBar } from '@univerjs/base-render';
+import type { ICommandInfo, IParagraph, Nullable } from '@univerjs/core';
+import {
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ FOCUSING_EDITOR,
+ FOCUSING_EDITOR_BUT_HIDDEN,
+ FOCUSING_FORMULA_EDITOR,
+ ICommandService,
+ IContextService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ RxDisposable,
+ toDisposable,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { takeUntil } from 'rxjs';
+
+import { getEditorObject } from '../../basics/editor/get-editor-object';
+import { SetEditorResizeOperation } from '../../commands/operations/set-editor-resize.operation';
+import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
+import { IEditorBridgeService } from '../../services/editor-bridge.service';
+
+@OnLifecycle(LifecycleStages.Steady, FormulaEditorController)
+export class FormulaEditorController extends RxDisposable {
+ private _loadedMap: Set<string> = new Set();
+
+ constructor(
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @Inject(DocViewModelManagerService) private readonly _docViewModelManagerService: DocViewModelManagerService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IContextService private readonly _contextService: IContextService,
+ @IFormulaEditorManagerService private readonly _formulaEditorManagerService: IFormulaEditorManagerService,
+ @IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize() {
+ this._syncFormulaEditorContent();
+ this._commandExecutedListener();
+ this._syncEditorSize();
+ this._listenFxBtnClick();
+
+ this._renderManagerService.currentRender$.pipe(takeUntil(this.dispose$)).subscribe((unitId) => {
+ if (unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
+
+ if (!this._loadedMap.has(unitId)) {
+ this._initialMain(unitId);
+ this._loadedMap.add(unitId);
+ }
+ });
+ }
+
+ private _listenFxBtnClick() {
+ this._formulaEditorManagerService.fxBtnClick$.pipe(takeUntil(this.dispose$)).subscribe(() => {
+ const isFocusButHidden =
+ this._contextService.getContextValue(FOCUSING_EDITOR_BUT_HIDDEN) &&
+ !this._contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isFocusButHidden) {
+ this._univerInstanceService.setCurrentUniverDocInstance(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+
+ this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, true);
+
+ const formulaEditorDataModel = this._univerInstanceService.getUniverDocInstance(
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ );
+
+ const visibleState = this._editorBridgeService.isVisible();
+ if (visibleState.visible === false) {
+ this._editorBridgeService.changeVisible({
+ visible: true,
+ eventType: DeviceInputEventType.PointerDown,
+ });
+ }
+
+ const content = formulaEditorDataModel?.getBody()?.dataStream;
+
+ if (content == null) {
+ return;
+ }
+
+ let newContent = content.startsWith('=') ? content : `=${content}`;
+
+ newContent = newContent.replace(/\r\n$/, '');
+
+ const textRanges: ITextRangeWithStyle[] = [
+ {
+ startOffset: newContent.length,
+ endOffset: newContent.length,
+ collapsed: true,
+ },
+ ];
+
+ const coverContentParams = {
+ unitId: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ body: {
+ dataStream: newContent,
+ },
+ segmentId: '',
+ };
+
+ this._commandService.executeCommand(CoverContentCommand.id, coverContentParams);
+
+ this._textSelectionManagerService.replaceTextRanges(textRanges);
+ }
+ });
+ }
+
+ private _initialMain(unitId: string) {
+ const formulaEditorDocObject = this._renderManagerService.getRenderById(unitId);
+ if (formulaEditorDocObject == null) {
+ return;
+ }
+
+ const { mainComponent: documentComponent } = formulaEditorDocObject;
+
+ if (documentComponent == null) {
+ return;
+ }
+
+ this.disposeWithMe(
+ toDisposable(
+ documentComponent.onPointerDownObserver.add(() => {
+ this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, true);
+ this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+
+ const visibleState = this._editorBridgeService.isVisible();
+ if (visibleState.visible === false) {
+ this._editorBridgeService.changeVisible({
+ visible: true,
+ eventType: DeviceInputEventType.PointerDown,
+ });
+ }
+ })
+ )
+ );
+ }
+
+ // Listen to changes in the size of the formula editor container to set the size of the editor.
+ private _syncEditorSize() {
+ this._formulaEditorManagerService.position$.pipe(takeUntil(this.dispose$)).subscribe((position) => {
+ if (position == null) {
+ return;
+ }
+ const editorObject = getEditorObject(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, this._renderManagerService);
+ const formulaEditorDataModel = this._univerInstanceService.getUniverDocInstance(
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ );
+
+ if (editorObject == null || formulaEditorDataModel == null) {
+ return;
+ }
+
+ const { width, height } = position;
+
+ const { engine } = editorObject;
+
+ // Update page size when container resized.
+ formulaEditorDataModel.updateDocumentDataPageSize(width);
+
+ this._autoScroll();
+
+ // resize canvas
+ requestIdleCallback(() => {
+ engine.resizeBySize(width, height);
+ });
+ });
+ }
+
+ // Sync cell content to formula editor bar when sheet selection changed.
+ private _syncFormulaEditorContent() {
+ this._editorBridgeService.state$.pipe(takeUntil(this.dispose$)).subscribe((param) => {
+ if (param == null || this._editorBridgeService.isForceKeepVisible()) {
+ return;
+ }
+
+ const body = param.documentLayoutObject.documentModel?.getBody();
+ const dataStream = body?.dataStream;
+ const paragraphs = body?.paragraphs;
+
+ if (dataStream == null || paragraphs == null) {
+ return;
+ }
+
+ this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs);
+
+ // Also need to resize document and scene after sync content.
+ this._autoScroll();
+ });
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];
+
+ const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ 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 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);
+
+ // handle weather need to show scroll bar.
+ this._autoScroll();
+ }
+ }
+
+ // Mark formula editor as non-focused, when current selection is not in formula editor.
+ if (command.id === SetTextSelectionsOperation.id) {
+ const { unitId } = command.params as ISetTextSelectionsOperationParams;
+ if (unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, false);
+ this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ }
+ }
+ })
+ );
+ }
+
+ private _syncContentAndRender(unitId: string, dataStream: string, paragraphs: IParagraph[]) {
+ const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
+
+ const docsSkeletonObject = this._docSkeletonManagerService.getSkeletonByUnitId(unitId);
+ const docDataModel = this._univerInstanceService.getUniverDocInstance(unitId);
+ const docViewModel = this._docViewModelManagerService.getViewModel(unitId);
+
+ if (docDataModel == null || docViewModel == null || docsSkeletonObject == null) {
+ return;
+ }
+
+ docDataModel.getBody()!.dataStream = dataStream;
+ docDataModel.getBody()!.paragraphs = paragraphs;
+
+ // Need to empty textRuns(previous formula highlight) every time when sync content(change selection or edit cell or edit formula bar).
+ if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ docDataModel.getBody()!.textRuns = [];
+ }
+
+ docViewModel.reset(docDataModel);
+
+ const { skeleton } = docsSkeletonObject;
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ skeleton.calculate();
+
+ if (INCLUDE_LIST.includes(unitId)) {
+ currentRender.mainComponent?.makeDirty();
+ }
+ }
+
+ private _autoScroll() {
+ const skeleton = this._docSkeletonManagerService.getSkeletonByUnitId(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)
+ ?.skeleton;
+ const position = this._formulaEditorManagerService.getPosition();
+
+ const editorObject = this._renderManagerService.getRenderById(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+
+ const formulaEditorDataModel = this._univerInstanceService.getUniverDocInstance(
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ );
+
+ if (skeleton == null || position == null || editorObject == null || formulaEditorDataModel == null) {
+ return;
+ }
+
+ const { marginTop = 0, marginBottom = 0 } = formulaEditorDataModel.getSnapshot().documentStyle;
+
+ const { scene, mainComponent } = editorObject;
+
+ let { actualHeight } = skeleton.getActualSize();
+ // page actual height also need to include page margin top and margin bottom.
+ actualHeight += marginTop + marginBottom;
+
+ const { width, height } = position;
+ const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+
+ let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;
+
+ if (actualHeight > height) {
+ if (scrollBar == null) {
+ viewportMain && new ScrollBar(viewportMain, { enableHorizontal: false });
+ } else {
+ viewportMain?.resetSizeAndScrollBar();
+ }
+ } else {
+ scrollBar = null;
+ viewportMain?.scrollTo({ x: 0, y: 0 });
+ viewportMain?.getScrollBar()?.dispose();
+ }
+
+ scene.transformByState({
+ width,
+ height: actualHeight,
+ });
+
+ mainComponent?.resize(width, actualHeight);
+ }
+}
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts
index 88c0a3fcbe..b9539d0e0f 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts
@@ -1,15 +1,19 @@
import { getDocObject } from '@univerjs/base-docs';
import { IRenderManagerService } from '@univerjs/base-render';
+import type { Nullable } from '@univerjs/core';
import {
+ DEFAULT_EMPTY_DOCUMENT_VALUE,
Disposable,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ HorizontalAlign,
IUniverInstanceService,
LifecycleStages,
- Nullable,
OnLifecycle,
+ VerticalAlign,
+ WrapStrategy,
} from '@univerjs/core';
-import { Subscription } from 'rxjs';
+import type { Subscription } from 'rxjs';
@OnLifecycle(LifecycleStages.Rendered, InitializeEditorController)
export class InitializeEditorController extends Disposable {
@@ -41,10 +45,38 @@ export class InitializeEditorController extends Disposable {
});
// create univer doc formula bar editor instance
- this._currentUniverService.createDoc({
+ const INITIAL_SNAPSHOT = {
id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- documentStyle: {},
- });
+ body: {
+ dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,
+ textRuns: [],
+ paragraphs: [
+ {
+ startIndex: 0,
+ },
+ ],
+ },
+ documentStyle: {
+ pageSize: {
+ width: Infinity,
+ height: Infinity,
+ },
+ marginTop: 5,
+ marginBottom: 5,
+ marginRight: 0,
+ marginLeft: 0,
+ paragraphLineGapDefault: 0,
+ renderConfig: {
+ horizontalAlign: HorizontalAlign.UNSPECIFIED,
+ verticalAlign: VerticalAlign.UNSPECIFIED,
+ centerAngle: 0,
+ vertexAngle: 0,
+ wrapStrategy: WrapStrategy.WRAP,
+ },
+ },
+ };
+
+ this._currentUniverService.createDoc(INITIAL_SNAPSHOT);
}
private _commandExecutedListener() {}
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
index 63254d65cf..aebe9e7f95 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
@@ -1,25 +1,22 @@
+import type { IRichTextEditingMutationParams } from '@univerjs/base-docs';
import {
DOCS_COMPONENT_MAIN_LAYER_INDEX,
DocSkeletonManagerService,
DocViewModelManagerService,
- IRichTextEditingMutationParams,
- NORMAL_TEXT_SELECTION_PLUGIN_NAME,
RichTextEditingMutation,
TextSelectionManagerService,
VIEWPORT_KEY,
} from '@univerjs/base-docs';
+import type { DocumentSkeleton, IDocumentLayoutObject, IEditorInputConfig, Scene } from '@univerjs/base-render';
import {
DeviceInputEventType,
- DocumentSkeleton,
- IDocumentLayoutObject,
- IEditorInputConfig,
IRenderManagerService,
ITextSelectionRenderManager,
Rect,
- Scene,
ScrollBar,
} from '@univerjs/base-render';
import { KeyCode } from '@univerjs/base-ui';
+import type { ICommandInfo, IDocumentBody, IDocumentData, IPosition, ITextRotation, Nullable } from '@univerjs/core';
import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
Disposable,
@@ -27,25 +24,20 @@ import {
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
FOCUSING_EDITOR,
FOCUSING_EDITOR_BUT_HIDDEN,
+ FOCUSING_FORMULA_EDITOR,
HorizontalAlign,
- ICommandInfo,
ICommandService,
IContextService,
- IDocumentBody,
- IDocumentData,
- IPosition,
- ITextRotation,
IUniverInstanceService,
LifecycleStages,
LocaleService,
- Nullable,
OnLifecycle,
Tools,
VerticalAlign,
WrapStrategy,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { Subscription } from 'rxjs';
+import type { Subscription } from 'rxjs';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
@@ -126,7 +118,7 @@ export class StartEditController extends Disposable {
return;
}
- const { document: documentComponent, scene } = editorObject;
+ const { document: documentComponent } = editorObject;
const { startX, endX } = position;
@@ -154,15 +146,8 @@ export class StartEditController extends Disposable {
documentComponent.changeSkeleton(documentSkeleton);
- this._textSelectionManagerService.setCurrentSelectionNotRefresh({
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
- unitId: docParam.unitId,
- });
-
this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, true);
- this._textSelectionRenderManager.changeRuntime(documentSkeleton, scene);
-
this._textSelectionManagerService.replaceTextRanges([
{
startOffset: 0,
@@ -184,7 +169,12 @@ export class StartEditController extends Disposable {
scaleY: number = 1
) {
const { startX, startY, endX, endY } = actualRangeWithCoord;
- const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const documentDataModel = documentLayoutObject.documentModel;
+
+ if (documentDataModel == null) {
+ return;
+ }
+
const { actualWidth, actualHeight } = this._predictingSize(
actualRangeWithCoord,
canvasOffset,
@@ -249,7 +239,7 @@ export class StartEditController extends Disposable {
const { textRotation, wrapStrategy } = documentLayoutObject;
- const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const documentDataModel = documentLayoutObject.documentModel;
const { a: angle } = textRotation as ITextRotation;
@@ -263,7 +253,8 @@ export class StartEditController extends Disposable {
actualHeight: actualHeight * scaleY,
};
}
- documentDataModel.updateDocumentDataPageSize(clientWidth - startX - canvasOffset.left);
+
+ documentDataModel?.updateDocumentDataPageSize(clientWidth - startX - canvasOffset.left);
documentSkeleton.calculate();
const size = documentSkeleton.getActualSize();
@@ -275,9 +266,9 @@ export class StartEditController extends Disposable {
}
// 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);
+ documentDataModel?.updateDocumentDataPageSize(editorWidth / scaleX);
- documentDataModel.updateDocumentRenderConfig({
+ documentDataModel?.updateDocumentRenderConfig({
horizontalAlign: HorizontalAlign.UNSPECIFIED,
});
@@ -328,6 +319,7 @@ export class StartEditController extends Disposable {
if (physicHeight > clientHeight) {
physicHeight = clientHeight;
+
if (scrollBar == null) {
viewportMain && new ScrollBar(viewportMain, { enableHorizontal: false });
} else {
@@ -358,6 +350,7 @@ export class StartEditController extends Disposable {
engine.resizeBySize(editorWidth, physicHeight);
});
+ // Update cell editor container position and size.
this._cellEditorManagerService.setState({
startX,
startY,
@@ -424,7 +417,7 @@ export class StartEditController extends Disposable {
return;
}
- const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = state;
+ const { position, documentLayoutObject, canvasOffset, scaleX, scaleY, editorUnitId } = state;
const editorObject = this._getEditorObject();
@@ -438,7 +431,7 @@ export class StartEditController extends Disposable {
const { documentModel: documentDataModel } = documentLayoutObject;
- const docParam = this._docSkeletonManagerService.getCurrent();
+ const docParam = this._docSkeletonManagerService.getSkeletonByUnitId(editorUnitId);
if (docParam == null || documentDataModel == null) {
return;
@@ -471,7 +464,7 @@ export class StartEditController extends Disposable {
collapsed: true,
},
]);
- } else {
+ } else if (eventType === DeviceInputEventType.Dblclick) {
// TODO: @JOCS, Get the position close to the cursor after clicking on the cell.
const cursor = documentDataModel.getBody()!.dataStream.length - 2 || 0;
@@ -532,16 +525,19 @@ export class StartEditController extends Disposable {
}
private _initialKeyboardListener() {
- this._textSelectionRenderManager.onInputBefore$.subscribe(this._showEditorByKeyboard.bind(this));
+ this._textSelectionRenderManager.onInputBefore$.subscribe((config) => {
+ const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
+
+ if (!isFocusFormulaEditor) {
+ this._showEditorByKeyboard(config);
+ }
+ });
}
private _showEditorByKeyboard(config: Nullable<IEditorInputConfig>) {
if (config == null) {
return;
}
- // const { event, content, activeRange, selectionList } = config;
-
- // this._editorBridgeService.show(DeviceInputEventType.Keyboard);
const event = config.event as KeyboardEvent;
@@ -552,8 +548,8 @@ export class StartEditController extends Disposable {
});
}
+ // Listen to document edits to refresh the size of the editor.
private _commandExecutedListener() {
- // Listen to document edits to refresh the size of the editor.
const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];
const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
@@ -563,26 +559,19 @@ export class StartEditController extends Disposable {
if (updateCommandList.includes(command.id)) {
const params = command.params as IRichTextEditingMutationParams;
const { unitId: commandUnitId } = params;
+ const unitId = this._editorBridgeService.getCurrentEditorId();
- const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
-
- if (docsSkeletonObject == null) {
+ if (unitId == null) {
return;
}
- const { unitId, skeleton } = docsSkeletonObject;
+ const skeleton = this._docSkeletonManagerService.getSkeletonByUnitId(unitId)?.skeleton;
- if (commandUnitId !== unitId) {
+ if (skeleton == null) {
return;
}
- const currentRender = this._renderManagerService.getRenderById(unitId);
-
- if (currentRender == null) {
- return;
- }
-
- if (!excludeUnitList.includes(unitId)) {
+ if (!excludeUnitList.includes(commandUnitId)) {
return;
}
@@ -594,10 +583,6 @@ export class StartEditController extends Disposable {
const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;
this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);
-
- // const editorObject = this._getEditorObject();
-
- // editorObject?.document.makeDirty();
}
})
);
diff --git a/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.ts b/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.ts
index c9128db621..eeb80c8004 100644
--- a/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.ts
+++ b/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.ts
@@ -1,13 +1,19 @@
import { BreakLineCommand, DeleteLeftCommand } from '@univerjs/base-docs';
import { DeviceInputEventType } from '@univerjs/base-render';
-import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';
+import type { IShortcutItem } from '@univerjs/base-ui';
+import { KeyCode, MetaKeys } from '@univerjs/base-ui';
import { FOCUSING_EDITOR } from '@univerjs/core';
import {
SetCellEditVisibleArrowOperation,
SetCellEditVisibleOperation,
} from '../../commands/operations/cell-edit.operation';
-import { whenEditorActivatedIsVisible, whenEditorDidNotInputFormulaActivated, whenEditorFocusIsHidden } from './utils';
+import {
+ whenEditorActivatedIsVisible,
+ whenEditorDidNotInputFormulaActivated,
+ whenEditorFocusIsHidden,
+ whenFormulaEditorFocused,
+} from './utils';
export const ARROW_SELECTION_KEYCODE_LIST = [
KeyCode.ARROW_DOWN,
@@ -91,13 +97,15 @@ export const EditorBreakLineShortcut: IShortcutItem = {
export const EditorDeleteLeftShortcut: IShortcutItem = {
id: DeleteLeftCommand.id,
- preconditions: (contextService) => whenEditorActivatedIsVisible(contextService),
+ preconditions: (contextService) =>
+ whenEditorActivatedIsVisible(contextService) || whenFormulaEditorFocused(contextService),
binding: KeyCode.BACKSPACE,
};
export const EditorDeleteLeftShortcutInActive: IShortcutItem = {
id: SetCellEditVisibleOperation.id,
- preconditions: (contextService) => whenEditorFocusIsHidden(contextService),
+ preconditions: (contextService) =>
+ whenEditorFocusIsHidden(contextService) && !whenFormulaEditorFocused(contextService),
binding: KeyCode.BACKSPACE,
staticParameters: {
visible: true,
diff --git a/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts b/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts
index a08c49ab52..e7c0da2e2e 100644
--- a/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts
+++ b/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts
@@ -1,9 +1,10 @@
+import type { IContextService } from '@univerjs/core';
import {
FOCUSING_EDITOR,
FOCUSING_EDITOR_BUT_HIDDEN,
FOCUSING_EDITOR_INPUT_FORMULA,
+ FOCUSING_FORMULA_EDITOR,
FOCUSING_SHEET,
- IContextService,
} from '@univerjs/core';
export function whenEditorNotActivated(contextService: IContextService) {
@@ -22,6 +23,10 @@ export function whenEditorActivatedIsVisible(contextService: IContextService) {
);
}
+export function whenFormulaEditorFocused(contextService: IContextService) {
+ return contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
+}
+
export function whenEditorInputFormulaActivated(contextService: IContextService) {
return (
contextService.getContextValue(FOCUSING_EDITOR) && contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)
diff --git a/packages/ui-plugin-sheets/src/index.ts b/packages/ui-plugin-sheets/src/index.ts
index f9c1b57932..9a459e4c54 100644
--- a/packages/ui-plugin-sheets/src/index.ts
+++ b/packages/ui-plugin-sheets/src/index.ts
@@ -18,6 +18,7 @@ export { getRepeatRange } from './services/auto-fill/tools';
export type { IAutoFillHook } from './services/auto-fill/type';
export { APPLY_TYPE, DATA_TYPE } from './services/auto-fill/type';
export { CellEditorManagerService, ICellEditorManagerService } from './services/editor/cell-editor-manager.service';
+export { IFormulaEditorManagerService } from './services/editor/formula-editor-manager.service';
export {
EditorBridgeService,
IEditorBridgeService,
diff --git a/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
index 6d5b3d23db..20a2609ac0 100644
--- a/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
+++ b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
@@ -1,8 +1,11 @@
-import { DeviceInputEventType, IDocumentLayoutObject } from '@univerjs/base-render';
-import { KeyCode } from '@univerjs/base-ui';
-import { IPosition, Nullable } from '@univerjs/core';
-import { createIdentifier, IDisposable } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import type { IDocumentLayoutObject } from '@univerjs/base-render';
+import { DeviceInputEventType } from '@univerjs/base-render';
+import type { KeyCode } from '@univerjs/base-ui';
+import type { IPosition, Nullable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject } from 'rxjs';
export interface IEditorBridgeServiceVisibleParam {
visible: boolean;
diff --git a/packages/ui-plugin-sheets/src/services/editor/cell-editor-manager.service.ts b/packages/ui-plugin-sheets/src/services/editor/cell-editor-manager.service.ts
index 9fab014f6f..cfb14f48ab 100644
--- a/packages/ui-plugin-sheets/src/services/editor/cell-editor-manager.service.ts
+++ b/packages/ui-plugin-sheets/src/services/editor/cell-editor-manager.service.ts
@@ -1,6 +1,8 @@
-import { IPosition, Nullable } from '@univerjs/core';
-import { createIdentifier, IDisposable } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import type { IPosition, Nullable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject } from 'rxjs';
export interface ICellEditorManagerParam extends Partial<IPosition> {
show: boolean;
diff --git a/packages/ui-plugin-sheets/src/services/editor/formula-editor-manager.service.ts b/packages/ui-plugin-sheets/src/services/editor/formula-editor-manager.service.ts
new file mode 100644
index 0000000000..a61c6fbec1
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/services/editor/formula-editor-manager.service.ts
@@ -0,0 +1,64 @@
+import type { Nullable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject } from 'rxjs';
+
+export interface IFormulaEditorManagerService {
+ position$: Observable<Nullable<DOMRect>>;
+ focus$: Observable<boolean>;
+ fxBtnClick$: Observable<boolean>;
+ dispose(): void;
+ setPosition(param: DOMRect): void;
+ getPosition(): Readonly<Nullable<DOMRect>>;
+ setFocus(param: boolean): void;
+}
+
+export class FormulaEditorManagerService implements IDisposable {
+ private _position: Nullable<DOMRect> = null;
+
+ private readonly _position$ = new BehaviorSubject<Nullable<DOMRect>>(null);
+ readonly position$ = this._position$.asObservable();
+
+ private _focus: boolean = false;
+
+ private readonly _focus$ = new BehaviorSubject<boolean>(this._focus);
+ readonly focus$ = this._focus$.asObservable();
+
+ private readonly _fxBtnClick$ = new BehaviorSubject<boolean>(false);
+ readonly fxBtnClick$ = this._fxBtnClick$.asObservable();
+
+ dispose(): void {
+ this._position$.complete();
+ this._focus$.complete();
+ this._position = null;
+ this._focus = false;
+ }
+
+ setPosition(param: DOMRect) {
+ this._position = param;
+
+ this._refresh(param);
+ }
+
+ getPosition(): Readonly<Nullable<DOMRect>> {
+ return this._position;
+ }
+
+ setFocus(param: boolean = false) {
+ this._focus = param;
+ this._focus$.next(param);
+ }
+
+ handleFxBtnClick(params: boolean) {
+ this._fxBtnClick$.next(params);
+ }
+
+ private _refresh(param: DOMRect): void {
+ this._position$.next(param);
+ }
+}
+
+export const IFormulaEditorManagerService = createIdentifier<FormulaEditorManagerService>(
+ 'univer.sheet-formula-editor-manager.service'
+);
diff --git a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
index 89d03d98fd..b8bb51de28 100644
--- a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
@@ -1,5 +1,6 @@
import { IUniverInstanceService, LocaleService, Plugin, PluginType } from '@univerjs/core';
-import { Dependency, Inject, Injector } from '@wendellhu/redi';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
import { filter } from 'rxjs/operators';
import { SHEET_UI_PLUGIN_NAME } from './basics';
@@ -9,6 +10,7 @@ import { SheetClipboardController } from './controllers/clipboard/clipboard.cont
import { SheetContextMenuController } from './controllers/contextmenu/contextmenu.controller';
import { EditingController } from './controllers/editor/editing.controller';
import { EndEditController } from './controllers/editor/end-edit.controller';
+import { FormulaEditorController } from './controllers/editor/formula-editor.controller';
import { InitializeEditorController } from './controllers/editor/initialize-editor.controller';
import { StartEditController } from './controllers/editor/start-edit.controller';
import { EditorBridgeController } from './controllers/editor-bridge.controller';
@@ -30,6 +32,10 @@ import { enUS } from './locale';
import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
import { ISheetClipboardService, SheetClipboardService } from './services/clipboard/clipboard.service';
import { CellEditorManagerService, ICellEditorManagerService } from './services/editor/cell-editor-manager.service';
+import {
+ FormulaEditorManagerService,
+ IFormulaEditorManagerService,
+} from './services/editor/formula-editor-manager.service';
import { EditorBridgeService, IEditorBridgeService } from './services/editor-bridge.service';
import { FormatPainterService, IFormatPainterService } from './services/format-painter/format-painter.service';
import { ScrollManagerService } from './services/scroll-manager.service';
@@ -67,6 +73,7 @@ export class SheetUIPlugin extends Plugin {
[ISheetBarService, { useClass: SheetBarService }],
[IFormatPainterService, { useClass: FormatPainterService }],
[ICellEditorManagerService, { useClass: CellEditorManagerService }],
+ [IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }],
[IAutoFillService, { useClass: AutoFillService }],
[ScrollManagerService],
[SheetSkeletonManagerService],
@@ -83,6 +90,7 @@ export class SheetUIPlugin extends Plugin {
[EditingController],
[EditorBridgeController],
[EndEditController],
+ [FormulaEditorController],
[FormatPainterController],
[FreezeController],
[HeaderMenuController],
diff --git a/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx b/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx
index 35c87005f8..b40f42f347 100644
--- a/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx
+++ b/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable no-magic-numbers */
import { IRenderManagerService } from '@univerjs/base-render';
import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
import { useDependency } from '@wendellhu/redi/react-bindings';
@@ -39,11 +40,13 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
if (editor == null) {
return;
}
+
const renderSubscription = renderManagerService.currentRender$
.pipe(
switchMap(() => {
const engine = renderManagerService.getRenderById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.engine;
engine?.setContainer(editor);
+
return cellEditorManagerService.state$;
})
)
diff --git a/packages/ui-plugin-sheets/src/views/formula-bar/FormulaBar.tsx b/packages/ui-plugin-sheets/src/views/formula-bar/FormulaBar.tsx
index f8201ac6da..1e85869ee9 100644
--- a/packages/ui-plugin-sheets/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/ui-plugin-sheets/src/views/formula-bar/FormulaBar.tsx
@@ -1,69 +1,135 @@
-import { ComponentManager } from '@univerjs/base-ui';
-import type { Nullable } from '@univerjs/core';
-import { CheckMarkSingle, CloseSingle } from '@univerjs/icons';
+import { DeviceInputEventType, IRenderManagerService } from '@univerjs/base-render';
+import { KeyCode } from '@univerjs/base-ui';
+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
+import { CheckMarkSingle, CloseSingle, DownTriangleSingle, FxSingle, UpTriangleSingle } from '@univerjs/icons';
import { useDependency } from '@wendellhu/redi/react-bindings';
-import React, { useState } from 'react';
+import clsx from 'clsx';
+import React, { useEffect, useRef, useState } from 'react';
+import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
+import { IEditorBridgeService } from '../../services/editor-bridge.service';
import styles from './index.module.less';
-interface FormulaState {
- namedRanges: any[];
- spanClass: string;
- formulaContent: string;
- fx: Nullable<Fx>;
+enum ArrowDirection {
+ Down,
+ Up,
}
-export interface Fx {
- icon: string;
- onClick: () => void;
+interface IFormulaState {
+ iconStyle: string;
+ arrowDirection: ArrowDirection;
}
export function FormulaBar() {
- const [state, setState] = useState<FormulaState>({
- namedRanges: [
- {
- value: '1',
- label: '1',
- },
- ],
- spanClass: styles.formulaGrey,
- formulaContent: '',
- fx: null,
- });
-
- const componentManager = useDependency(ComponentManager);
- const Icon = componentManager.get(state.fx?.icon ?? '');
-
- function printChange(e: React.KeyboardEvent<HTMLDivElement>) {
- e.stopPropagation();
- console.log(e);
+ const [iconStyle, setIconStyle] = useState<string>(styles.formulaGrey);
+ const [arrowDirection, setArrowDirection] = useState<ArrowDirection>(ArrowDirection.Down);
+
+ const editorRef = useRef<HTMLDivElement>(null);
+
+ const renderManagerService: IRenderManagerService = useDependency(IRenderManagerService);
+
+ const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
+
+ const editorBridgeService = useDependency(IEditorBridgeService);
+
+ useEffect(() => {
+ const editor = editorRef.current;
+
+ if (!editor) {
+ return;
+ }
+
+ const renderSubscription = renderManagerService.currentRender$.subscribe((param) => {
+ if (param !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
+
+ const engine = renderManagerService.getRenderById(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)?.engine;
+ engine?.setContainer(editor);
+ });
+
+ const resizeObserver = new ResizeObserver(() => {
+ const editorRect = editor.getBoundingClientRect();
+
+ formulaEditorManagerService.setPosition(editorRect);
+ });
+
+ resizeObserver.observe(editor);
+
+ editorBridgeService.visible$.subscribe((visibleInfo) => {
+ setIconStyle(visibleInfo.visible ? styles.formulaActive : styles.formulaGrey);
+ });
+
+ // Clean up on unmount
+ return () => {
+ resizeObserver.unobserve(editor);
+ renderSubscription.unsubscribe();
+ };
+ }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
+
+ function handleArrowClick() {
+ setArrowDirection(arrowDirection === ArrowDirection.Down ? ArrowDirection.Up : ArrowDirection.Down);
+ }
+
+ function handleCloseBtnClick() {
+ const visibleState = editorBridgeService.isVisible();
+ if (visibleState.visible) {
+ editorBridgeService.changeVisible({
+ visible: false,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.ESC,
+ });
+ }
+ }
+
+ function handleConfirmBtnClick() {
+ const visibleState = editorBridgeService.isVisible();
+ if (visibleState.visible) {
+ editorBridgeService.changeVisible({
+ visible: false,
+ eventType: DeviceInputEventType.PointerDown,
+ });
+ }
+ }
+
+ function handlerFxBtnClick() {
+ formulaEditorManagerService.handleFxBtnClick(true);
}
return (
- <div className={styles.formulaBox}>
- {/* <Select children={namedRanges} type={0}></Select> */}
+ <div className={styles.formulaBox} style={{ height: ArrowDirection.Down === arrowDirection ? '28px' : '82px' }}>
+ <div className={styles.nameRanges}>
+ <div className={styles.nameRangesInput} />
+ </div>
+
<div className={styles.formulaBar}>
<div className={styles.formulaIcon}>
- <span className={state.spanClass}>
- <CloseSingle />
- </span>
- <span className={state.spanClass}>
- <CheckMarkSingle />
- </span>
- {state.fx ? (
- <span className={styles.formulaBlack} onClick={state.fx.onClick}>
- {Icon && <Icon />}
+ <div className={styles.formulaIconWrapper}>
+ <span
+ className={clsx(styles.iconContainer, styles.iconContainerError, iconStyle)}
+ onClick={handleCloseBtnClick}
+ >
+ <CloseSingle />
+ </span>
+
+ <span
+ className={clsx(styles.iconContainer, styles.iconContainerSuccess, iconStyle)}
+ onClick={handleConfirmBtnClick}
+ >
+ <CheckMarkSingle />
</span>
- ) : null}
+
+ <span className={styles.iconContainer} onClick={handlerFxBtnClick}>
+ <FxSingle />
+ </span>
+ </div>
</div>
+
<div className={styles.formulaInput}>
- <div
- autoFocus
- contentEditable={true}
- className={styles.formulaContent}
- onKeyUp={(e) => printChange(e)}
- dangerouslySetInnerHTML={{ __html: state.formulaContent }}
- />
+ <div className={styles.formulaContent} ref={editorRef} />
+ <div className={styles.arrowContainer} onClick={handleArrowClick}>
+ {arrowDirection === ArrowDirection.Down ? <DownTriangleSingle /> : <UpTriangleSingle />}
+ </div>
</div>
</div>
</div>
diff --git a/packages/ui-plugin-sheets/src/views/formula-bar/index.module.less b/packages/ui-plugin-sheets/src/views/formula-bar/index.module.less
index 600dac72b4..a86a3d96f6 100644
--- a/packages/ui-plugin-sheets/src/views/formula-bar/index.module.less
+++ b/packages/ui-plugin-sheets/src/views/formula-bar/index.module.less
@@ -3,60 +3,105 @@
box-sizing: border-box;
height: 28px;
- padding: 0 var(--padding-xl);
background: rgb(var(--bg-color-secondary));
border-bottom: 1px solid rgb(var(--border-color));
- .select-button .tooltip-group .tooltip-body {
- display: flex;
+ transition: height .15s;
- input {
- width: 85px;
- height: 100%;
- }
+ .name-ranges {
+ box-sizing: border-box;
+ width: 80px;
+ height: 100%;
+ padding: 6px 0;
- svg {
- vertical-align: text-bottom;
+ &-input {
+ height: 100%;
+ border-right: 1px solid rgb(var(--border-color));
}
}
.formula-bar {
display: flex;
width: 100%;
+ height: 100%;
.formula-icon {
- display: flex;
- align-items: center;
- font-size: var(--font-size-xs);
- border-right: 1px solid var(--gray-15);
+ padding: 6px 0;
- span[role='img'] {
- font-size: 24px;
- }
+ &-wrapper {
+ position: relative;
- .formula-grey {
- color: var(--gray-5);
- }
+ display: flex;
+ gap: var(--margin-xs);
+ align-items: center;
+ justify-content: center;
+
+ box-sizing: border-box;
+ width: 80px;
+ height: 100%;
+
+ font-size: var(--font-size-xs);
+
+ border-right: 1px solid rgb(var(--border-color));
+
+
+ .icon-container {
+ cursor: pointer;
- .formula-black {
- color: var(--text-color);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ font-size: var(--font-size-lg);
+
+ &-success {
+ &.formula-active {
+ color: rgb(var(--success-color));
+ }
+ }
+
+ &-error {
+ &.formula-active {
+ color: rgb(var(--error-color));
+ }
+ }
+ }
}
}
.formula-input {
overflow: hidden;
display: flex;
- align-items: center;
+ flex: 1;
width: 100%;
- padding: 0 10px;
+ padding: 0 0 0 10px;
.formula-content {
+ position: relative;
+
width: 100%;
+ height: 100%;
+
word-wrap: break-word;
+
outline: none;
}
+
+ .arrow-container {
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ height: 100%;
+
+ font-size: var(--font-size-xs);
+ color: rgb(var(--text-color-secondary));
+ }
}
}
}
diff --git a/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx b/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx
index edbda73ab3..14224a099a 100644
--- a/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx
@@ -9,7 +9,7 @@ import { SheetBar } from '../sheet-bar/SheetBar';
import { StatusBar } from '../status-bar/StatusBar';
import styles from './index.module.less';
-export interface BaseSheetContainerProps {
+export interface IBaseSheetContainerProps {
config: ISheetUIPluginConfig;
changeLocale: (locale: string) => void;
methods?: any;