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(sheet): sheet editor develop (#310)

Univercf755e6c82ed
diff --git a/examples/univer-sheet-ts/src/main.tsx b/examples/univer-sheet-ts/src/main.tsx
index 8a7e6e1b58..a76dadc38e 100644
--- a/examples/univer-sheet-ts/src/main.tsx
+++ b/examples/univer-sheet-ts/src/main.tsx
@@ -1,9 +1,5 @@
import { DocPlugin } from '@univerjs/base-docs';
-import {
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- RenderEngine,
-} from '@univerjs/base-render';
+import { RenderEngine } from '@univerjs/base-render';
import { SheetPlugin } from '@univerjs/base-sheets';
import { greenTheme, UIPlugin } from '@univerjs/base-ui';
import { DEFAULT_WORKBOOK_DATA_DEMO } from '@univerjs/common-plugin-data';
@@ -14,7 +10,6 @@ import { DebuggerPlugin } from '@univerjs/sheets-plugin-debugger';
// import { ImagePlugin } from '@univerjs/sheets-plugin-image';
// import { ImportXlsxPlugin } from '@univerjs/sheets-plugin-import-xlsx';
// import { NumfmtPlugin } from '@univerjs/sheets-plugin-numfmt';
-import { DocUIPlugin } from '@univerjs/ui-plugin-docs';
import { SheetUIPlugin } from '@univerjs/ui-plugin-sheets';
import { locales } from './locales';
@@ -30,7 +25,7 @@ const univer = new Univer({
univer.registerPlugin(DocPlugin, {
hasScroll: false,
});
-univer.registerPlugin(DocUIPlugin);
+// univer.registerPlugin(DocUIPlugin);
univer.registerPlugin(RenderEngine);
univer.registerPlugin(UIPlugin, {
container: 'univer-container',
@@ -49,18 +44,6 @@ univer.registerPlugin(DebuggerPlugin);
// univer.registerPlugin(ImportXlsxPlugin);
// univer.registerPlugin(ImagePlugin);
-// create univer doc normal editor instance
-univer.createUniverDoc({
- id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- documentStyle: {},
-});
-
-// create univer doc formula bar editor instance
-univer.createUniverDoc({
- id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- documentStyle: {},
-});
-
// create univer sheet instance
univer.createUniverSheet(DEFAULT_WORKBOOK_DATA_DEMO);
diff --git a/packages/base-docs/src/Basics/component-tools.ts b/packages/base-docs/src/Basics/component-tools.ts
index 364a8846c3..c5ecba329a 100644
--- a/packages/base-docs/src/Basics/component-tools.ts
+++ b/packages/base-docs/src/Basics/component-tools.ts
@@ -31,3 +31,24 @@ export function getDocObject(
engine,
};
}
+
+export function getDocObjectById(
+ unitId: string,
+ renderManagerService: IRenderManagerService
+): Nullable<IDocObjectParam> {
+ const currentRender = renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { components, mainComponent, scene, engine } = currentRender;
+
+ const document = mainComponent as Documents;
+
+ return {
+ document,
+ scene,
+ engine,
+ };
+}
diff --git a/packages/base-docs/src/Basics/docs-view-key.ts b/packages/base-docs/src/Basics/docs-view-key.ts
index e6bbf27851..6ed6b981c1 100644
--- a/packages/base-docs/src/Basics/docs-view-key.ts
+++ b/packages/base-docs/src/Basics/docs-view-key.ts
@@ -14,3 +14,5 @@ export const DOCS_COMPONENT_MAIN_LAYER_INDEX = 0;
export const DOCS_COMPONENT_HEADER_LAYER_INDEX = 2;
export const DOCS_COMPONENT_DEFAULT_Z_INDEX = 10;
+
+export const NORMAL_TEXT_SELECTION_PLUGIN_NAME = 'normalTextSelectionPluginName';
diff --git a/packages/base-docs/src/Controller/doc-render.controller.ts b/packages/base-docs/src/Controller/doc-render.controller.ts
index 7e964a86aa..e207784a7e 100644
--- a/packages/base-docs/src/Controller/doc-render.controller.ts
+++ b/packages/base-docs/src/Controller/doc-render.controller.ts
@@ -1,7 +1,23 @@
-import { Documents, IRenderManagerService } from '@univerjs/base-render';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import {
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ Documents,
+ DocumentSkeleton,
+ IRender,
+ IRenderManagerService,
+ PageLayoutType,
+} from '@univerjs/base-render';
+import {
+ Disposable,
+ ICommandInfo,
+ ICommandService,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
+import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
@OnLifecycle(LifecycleStages.Rendered, DocRenderController)
@@ -31,12 +47,6 @@ export class DocRenderController extends Disposable {
const { skeleton: documentSkeleton, unitId } = param;
- const documentModel = this._currentUniverService.getUniverDocInstance(unitId);
-
- if (documentModel == null) {
- return;
- }
-
const currentRender = this._renderManagerService.getRenderById(unitId);
if (currentRender == null) {
@@ -49,9 +59,134 @@ export class DocRenderController extends Disposable {
docsComponent.changeSkeleton(documentSkeleton);
- documentSkeleton.calculate();
+ // documentSkeleton.calculate();
+
+ this.recalculateSizeBySkeleton(currentRender, documentSkeleton);
+
+ this.calculatePagePosition(currentRender);
});
}
- private _commandExecutedListener() {}
+ calculatePagePosition(currentRender: IRender) {
+ const { mainComponent, scene } = currentRender;
+
+ const docsComponent = mainComponent as Documents;
+
+ const parent = scene?.getParent();
+
+ const { width: docsWidth, height: docsHeight, pageMarginLeft, pageMarginTop } = docsComponent;
+ if (parent == null || docsWidth === Infinity || docsHeight === Infinity) {
+ return;
+ }
+ const { width: engineWidth, height: engineHeight } = parent;
+ let docsLeft = 0;
+ let docsTop = 0;
+
+ let sceneWidth = 0;
+
+ let sceneHeight = 0;
+
+ if (engineWidth > docsWidth) {
+ docsLeft = engineWidth / 2 - docsWidth / 2;
+ sceneWidth = engineWidth - 30;
+ } else {
+ docsLeft = pageMarginLeft;
+ sceneWidth = docsWidth + pageMarginLeft * 2;
+ }
+
+ if (engineHeight > docsHeight) {
+ docsTop = engineHeight / 2 - docsHeight / 2;
+ sceneHeight = engineHeight - 30;
+ } else {
+ docsTop = pageMarginTop;
+ sceneHeight = docsHeight + pageMarginTop * 2;
+ }
+
+ // this.docsLeft = docsLeft;
+
+ // this.docsTop = docsTop;
+
+ scene.resize(sceneWidth, sceneHeight + 200);
+
+ docsComponent.translate(docsLeft, docsTop);
+
+ return this;
+ }
+
+ recalculateSizeBySkeleton(currentRender: IRender, skeleton: DocumentSkeleton) {
+ const { mainComponent, scene } = currentRender;
+
+ const docsComponent = mainComponent as Documents;
+
+ const data = skeleton.getSkeletonData();
+
+ if (data == null) {
+ return;
+ }
+
+ const pages = data.pages;
+ let width = 0;
+ let height = 0;
+ for (let i = 0, len = pages.length; i < len; i++) {
+ const page = pages[i];
+ const { pageWidth, pageHeight } = page;
+ if (docsComponent.pageLayoutType === PageLayoutType.VERTICAL) {
+ height += pageHeight;
+ if (i !== len - 1) {
+ height += docsComponent.pageMarginTop;
+ }
+ width = Math.max(width, pageWidth);
+ } else if (docsComponent.pageLayoutType === PageLayoutType.HORIZONTAL) {
+ width += pageWidth;
+ if (i !== len - 1) {
+ width += docsComponent.pageMarginLeft;
+ }
+ height = Math.max(height, pageHeight);
+ }
+ }
+
+ docsComponent.resize(width, height);
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [RichTextEditingMutation.id];
+
+ const excludeUnitList = [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: commandUnitId } = params;
+
+ const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+
+ if (docsSkeletonObject == null) {
+ return;
+ }
+
+ const { unitId, skeleton } = docsSkeletonObject;
+
+ if (commandUnitId !== unitId) {
+ return;
+ }
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ if (excludeUnitList.includes(unitId)) {
+ currentRender.mainComponent?.makeDirty();
+ return;
+ }
+
+ this.recalculateSizeBySkeleton(currentRender, skeleton);
+
+ this.calculatePagePosition(currentRender);
+ }
+ })
+ );
+ }
}
diff --git a/packages/base-docs/src/Controller/page-render.controller.ts b/packages/base-docs/src/Controller/page-render.controller.ts
index 940db386ae..49216774de 100644
--- a/packages/base-docs/src/Controller/page-render.controller.ts
+++ b/packages/base-docs/src/Controller/page-render.controller.ts
@@ -1,4 +1,11 @@
-import { Documents, IPageRenderConfig, IRenderManagerService, Rect } from '@univerjs/base-render';
+import {
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ Documents,
+ IPageRenderConfig,
+ IRenderManagerService,
+ Rect,
+} from '@univerjs/base-render';
import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
@@ -48,6 +55,9 @@ export class PageRenderController extends Disposable {
const pageSize = docsComponent.getSkeleton()?.getPageSize();
docsComponent.onPageRenderObservable.add((config: IPageRenderConfig) => {
+ if ([DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY].includes(unitId)) {
+ return;
+ }
const { page, pageLeft, pageTop, ctx } = config;
const { width, height, marginBottom, marginLeft, marginRight, marginTop } = page;
ctx.save();
diff --git a/packages/base-docs/src/Controller/text-selection.controller.ts b/packages/base-docs/src/Controller/text-selection.controller.ts
index b328cbd7ee..fb521d7a63 100644
--- a/packages/base-docs/src/Controller/text-selection.controller.ts
+++ b/packages/base-docs/src/Controller/text-selection.controller.ts
@@ -1,6 +1,7 @@
import {
CURSOR_TYPE,
cursorConvertToTextSelection,
+ Documents,
getOneTextSelectionRange,
IMouseEvent,
IPointerEvent,
@@ -21,15 +22,12 @@ import {
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { getDocObject, IDocObjectParam } from '../Basics/component-tools';
-import { VIEWPORT_KEY } from '../Basics/docs-view-key';
+import { getDocObjectById } from '../Basics/component-tools';
+import { NORMAL_TEXT_SELECTION_PLUGIN_NAME, VIEWPORT_KEY } from '../Basics/docs-view-key';
import { ISetZoomRatioMutationParams, SetZoomRatioMutation } from '../commands/mutations/set-zoom-ratio.mutation';
import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
-import {
- NORMAL_TEXT_SELECTION_PLUGIN_NAME,
- TextSelectionManagerService,
-} from '../services/text-selection-manager.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@OnLifecycle(LifecycleStages.Rendered, TextSelectionController)
export class TextSelectionController extends Disposable {
@@ -39,6 +37,8 @@ export class TextSelectionController extends Disposable {
private _downObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+ private _loadedMap = new Set();
+
constructor(
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@@ -50,47 +50,58 @@ export class TextSelectionController extends Disposable {
) {
super();
+ this._renderManagerService.currentRender$.subscribe((unitId) => {
+ if (unitId == null) {
+ return;
+ }
+
+ if (this._currentUniverService.getUniverDocInstance(unitId) == null) {
+ return;
+ }
+
+ if (!this._loadedMap.has(unitId)) {
+ this._initialMain(unitId);
+ this._loadedMap.add(unitId);
+ }
+ });
+
this._initialize();
}
override dispose(): void {
- const docObject = this._getDocObject();
- if (docObject == null) {
- return;
- }
- const { document, scene } = docObject;
- document.onPointerEnterObserver.remove(this._moveInObserver);
- document.onPointerLeaveObserver.remove(this._moveOutObserver);
- document.onPointerLeaveObserver.remove(this._downObserver);
+ this._renderManagerService.getRenderAll().forEach((docObject) => {
+ const { mainComponent } = docObject;
+ if (mainComponent == null) {
+ return;
+ }
+ const document = mainComponent as Documents;
+ document.onPointerEnterObserver.remove(this._moveInObserver);
+ document.onPointerLeaveObserver.remove(this._moveOutObserver);
+ document.onPointerLeaveObserver.remove(this._downObserver);
+ });
}
private _initialize() {
- const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
-
- const docObject = this._getDocObject();
- if (docObject == null) {
- return;
- }
-
this._onChangeListener();
- this._initialMain(docObject);
-
this._skeletonListener();
- this._commandExecutedListener();
-
this._userActionSyncListener();
- const unitId = documentModel.getUnitId();
+ this._commandExecutedListener();
- this._textSelectionManagerService.setCurrentSelection({
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
- unitId,
- });
+ // this._textSelectionManagerService.setCurrentSelection({
+ // pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ // unitId,
+ // });
}
- private _initialMain(docObject: IDocObjectParam) {
+ private _initialMain(unitId: string) {
+ const docObject = this._getDocObjectById(unitId);
+ if (docObject == null) {
+ return;
+ }
+
const { document, scene } = docObject;
const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
@@ -104,7 +115,7 @@ export class TextSelectionController extends Disposable {
});
this._downObserver = document?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
- this._textSelectionRenderManager.eventTrigger(evt, document.getOffsetConfig());
+ this._textSelectionRenderManager.eventTrigger(evt, document.getOffsetConfig(), viewportMain);
if (evt.button !== 2) {
state.stopPropagation();
}
@@ -113,14 +124,15 @@ export class TextSelectionController extends Disposable {
private _onChangeListener() {
this._textSelectionManagerService.textSelectionInfo$.subscribe((param) => {
+ const unitId = this._textSelectionManagerService.getCurrentSelection()?.unitId;
this._textSelectionRenderManager.reset();
- if (param == null) {
+ if (param == null || unitId == null) {
return;
}
const docSkeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
- const currentRender = this._getDocObject();
+ const currentRender = this._getDocObjectById(unitId);
if (currentRender == null || docSkeleton == null) {
return;
@@ -144,14 +156,17 @@ export class TextSelectionController extends Disposable {
private _userActionSyncListener() {
this._textSelectionRenderManager.textSelection$.subscribe((textSelections) => {
- const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
- const unitId = documentModel.getUnitId();
+ const docsObject = this._docSkeletonManagerService.getCurrent();
- const docSkeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+ if (docsObject == null) {
+ return;
+ }
+
+ const { skeleton: docSkeleton, unitId } = docsObject;
- const document = this._getDocObject()?.document;
+ const document = this._getDocObjectById(unitId)?.document;
- if (docSkeleton == null || document == null) {
+ if (document == null) {
return;
}
@@ -175,8 +190,8 @@ export class TextSelectionController extends Disposable {
});
}
- private _getDocObject() {
- return getDocObject(this._currentUniverService, this._renderManagerService);
+ private _getDocObjectById(unitId: string) {
+ return getDocObjectById(unitId, this._renderManagerService);
}
private _commandExecutedListener() {
@@ -185,11 +200,12 @@ export class TextSelectionController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (updateCommandList.includes(command.id)) {
- const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
-
const params = command.params as ISetZoomRatioMutationParams;
const { documentId } = params;
- if (documentId !== documentModel.getUnitId()) {
+
+ const unitId = this._textSelectionManagerService.getCurrentSelection()?.unitId;
+
+ if (documentId !== unitId) {
return;
}
diff --git a/packages/base-docs/src/DocPlugin.ts b/packages/base-docs/src/DocPlugin.ts
index d93eb9894c..6d2a66c1ff 100644
--- a/packages/base-docs/src/DocPlugin.ts
+++ b/packages/base-docs/src/DocPlugin.ts
@@ -71,7 +71,7 @@ export class DocPlugin extends Plugin {
this._config = Object.assign(DEFAULT_DOCUMENT_PLUGIN_DATA, config);
- // this.initialConfig(config);
+ this.initialConfig(config);
this._initializeDependencies(_injector);
@@ -123,8 +123,12 @@ export class DocPlugin extends Plugin {
}
initialConfig(config: IDocPluginConfig) {
- const unitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();
- this._configService.batchSettings(unitId, config);
+ this._currentUniverService.docAdded$.subscribe((documentModel) => {
+ if (documentModel == null) {
+ throw new Error('documentModel is null');
+ }
+ this._configService.batchSettings(documentModel.getUnitId(), config);
+ });
}
// initCanvasView() {
diff --git a/packages/base-docs/src/View/Render/Views/DocsView.ts b/packages/base-docs/src/View/Render/Views/DocsView.ts
index 8b2031d251..a1ec0b19f2 100644
--- a/packages/base-docs/src/View/Render/Views/DocsView.ts
+++ b/packages/base-docs/src/View/Render/Views/DocsView.ts
@@ -1,4 +1,4 @@
-import { Documents, DocumentSkeleton, IDocumentSkeletonDrawing, Picture, Scene } from '@univerjs/base-render';
+import { Documents, DocumentSkeleton, Scene } from '@univerjs/base-render';
import { DocumentModel, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
@@ -54,31 +54,31 @@ export class DocsView extends BaseView {
}
scrollToCenter() {
- const { docsLeft, docsTop } = this._documents.calculatePagePosition();
+ // const { docsLeft, docsTop } = this._documents.calculatePagePosition();
const pages = this._documentSkeleton.getSkeletonData()?.pages;
- if (!pages) {
- return;
- }
+ // if (!pages) {
+ // return;
+ // }
- for (let i = 0; i < pages.length; i++) {
- const page = pages[i];
- for (const k of page.skeDrawings.keys()) {
- const obj = this.getScene().getObject(k);
- if (obj) {
- const drawing = page.skeDrawings.get(k) as IDocumentSkeletonDrawing;
- if (obj instanceof Picture) {
- const props = obj.getPictureProps();
- obj.translate(
- drawing.aLeft + docsLeft + (props.liX ?? 0),
- drawing.aTop + docsTop + (props.liY ?? 0)
- );
- } else {
- obj.translate(drawing.aLeft + docsLeft, drawing.aTop + docsTop);
- }
- }
- }
- }
+ // for (let i = 0; i < pages.length; i++) {
+ // const page = pages[i];
+ // for (const k of page.skeDrawings.keys()) {
+ // const obj = this.getScene().getObject(k);
+ // if (obj) {
+ // const drawing = page.skeDrawings.get(k) as IDocumentSkeletonDrawing;
+ // if (obj instanceof Picture) {
+ // const props = obj.getPictureProps();
+ // obj.translate(
+ // drawing.aLeft + docsLeft + (props.liX ?? 0),
+ // drawing.aTop + docsTop + (props.liY ?? 0)
+ // );
+ // } else {
+ // obj.translate(drawing.aLeft + docsLeft, drawing.aTop + docsTop);
+ // }
+ // }
+ // }
+ // }
}
protected override _initialize() {
@@ -144,14 +144,14 @@ export class DocsView extends BaseView {
throw new Error();
}
- const { pageMarginLeft, pageMarginTop, docsLeft, docsTop } = documents.calculatePagePosition();
+ // const { pageMarginLeft, pageMarginTop, docsLeft, docsTop } = documents.calculatePagePosition();
- for (let i = 0; i < pages.length; i++) {
- for (const k of pages[i].skeDrawings.keys()) {
- const obj = this.getScene().getObject(k);
- obj?.translate(obj.left + docsLeft - pageMarginLeft, obj.top + docsTop - pageMarginTop);
- }
- }
+ // for (let i = 0; i < pages.length; i++) {
+ // for (const k of pages[i].skeDrawings.keys()) {
+ // const obj = this.getScene().getObject(k);
+ // obj?.translate(obj.left + docsLeft - pageMarginLeft, obj.top + docsTop - pageMarginTop);
+ // }
+ // }
}
private _buildSkeleton(model: DocumentModel) {
diff --git a/packages/base-docs/src/View/Render/Views/DrawingsView.ts b/packages/base-docs/src/View/Render/Views/DrawingsView.ts
index 73b011a3c2..6e699ad756 100644
--- a/packages/base-docs/src/View/Render/Views/DrawingsView.ts
+++ b/packages/base-docs/src/View/Render/Views/DrawingsView.ts
@@ -36,7 +36,7 @@ export class DrawingsView extends BaseView {
for (let i = 0, len = pages.length; i < len; i++) {
const page = pages[i];
- const { skeDrawings, marginLeft, marginTop, pageWidth, pageHeight } = page;
+ const { skeDrawings, marginLeft, marginTop } = page;
// cumPageLeft + = pageWidth + documents.pageMarginLeft;
diff --git a/packages/base-docs/src/View/doc-canvas-view.ts b/packages/base-docs/src/View/doc-canvas-view.ts
index 3664f620e1..7d93afd77f 100644
--- a/packages/base-docs/src/View/doc-canvas-view.ts
+++ b/packages/base-docs/src/View/doc-canvas-view.ts
@@ -35,6 +35,9 @@ export class DocCanvasView {
private _scene!: Scene;
private _currentDocumentModel!: DocumentModel;
+
+ private _loadedMap = new Set();
+
constructor(
@IRenderManagerService private readonly _renderManagerService: RenderManagerService,
@IConfigService private readonly _configService: IConfigService,
@@ -45,10 +48,15 @@ export class DocCanvasView {
) {
this._currentUniverService.currentDoc$.subscribe((documentModel) => {
if (documentModel == null) {
- throw new Error('documentModel is null');
+ return;
+ }
+
+ const unitId = documentModel.getUnitId();
+ if (!this._loadedMap.has(unitId)) {
+ this._currentDocumentModel = documentModel;
+ this._addNewRender();
+ this._loadedMap.add(unitId);
}
- this._currentDocumentModel = documentModel;
- this._addNewRender();
});
}
@@ -71,8 +79,6 @@ export class DocCanvasView {
this._renderManagerService.createRender(unitId);
}
- this._renderManagerService.setCurrent(unitId);
-
const currentRender = this._renderManagerService.getRenderById(unitId);
if (currentRender == null) {
@@ -144,6 +150,8 @@ export class DocCanvasView {
// }
});
}
+
+ this._renderManagerService.setCurrent(unitId);
}
private _addComponent(currentRender: IRender) {
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 882d6903f8..13cbcedee4 100644
--- a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
@@ -52,9 +52,9 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
const { unitId, mutations } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
- const document = univerInstanceService.getUniverDocInstance(unitId);
- if (!document) {
- throw new Error(`Document not found for unitId: ${unitId}`);
+ const documentModel = univerInstanceService.getUniverDocInstance(unitId);
+ if (!documentModel) {
+ throw new Error(`DocumentModel not found for unitId: ${unitId}`);
}
const undoMutations: Array<IRetainMutationParams | IInsertMutationParams | IDeleteMutationParams> = [];
@@ -65,7 +65,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
const { coverType, body, len, segmentId } = mutation;
if (body != null) {
const documentBody = UpdateAttributeApply(
- document,
+ documentModel,
body,
len,
commonParameter.cursor,
@@ -87,7 +87,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
});
} else if (mutation.t === 'i') {
const { body, len, segmentId, line } = mutation;
- InsertApply(document, body!, len, commonParameter.cursor, segmentId);
+ InsertApply(documentModel, body!, len, commonParameter.cursor, segmentId);
commonParameter.moveCursor(len);
undoMutations.push({
t: 'd',
@@ -97,7 +97,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
});
} else if (mutation.t === 'd') {
const { len, segmentId } = mutation;
- const documentBody = DeleteApply(document, len, commonParameter.cursor, segmentId);
+ const documentBody = DeleteApply(documentModel, len, commonParameter.cursor, segmentId);
undoMutations.push({
...mutation,
t: 'i',
diff --git a/packages/base-docs/src/commands/mutations/functions/common.ts b/packages/base-docs/src/commands/mutations/functions/common.ts
index 798620ab61..00d80d5977 100644
--- a/packages/base-docs/src/commands/mutations/functions/common.ts
+++ b/packages/base-docs/src/commands/mutations/functions/common.ts
@@ -13,6 +13,13 @@ import {
sortRulesFactory,
} from '@univerjs/core';
+/**
+ * Inserting styled text content into the current document model.
+ * @param body The current content object of the document model.
+ * @param insertBody The newly added content object that includes complete text and textRun style information.
+ * @param textLength The length of the inserted content text.
+ * @param currentIndex Determining the index where the content will be inserted into the current content.
+ */
export function insertTextRuns(
body: IDocumentBody,
insertBody: IDocumentBody,
@@ -25,7 +32,7 @@ export function insertTextRuns(
return;
}
- let insertIndex = Infinity;
+ let insertIndex = Infinity; // The current index of the textRun where the insertion needs to be made.
for (let i = 0, len = textRuns.length; i < len; i++) {
const textRun = textRuns[i];
const { st, ed } = textRun;
@@ -36,7 +43,12 @@ export function insertTextRuns(
if (insertIndex === Infinity) {
insertIndex = -Infinity;
}
- } else if (ed >= currentIndex) {
+ } else if (ed >= currentIndex - 1) {
+ /**
+ * Inserting text at the end of a rich text content,
+ * with the newly inserted text inheriting the style of that content.
+ * So, it is necessary to set ed >= currentIndex - 1 to ensure that the new text is inserted while maintaining the style of the existing content.
+ */
textRun.ed += textLength;
insertIndex = i;
}
@@ -85,6 +97,14 @@ export function insertTextRuns(
}
}
+/**
+ * Based on the insertBody parameter, which includes a paragraph object,
+ * you can add and adjust the position of paragraphs.
+ * @param body The current content object of the document model.
+ * @param insertBody The newly added content object that includes paragraph information.
+ * @param textLength The length of the inserted content text.
+ * @param currentIndex Determining the index where the content will be inserted into the current content.
+ */
export function insertParagraphs(
body: IDocumentBody,
insertBody: IDocumentBody,
@@ -104,7 +124,7 @@ export function insertParagraphs(
for (let i = 0, len = paragraphs.length; i < len; i++) {
const paragraph = paragraphs[i];
const { startIndex } = paragraph;
- if (startIndex > currentIndex) {
+ if (startIndex >= currentIndex) {
paragraph.startIndex += textLength;
}
@@ -162,7 +182,14 @@ export function insertSectionBreaks(
for (let i = 0, len = sectionBreaks.length; i < len; i++) {
const sectionBreak = sectionBreaks[i];
const { startIndex } = sectionBreak;
- if (startIndex > currentIndex) {
+ if (startIndex >= currentIndex) {
+ /**
+ * Here, startIndex >= currentIndex means that the starting index of
+ * the new paragraph should be greater than or equal to the current index.
+ * This ensures that the paragraph is inserted at a position after the current paragraph.
+ * However, the accuracy of this condition depends on the specific context and
+ * implementation details, so it would be best to validate it further in your specific scenario.
+ */
sectionBreak.startIndex += textLength;
}
}
@@ -194,7 +221,7 @@ export function insertCustomBlocks(
for (let i = 0, len = customBlocks.length; i < len; i++) {
const customBlock = customBlocks[i];
const { startIndex } = customBlock;
- if (startIndex > currentIndex) {
+ if (startIndex >= currentIndex) {
customBlock.startIndex += textLength;
}
}
@@ -224,7 +251,7 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, tex
if (startIndex > currentIndex) {
table.startIndex += textLength;
table.endIndex += textLength;
- } else if (endIndex >= currentIndex) {
+ } else if (endIndex >= currentIndex - 1) {
table.endIndex += textLength;
}
}
@@ -260,7 +287,7 @@ export function insertCustomRanges(
if (startIndex > currentIndex) {
customRange.startIndex += textLength;
customRange.endIndex += textLength;
- } else if (endIndex >= currentIndex) {
+ } else if (endIndex >= currentIndex - 1) {
customRange.endIndex += textLength;
}
}
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index ade9a5e688..d81109ef07 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -1,4 +1,5 @@
export * from './Basics/component-tools';
+export * from './Basics/docs-view-key';
export {
CoverCommand,
DeleteCommand,
@@ -11,6 +12,10 @@ export {
type IUpdateCommandParams,
UpdateCommand,
} from './commands/commands/core-editing.command';
+export {
+ type IRichTextEditingMutationParams,
+ RichTextEditingMutation,
+} from './commands/mutations/core-editing.mutation';
export * from './DocPlugin';
export * from './Locale';
export { DocSkeletonManagerService } from './services/doc-skeleton-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 3f5a92cda9..9dc0a580e9 100644
--- a/packages/base-docs/src/services/doc-skeleton-manager.service.ts
+++ b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
@@ -49,6 +49,40 @@ export class DocSkeletonManagerService implements IDisposable {
return this._getCurrentBySearch(this._currentSkeleton);
}
+ updateCurrent(searchParm: IDocSkeletonManagerSearch) {
+ const { unitId } = searchParm;
+
+ const documentModel = this._currentUniverService.getUniverDocInstance(searchParm.unitId);
+
+ if (documentModel == null || documentModel.bodyModel == null) {
+ return;
+ }
+
+ const skeleton = this._buildSkeleton(documentModel);
+
+ skeleton.calculate();
+
+ const oldDocSkeleton = this._docSkeletonParam.find((doc) => doc.unitId === unitId);
+ if (oldDocSkeleton != null) {
+ const index = this._docSkeletonParam.indexOf(oldDocSkeleton);
+ this._docSkeletonParam.splice(index, 1);
+ }
+
+ this._docSkeletonParam.push({
+ unitId,
+ skeleton,
+ dirty: false,
+ });
+
+ this._currentSkeleton = searchParm;
+
+ this._currentSkeletonBefore$.next(this.getCurrent());
+
+ this._currentSkeleton$.next(this.getCurrent());
+
+ return this.getCurrent();
+ }
+
setCurrent(searchParm: IDocSkeletonManagerSearch): Nullable<IDocSkeletonManagerParam> {
const param = this._getCurrentBySearch(searchParm);
if (param != null) {
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 295d8f7648..debcd726a6 100644
--- a/packages/base-docs/src/services/text-selection-manager.service.ts
+++ b/packages/base-docs/src/services/text-selection-manager.service.ts
@@ -1,9 +1,9 @@
-import { ISelectionStyle, ITextSelectionRangeWithStyle } from '@univerjs/base-render';
+import { ITextSelectionRangeWithStyle } from '@univerjs/base-render';
import { ISelectionCell, Nullable } from '@univerjs/core';
import { IDisposable } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
-export const NORMAL_TEXT_SELECTION_PLUGIN_NAME = 'normalTextSelectionPluginName';
+import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../Basics/docs-view-key';
export interface ITextSelectionManagerSearchParam {
pluginName: string;
@@ -29,6 +29,10 @@ export class TextSelectionManagerService implements IDisposable {
readonly textSelectionInfo$ = this._textSelectionInfo$.asObservable();
+ getCurrentSelection() {
+ return this._currentSelection;
+ }
+
reset() {
if (this._currentSelection == null) {
return;
@@ -143,36 +147,6 @@ export class TextSelectionManagerService implements IDisposable {
this._removeByParam(index, this._currentSelection);
}
- createDefaultAutoFillSelection(): ISelectionStyle {
- return {
- strokeWidth: 2,
- stroke: '#FFF000',
- fill: 'rgba(0, 0, 0, 0.2)',
- widgets: {},
- hasAutoFill: true,
- };
- }
-
- createCopyPasteSelection(): ISelectionStyle {
- return {
- strokeWidth: 2,
- stroke: '#FFF000',
- fill: 'rgba(0, 0, 0, 0.2)',
- widgets: {},
- hasAutoFill: false,
- };
- }
-
- createDefaultSelection(): ISelectionStyle {
- return {
- strokeWidth: 2,
- stroke: '#FFF000',
- fill: 'rgba(0, 0, 0, 0.2)',
- widgets: { tr: true, tl: true, br: true, bl: true },
- hasAutoFill: false,
- };
- }
-
private _getTextRanges(param: Nullable<ITextSelectionManagerSearchParam>) {
if (param == null) {
return;
diff --git a/packages/base-render/src/Basics/IDocumentSkeletonCached.ts b/packages/base-render/src/Basics/IDocumentSkeletonCached.ts
index 356d101899..5743058ef3 100644
--- a/packages/base-render/src/Basics/IDocumentSkeletonCached.ts
+++ b/packages/base-render/src/Basics/IDocumentSkeletonCached.ts
@@ -1,251 +1,257 @@
-import {
- BulletAlignment,
- ColumnSeparatorType,
- DataStreamTreeTokenType,
- IDocumentRenderConfig,
- IDrawing,
- IIndentStart,
- INestingLevel,
- ITextStyle,
- PageOrientType,
-} from '@univerjs/core';
-
-export interface IDocumentSkeletonCached extends ISkeletonResourceReference {
- pages: IDocumentSkeletonPage[];
- left: number;
- top: number;
- st: number; // startIndex 文本开始索引
- ed?: number; // endIndex 文本结束索引
-}
-
-export interface ISkeletonResourceReference {
- skeHeaders: Map<string, Map<number, IDocumentSkeletonHeader>>; // id:{ width: IDocumentSkeletonFooter }
- skeFooters: Map<string, Map<number, IDocumentSkeletonFooter>>;
- /* Global cache, does not participate in rendering, only helps skeleton generation */
- skeListLevel?: Map<string, IDocumentSkeletonBullet[]>; // 有序列表缓存,id:{ level: max(width)的bullet }
- drawingAnchor?: Map<number, IDocumentSkeletonDrawingAnchor>; // Anchor point to assist floating element positioning
-}
-
-export interface IDocumentSkeletonDrawingAnchor {
- elements: IDocumentSkeletonLine[]; // element: lines, tr
- paragraphIndex: number; // block id
- top: number; // relative height for previous block
-}
-
-export interface IDocumentSkeletonHeaderFooterBase {
- lines: IDocumentSkeletonLine[];
- skeDrawings: Map<string, IDocumentSkeletonDrawing>;
- height: number; // footer或header的总长度
- st: number; // startIndex 文本开始索引
- ed: number; // endIndex 文本结束索引
- marginLeft: number;
-}
-
-export interface IDocumentSkeletonHeader extends IDocumentSkeletonHeaderFooterBase {
- marginTop: number;
-}
-
-export interface IDocumentSkeletonFooter extends IDocumentSkeletonHeaderFooterBase {
- marginBottom: number;
-}
-
-export interface IDocumentSkeletonPage {
- sections: IDocumentSkeletonSection[];
- headerId: string;
- footerId: string;
- // page
- pageWidth: number;
- pageHeight: number;
- pageOrient: PageOrientType;
-
- pageNumber: number; // page页数
- pageNumberStart: number; // page开始页序号
- verticalAlign: Boolean; // 垂直对齐,仅对一页生效
- angle: number; // 旋转角度,仅对一页生效
- width: number; // pageWidth,默认Infinity
- height: number; // pageHeight,默认Infinity
- marginLeft: number;
- marginRight: number;
- marginTop: number;
- marginBottom: number;
- breakType: BreakType; // 分页产生的类型
- st: number; // startIndex 文本开始索引
- ed: number; // endIndex 文本结束索引
- skeDrawings: Map<string, IDocumentSkeletonDrawing>;
- renderConfig?: IDocumentRenderConfig;
- parent?: IDocumentSkeletonCached;
-}
-
-export interface IDocumentSkeletonSection {
- columns: IDocumentSkeletonColumn[];
- colCount: number; // column Count 列的数量
- // section坐标系相对于page
- height: number; // 设置的高度, 如果未指定则与pageContentHeight相同 = pageHeight - marginTop - marginBottom
- top: number; // 根据pre height计算下一个section开始位置
- st: number; // startIndex 文本开始索引
- ed: number; // endIndex 文本结束索引
- parent?: IDocumentSkeletonPage;
-}
-
-export interface IDocumentSkeletonColumn {
- lines: IDocumentSkeletonLine[];
- // column坐标系相对于section
- left: number;
- width: number; // (columnWidth + spaceWidth) + ... = page.Width
- height?: number; // 实际的高度
- spaceWidth: number;
- separator: ColumnSeparatorType; // 类型
- st: number; // startIndex 文本开始索引
- ed: number; // endIndex 文本结束索引
- drawingLRIds: []; // 影响行列的元素id集合,影响左右
- isFull: boolean; // 内容是否装满
- parent?: IDocumentSkeletonSection;
-}
-
-export interface IDocumentSkeletonLine {
- paragraphIndex: number; // ID number associated with block
- type: LineType; // 行的类型,可以是段落或者其他block
- // line坐标系相对于column
- divides: IDocumentSkeletonDivide[]; // divides 受到对象影响,把行切分为N部分
- divideLen: number; // divideLen 被对象分割为多少块
-
- lineHeight: number; // 行总体高度 lineHeight =max(span.fontBoundingBoxAscent + span.fontBoundingBoxDescent, span2.....) + space
- contentHeight: number; // contentHeight 行内容高度,contentHeight,=max(span.fontBoundingBoxAscent + span.fontBoundingBoxDescent, span2.....)
- top: number; // top paragraph(spaceAbove, spaceBelow, lineSpacing*PreLineHeight)
- asc: number; // =max(span.textMetrics.asc) alphabet对齐,需要校准
- paddingTop: number; // paddingTop 内容到顶部的距离
- paddingBottom: number; // paddingBottom 内容到底部的距离
- marginTop: number; // marginTop 针对段落的spaceAbove
- marginBottom: number; // marginBottom 针对段落的spaceBlow
- spaceBelowApply: number; // spaceBelowApply 计算后的下间距,只参与计算
- width?: number; // the actual width of a line
- st: number; // startIndex 文本开始索引
- ed: number; // endIndex 文本结束索引
-
- lineIndex: number; // lineIndex 行号
- bullet?: IDocumentSkeletonBullet; // 无序和有序列表标题
- paragraphStart: boolean; // Paragraph start 默认false
-
- // dtId: string[]; // drawingTBIds 影响行的元素id集合,会切割divide,影响上下
- // bmt: number; // benchmarkTop, drawing的位置是根据paragraph的位置进行相对定位的,段落跨页后,需要一个校准
- parent?: IDocumentSkeletonColumn;
-}
-
-export interface IDocumentSkeletonDivide {
- // divide 分割,为了适配插入对象、图片、表格等,图文混排
- spanGroup: IDocumentSkeletonSpan[]; // spanGroup
- width: number; // width 被分割后的总宽度
- left: number; // left 被对象分割后的偏移位置 | d1 | | d2 |
- paddingLeft: number; // paddingLeft 根据horizonAlign和width计算对齐偏移
- isFull: boolean; // isFull, // 内容是否装满
- st: number; // startIndex
- ed: number; // endIndex
- parent?: IDocumentSkeletonLine;
-}
-
-export interface IDocumentSkeletonSpan {
- // word or letter or image or custom
- eId?: string; // elementId, For custom cases
- spanType: SpanType; // SpanType
- streamType: DataStreamTreeTokenType;
- width: number; // cum width
- bBox: IDocumentSkeletonBoundingBox; // bBox: size of Span
- paddingLeft: number; // paddingLeft, adjust text align in span
- left: number; // left
- count?: number; // count, content,default 1
- content?: string; // content
- ts?: ITextStyle; // text style
- fontStyle?: IDocumentSkeletonFontStyle; // fontStyle : ITextStyle convert to canvas font
- parent?: IDocumentSkeletonDivide;
- url?: string; // image url
- featureId?: string; // support interaction for feature ,eg. hyperLine person
-}
-
-export interface IDocumentSkeletonBullet extends IIndentStart {
- listId: string; // listId
- symbol: string; // symbol 列表的内容
- ts: ITextStyle; // 文字样式
- fontStyle?: IDocumentSkeletonFontStyle; // fontStyle 从ITextStyle转换为canvas font
- startIndexItem: number; // startIndexItem,列表从第几开始
- bBox: IDocumentSkeletonBoundingBox; // bBox 文字的位置信息
- nestingLevel?: INestingLevel;
- bulletAlign?: BulletAlignment;
- bulletType?: boolean; // bulletType false unordered, true ordered;
- // bp: number; // bulletPosition 列表离页边的距离
- // ti: number; // textIndent 内容距列表的距离,取Max(textIndent, followWith+)
- // fw: number; // followWidth 内容距离列表的间隔距离
-}
-
-export interface IDocumentSkeletonDrawing {
- objectId: string;
- aLeft: number; // 相对于page的左方
- aTop: number; // 相对于page的上方
- width: number;
- height: number;
- angle: number; // 旋转
- initialState: boolean; // 是否初始化
- drawingOrigin: IDrawing;
-}
-
-export interface IDocumentSkeletonFontStyle {
- fontString: string;
- fontSize: number;
- fontFamily: string;
-}
-
-export interface IDocumentSkeletonBoundingBox {
- width: number; // width
- ba: number; // boundingBoxAscent
- bd: number; // boundingBoxDescent
- aba: number; // actualBoundingBoxAscent
- abd: number; // actualBoundingBoxDescent
- sp: number; // strikeoutPosition
- sbr: number; // subscriptSizeRatio
- sbo: number; // subscriptOffset
- spr: number; // superscriptSizeRatio
- spo: number; // superscriptOffset
-}
-
-export enum SkeletonType {
- SPAN,
- DIVIDE,
- LINE,
- COLUMN,
- SECTION,
- PAGE,
- DRAWING,
- BULLET,
- HEADER,
- FOOTER,
- ALL,
-}
-
-export enum BreakType {
- SECTION,
- PAGE,
- COLUMN,
-}
-
-export enum LineType {
- PARAGRAPH,
- BLOCK,
-}
-
-export enum SpanType {
- LETTER,
- WORD,
- LIST,
- PLACEHOLDER,
- TAB,
- IMAGE,
- AT,
- MATH,
- MULTI_LINE,
- CUSTOM,
-}
-
-export enum PageLayoutType {
- VERTICAL,
- HORIZONTAL,
- AUTO,
-}
+import {
+ BulletAlignment,
+ ColumnSeparatorType,
+ DataStreamTreeTokenType,
+ IDocumentRenderConfig,
+ IDrawing,
+ IIndentStart,
+ INestingLevel,
+ ITextStyle,
+ PageOrientType,
+} from '@univerjs/core';
+
+export interface IDocumentSkeletonCached extends ISkeletonResourceReference {
+ pages: IDocumentSkeletonPage[];
+ left: number;
+ top: number;
+ st: number; // startIndex 文本开始索引
+ ed?: number; // endIndex 文本结束索引
+}
+
+export interface ISkeletonResourceReference {
+ skeHeaders: Map<string, Map<number, IDocumentSkeletonHeader>>; // id:{ width: IDocumentSkeletonFooter }
+ skeFooters: Map<string, Map<number, IDocumentSkeletonFooter>>;
+ /* Global cache, does not participate in rendering, only helps skeleton generation */
+ skeListLevel?: Map<string, IDocumentSkeletonBullet[]>; // 有序列表缓存,id:{ level: max(width)的bullet }
+ drawingAnchor?: Map<number, IDocumentSkeletonDrawingAnchor>; // Anchor point to assist floating element positioning
+}
+
+export interface IDocumentSkeletonDrawingAnchor {
+ elements: IDocumentSkeletonLine[]; // element: lines, tr
+ paragraphIndex: number; // block id
+ top: number; // relative height for previous block
+}
+
+export interface IDocumentSkeletonHeaderFooterBase {
+ lines: IDocumentSkeletonLine[];
+ skeDrawings: Map<string, IDocumentSkeletonDrawing>;
+ height: number; // footer或header的总长度
+ st: number; // startIndex 文本开始索引
+ ed: number; // endIndex 文本结束索引
+ marginLeft: number;
+}
+
+export interface IDocumentSkeletonHeader extends IDocumentSkeletonHeaderFooterBase {
+ marginTop: number;
+}
+
+export interface IDocumentSkeletonFooter extends IDocumentSkeletonHeaderFooterBase {
+ marginBottom: number;
+}
+
+export interface IDocumentSkeletonPage {
+ sections: IDocumentSkeletonSection[];
+ headerId: string;
+ footerId: string;
+ // page
+ pageWidth: number; // default Infinity, The current page width follows the snapshot configuration, determined jointly by documentStyle and sectionBreak, representing the static limit for each page, unrelated to the actual content's text width.
+ pageHeight: number; // default Infinity, The current page's height follows the snapshot configuration, jointly determined by documentStyle and sectionBreak, representing the static limit for each page, unrelated to the total height of the actual content's text.
+ pageOrient: PageOrientType; // Paper orientation, whether it's portrait (vertical) or landscape (horizontal)
+ marginLeft: number; // The current page's padding, used to accommodate column title space, follows the snapshot configuration, jointly determined by documentStyle and sectionBreak. It represents the static limit for each page, which may vary per page.
+ marginRight: number;
+ marginTop: number;
+ marginBottom: number;
+
+ pageNumber: number; // page页数
+ pageNumberStart: number; // page开始页序号
+ verticalAlign: Boolean; // 垂直对齐,仅对一页生效
+ angle: number; // 旋转角度,仅对一页生效
+ width: number; // actual or content width,default 0
+ height: number; // actual or content height, default 0
+
+ breakType: BreakType; // 分页产生的类型
+ st: number; // startIndex 文本开始索引
+ ed: number; // endIndex 文本结束索引
+ skeDrawings: Map<string, IDocumentSkeletonDrawing>;
+ renderConfig?: IDocumentRenderConfig;
+ parent?: IDocumentSkeletonCached;
+}
+
+export interface IDocumentSkeletonSection {
+ columns: IDocumentSkeletonColumn[];
+ colCount: number; // column Count 列的数量
+ // section坐标系相对于page
+ height: number; // 设置的高度, 如果未指定则与pageContentHeight相同 = pageHeight - marginTop - marginBottom
+ top: number; // 根据pre height计算下一个section开始位置
+ st: number; // startIndex 文本开始索引
+ ed: number; // endIndex 文本结束索引
+ parent?: IDocumentSkeletonPage;
+}
+
+export interface IDocumentSkeletonColumn {
+ lines: IDocumentSkeletonLine[];
+ // column坐标系相对于section
+ left: number;
+ width: number; // (columnWidth + spaceWidth) + ... = page.Width
+ height?: number; // 实际的高度
+ spaceWidth: number;
+ separator: ColumnSeparatorType; // 类型
+ st: number; // startIndex 文本开始索引
+ ed: number; // endIndex 文本结束索引
+ drawingLRIds: []; // 影响行列的元素id集合,影响左右
+ isFull: boolean; // 内容是否装满
+ parent?: IDocumentSkeletonSection;
+}
+
+export interface IDocumentSkeletonLine {
+ paragraphIndex: number; // ID number associated with block
+ type: LineType; // 行的类型,可以是段落或者其他block
+ // line坐标系相对于column
+ divides: IDocumentSkeletonDivide[]; // divides 受到对象影响,把行切分为N部分
+ divideLen: number; // divideLen 被对象分割为多少块
+
+ lineHeight: number; // 行总体高度 lineHeight =max(span.fontBoundingBoxAscent + span.fontBoundingBoxDescent, span2.....) + space
+ contentHeight: number; // contentHeight 行内容高度,contentHeight,=max(span.fontBoundingBoxAscent + span.fontBoundingBoxDescent, span2.....)
+ top: number; // top paragraph(spaceAbove, spaceBelow, lineSpacing*PreLineHeight)
+ asc: number; // =max(span.textMetrics.asc) alphabet对齐,需要校准
+ paddingTop: number; // paddingTop 内容到顶部的距离
+ paddingBottom: number; // paddingBottom 内容到底部的距离
+ marginTop: number; // marginTop 针对段落的spaceAbove
+ marginBottom: number; // marginBottom 针对段落的spaceBlow
+ spaceBelowApply: number; // spaceBelowApply 计算后的下间距,只参与计算
+ width?: number; // the actual width of a line
+ st: number; // startIndex 文本开始索引
+ ed: number; // endIndex 文本结束索引
+
+ lineIndex: number; // lineIndex 行号
+ bullet?: IDocumentSkeletonBullet; // 无序和有序列表标题
+ paragraphStart: boolean; // Paragraph start 默认false
+
+ // dtId: string[]; // drawingTBIds 影响行的元素id集合,会切割divide,影响上下
+ // bmt: number; // benchmarkTop, drawing的位置是根据paragraph的位置进行相对定位的,段落跨页后,需要一个校准
+ parent?: IDocumentSkeletonColumn;
+}
+
+export interface IDocumentSkeletonDivide {
+ // divide 分割,为了适配插入对象、图片、表格等,图文混排
+ spanGroup: IDocumentSkeletonSpan[]; // spanGroup
+ width: number; // width 被分割后的总宽度
+ left: number; // left 被对象分割后的偏移位置 | d1 | | d2 |
+ paddingLeft: number; // paddingLeft 根据horizonAlign和width计算对齐偏移
+ isFull: boolean; // isFull, // 内容是否装满
+ st: number; // startIndex
+ ed: number; // endIndex
+ parent?: IDocumentSkeletonLine;
+}
+
+export interface IDocumentSkeletonSpan {
+ // word or letter or image or custom
+ eId?: string; // elementId, For custom cases
+ spanType: SpanType; // SpanType
+ streamType: DataStreamTreeTokenType;
+ width: number; // cum width
+ bBox: IDocumentSkeletonBoundingBox; // bBox: size of Span
+ paddingLeft: number; // paddingLeft, adjust text align in span
+ left: number; // left
+ count?: number; // count, content,default 1
+ content?: string; // content
+ ts?: ITextStyle; // text style
+ fontStyle?: IDocumentSkeletonFontStyle; // fontStyle : ITextStyle convert to canvas font
+ parent?: IDocumentSkeletonDivide;
+ url?: string; // image url
+ featureId?: string; // support interaction for feature ,eg. hyperLine person
+}
+
+export interface IDocumentSkeletonBullet extends IIndentStart {
+ listId: string; // listId
+ symbol: string; // symbol 列表的内容
+ ts: ITextStyle; // 文字样式
+ fontStyle?: IDocumentSkeletonFontStyle; // fontStyle 从ITextStyle转换为canvas font
+ startIndexItem: number; // startIndexItem,列表从第几开始
+ bBox: IDocumentSkeletonBoundingBox; // bBox 文字的位置信息
+ nestingLevel?: INestingLevel;
+ bulletAlign?: BulletAlignment;
+ bulletType?: boolean; // bulletType false unordered, true ordered;
+ // bp: number; // bulletPosition 列表离页边的距离
+ // ti: number; // textIndent 内容距列表的距离,取Max(textIndent, followWith+)
+ // fw: number; // followWidth 内容距离列表的间隔距离
+}
+
+export interface IDocumentSkeletonDrawing {
+ objectId: string;
+ aLeft: number; // 相对于page的左方
+ aTop: number; // 相对于page的上方
+ width: number;
+ height: number;
+ angle: number; // 旋转
+ initialState: boolean; // 是否初始化
+ drawingOrigin: IDrawing;
+}
+
+export interface IDocumentSkeletonFontStyle {
+ fontString: string;
+ fontSize: number;
+ fontFamily: string;
+}
+
+export interface IDocumentSkeletonBoundingBox {
+ width: number; // width
+ ba: number; // boundingBoxAscent
+ bd: number; // boundingBoxDescent
+ aba: number; // actualBoundingBoxAscent
+ abd: number; // actualBoundingBoxDescent
+ sp: number; // strikeoutPosition
+ sbr: number; // subscriptSizeRatio
+ sbo: number; // subscriptOffset
+ spr: number; // superscriptSizeRatio
+ spo: number; // superscriptOffset
+}
+
+export enum SkeletonType {
+ SPAN,
+ DIVIDE,
+ LINE,
+ COLUMN,
+ SECTION,
+ PAGE,
+ DRAWING,
+ BULLET,
+ HEADER,
+ FOOTER,
+ ALL,
+}
+
+export enum BreakType {
+ SECTION,
+ PAGE,
+ COLUMN,
+}
+
+export enum LineType {
+ PARAGRAPH,
+ BLOCK,
+}
+
+export enum SpanType {
+ LETTER,
+ WORD,
+ LIST,
+ PLACEHOLDER,
+ TAB,
+ IMAGE,
+ AT,
+ MATH,
+ MULTI_LINE,
+ CUSTOM,
+}
+
+/**
+ * Determining the text layout, whether it's vertical or horizontal,
+ * data storage is primarily horizontal,
+ * and vertical layout is supported through rendering and drawing.
+ */
+export enum PageLayoutType {
+ VERTICAL,
+ HORIZONTAL,
+ AUTO,
+}
diff --git a/packages/base-render/src/Basics/TextSelection.ts b/packages/base-render/src/Basics/TextSelection.ts
index f828131c11..7184eaac7e 100644
--- a/packages/base-render/src/Basics/TextSelection.ts
+++ b/packages/base-render/src/Basics/TextSelection.ts
@@ -15,5 +15,5 @@ export const NORMAL_TEXT_SELECTION_PLUGIN_STYLE: ITextSelectionStyle = {
};
export interface ITextSelectionRangeWithStyle extends ITextSelectionRangeParam {
- style: ITextSelectionStyle;
+ style?: ITextSelectionStyle;
}
diff --git a/packages/base-render/src/Component/Docs/Block/Paragraph/Layout.Ruler.ts b/packages/base-render/src/Component/Docs/Block/Paragraph/Layout.Ruler.ts
index f508a5d625..2af70c6588 100644
--- a/packages/base-render/src/Component/Docs/Block/Paragraph/Layout.Ruler.ts
+++ b/packages/base-render/src/Component/Docs/Block/Paragraph/Layout.Ruler.ts
@@ -325,9 +325,9 @@ function _lineOperator(
const preTop = line?.top || 0;
const lineTop = preLineHeight + preTop;
- const { width, headerId, footerId } = lastPage;
- const headersDrawings = skeHeaders?.get(headerId)?.get(width)?.skeDrawings;
- const footersDrawings = skeFooters?.get(footerId)?.get(width)?.skeDrawings;
+ const { pageWidth, headerId, footerId } = lastPage;
+ const headersDrawings = skeHeaders?.get(headerId)?.get(pageWidth)?.skeDrawings;
+ const footersDrawings = skeFooters?.get(footerId)?.get(pageWidth)?.skeDrawings;
__updateDrawingPosition(
lineTop,
diff --git a/packages/base-render/src/Component/Docs/Block/Paragraph/Paragraph.ts b/packages/base-render/src/Component/Docs/Block/Paragraph/Paragraph.ts
index 67a2f5bf56..139eb1e206 100644
--- a/packages/base-render/src/Component/Docs/Block/Paragraph/Paragraph.ts
+++ b/packages/base-render/src/Component/Docs/Block/Paragraph/Paragraph.ts
@@ -339,6 +339,13 @@ function _getNextPageNumber(lastPage: IDocumentSkeletonPage) {
return lastPage.pageNumber + 1;
}
+/**
+ * todo: @author DR-univer
+ * When aligning text horizontally within a document,
+ * it may be ineffective if the total line width is not initially calculated.
+ * Therefore, multiple calculations are performed, which may impact performance.
+ * Needs optimization for efficiency.
+ */
function horizontalAlignHandler(line: IDocumentSkeletonLine, horizontalAlign: HorizontalAlign) {
if (horizontalAlign === HorizontalAlign.UNSPECIFIED || horizontalAlign === HorizontalAlign.LEFT) {
return;
diff --git a/packages/base-render/src/Component/Docs/Common/Liquid.ts b/packages/base-render/src/Component/Docs/Common/Liquid.ts
index 74172ae06c..a05ed57a63 100644
--- a/packages/base-render/src/Component/Docs/Common/Liquid.ts
+++ b/packages/base-render/src/Component/Docs/Common/Liquid.ts
@@ -53,6 +53,34 @@ export class Liquid {
}
}
+ // const {
+ // verticalAlign = VerticalAlign.TOP,
+ // horizontalAlign = HorizontalAlign.LEFT,
+ // centerAngle: centerAngleDeg = 0,
+ // vertexAngle: vertexAngleDeg = 0,
+ // wrapStrategy = WrapStrategy.UNSPECIFIED,
+ // isRotateNonEastAsian = BooleanNumber.FALSE,
+ // } = renderConfig;
+
+ // let paddingTop = 0;
+
+ // if (verticalAlign === VerticalAlign.MIDDLE && pageHeight !== Infinity) {
+ // paddingTop = (pageHeight - height) / 2;
+ // } else if (verticalAlign === VerticalAlign.BOTTOM && pageHeight !== Infinity) {
+ // paddingTop = pageHeight - height - pagePaddingBottom;
+ // } else {
+ // paddingTop = pagePaddingTop;
+ // }
+
+ // let paddingLeft = 0;
+
+ // if (horizontalAlign === HorizontalAlign.CENTER && pageWidth !== Infinity) {
+ // paddingLeft = (pageWidth - width) / 2;
+ // } else if (horizontalAlign === HorizontalAlign.RIGHT && pageWidth !== Infinity) {
+ // paddingLeft = pageWidth - width - pagePaddingRight;
+ // } else {
+ // paddingLeft = pagePaddingLeft;
+ // }
translatePagePadding(page: IDocumentSkeletonPage) {
const {
marginTop: pagePaddingTop = 0,
@@ -102,9 +130,9 @@ export class Liquid {
let pageLeft = 0;
if (type === PageLayoutType.VERTICAL) {
- pageTop = pageHeight + top;
+ pageTop += pageHeight + top;
} else if (type === PageLayoutType.HORIZONTAL) {
- pageLeft = pageWidth + left;
+ pageLeft += pageWidth + left;
}
this.translate(pageLeft, pageTop);
diff --git a/packages/base-render/src/Component/Docs/Common/Page.ts b/packages/base-render/src/Component/Docs/Common/Page.ts
index 2726504530..1ade5f34e7 100644
--- a/packages/base-render/src/Component/Docs/Common/Page.ts
+++ b/packages/base-render/src/Component/Docs/Common/Page.ts
@@ -56,8 +56,10 @@ export function createSkeletonPage(
page.marginLeft = marginLeft;
page.marginRight = marginRight;
page.breakType = breakType;
- page.width = page.pageWidth = pageWidth;
- page.height = page.pageHeight = pageHeight;
+ page.pageWidth = pageWidth;
+ page.width = 0;
+ page.pageHeight = pageHeight;
+ page.height = 0;
page.pageOrient = pageOrient;
const { defaultHeaderId, evenPageHeaderId, firstPageHeaderId } = headerIds;
diff --git a/packages/base-render/src/Component/Docs/Common/TextSelection.ts b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
index 90873ba244..e49a5843b2 100644
--- a/packages/base-render/src/Component/Docs/Common/TextSelection.ts
+++ b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
@@ -32,7 +32,14 @@ export function cursorConvertToTextSelection(
docSkeleton: DocumentSkeleton,
documentOffsetConfig: IDocumentOffsetConfig
): Nullable<TextSelection> {
- const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, style } = range;
+ const {
+ cursorStart,
+ cursorEnd,
+ isCollapse,
+ isEndBack,
+ isStartBack,
+ style = NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ } = range;
const startNode = docSkeleton.findNodePositionByCharIndex(cursorStart, isStartBack);
let endNode;
diff --git a/packages/base-render/src/Component/Docs/Common/Tools.ts b/packages/base-render/src/Component/Docs/Common/Tools.ts
index 010d4fbecf..49c41622c5 100644
--- a/packages/base-render/src/Component/Docs/Common/Tools.ts
+++ b/packages/base-render/src/Component/Docs/Common/Tools.ts
@@ -53,7 +53,7 @@ export function getLastLineByColumn(column: IDocumentSkeletonColumn) {
}
export function getPageContentWidth(page: IDocumentSkeletonPage) {
- const { width: pageWidth, marginLeft: pageMarginLeft, marginRight: pageMarginRight } = page;
+ const { pageWidth, marginLeft: pageMarginLeft, marginRight: pageMarginRight } = page;
const pageContentWidth = pageWidth - pageMarginLeft - pageMarginRight;
return pageContentWidth;
}
@@ -289,14 +289,15 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
const pageStartIndex = prePageStartIndex;
const pageEndIndex = pageStartIndex;
let preSectionStartIndex = pageStartIndex;
- let maxPageWidth = -Infinity;
- let pageHeight = 0;
+ let maxContentWidth = -Infinity;
+ let contentHeight = 0;
for (const section of sections) {
const { columns } = section;
const sectionStartIndex = preSectionStartIndex;
const sectionEndIndex = pageStartIndex;
let preColumnStartIndex = sectionStartIndex;
let maxSectionHeight = -Infinity;
+ let sectionWidth = 0;
for (const column of columns) {
const { lines } = column;
const columStartIndex = preColumnStartIndex;
@@ -318,9 +319,9 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
const divide = divides[i];
const { spanGroup } = divide;
- if (spanGroup.length === 0) {
- continue;
- }
+ // if (spanGroup.length === 0) {
+ // continue;
+ // }
const divStartIndex = preDivideStartIndex;
let divEndIndex = divStartIndex;
@@ -339,18 +340,18 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
maxLineAsc = Math.max(maxLineAsc, ba);
- if (i === divideLength - 1 && divide.width === Infinity) {
+ if (i === divideLength - 1) {
// 宽度为Infinity时,最后一个divide也是Infinity,需要计算一个实际宽度。
actualWidth += span.width;
}
}
if (i === divideLength - 1) {
- if (divide.width === Infinity) {
- divide.width = actualWidth;
- } else {
- actualWidth += divide.width;
- }
+ // if (divide.width === Infinity) {
+ // divide.width = actualWidth;
+ // } else {
+ // actualWidth += divide.width;
+ // }
actualWidth += divide.left;
}
@@ -371,10 +372,10 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
column.st = columStartIndex === 0 ? 0 : columStartIndex + 1;
column.ed = preLineStartIndex >= column.st ? preLineStartIndex : column.st;
column.height = columnHeight;
- if (column.width === Infinity) {
- column.width = maxColumnWidth;
- }
- maxPageWidth = Math.max(maxPageWidth, maxColumnWidth);
+
+ column.width = maxColumnWidth;
+ sectionWidth += maxColumnWidth;
+
maxSectionHeight = Math.max(maxSectionHeight, column.height);
preColumnStartIndex = column.ed;
@@ -383,15 +384,17 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
section.st = sectionStartIndex === 0 ? 0 : sectionStartIndex + 1;
section.ed = preColumnStartIndex >= section.st ? preColumnStartIndex : section.st;
section.height = maxSectionHeight;
- pageHeight += maxSectionHeight;
+ contentHeight += maxSectionHeight;
+
+ maxContentWidth = Math.max(maxContentWidth, sectionWidth);
preSectionStartIndex = section.ed;
}
page.st = pageStartIndex === 0 ? 0 : pageStartIndex + 1;
page.ed = preSectionStartIndex >= page.st ? preSectionStartIndex : page.st;
- page.height = pageHeight;
- page.width = maxPageWidth;
+ page.height = contentHeight;
+ page.width = maxContentWidth;
prePageStartIndex = page.ed;
}
@@ -506,18 +509,18 @@ export function getPositionHorizon(
} else if (relativeFrom === ObjectRelativeFromH.OUTSIDE_MARGIN) {
// TODO
} else if (relativeFrom === ObjectRelativeFromH.PAGE) {
- const { width } = page;
+ const { pageWidth } = page;
let absoluteLeft = 0;
if (align === AlignTypeH.RIGHT) {
- absoluteLeft = width - objectWidth;
+ absoluteLeft = pageWidth - objectWidth;
} else if (align === AlignTypeH.CENTER) {
- absoluteLeft = width / 2 - objectWidth / 2;
+ absoluteLeft = pageWidth / 2 - objectWidth / 2;
}
return absoluteLeft;
}
}
} else if (posOffset) {
- const { width: pageWidth, marginLeft, marginRight } = page;
+ const { pageWidth, marginLeft, marginRight } = page;
const boundaryLeft = marginLeft;
const boundaryRight = pageWidth - marginRight;
@@ -543,7 +546,7 @@ export function getPositionHorizon(
}
return absoluteLeft;
} else if (percent) {
- const { width: pageWidth, marginLeft, marginRight } = page;
+ const { pageWidth, marginLeft, marginRight } = page;
if (relativeFrom === ObjectRelativeFromH.LEFT_MARGIN) {
// TODO
} else if (relativeFrom === ObjectRelativeFromH.MARGIN) {
@@ -594,12 +597,12 @@ export function getPositionVertical(
} else if (relativeFrom === ObjectRelativeFromV.OUTSIDE_MARGIN) {
// TODO
} else if (relativeFrom === ObjectRelativeFromV.PAGE) {
- const { height } = page;
+ const { pageHeight } = page;
let absoluteTop = 0;
if (align === AlignTypeV.BOTTOM) {
- absoluteTop = height - objectHeight;
+ absoluteTop = pageHeight - objectHeight;
} else if (align === AlignTypeV.CENTER) {
- absoluteTop = height / 2 - objectHeight / 2;
+ absoluteTop = pageHeight / 2 - objectHeight / 2;
}
return absoluteTop;
}
@@ -624,7 +627,7 @@ export function getPositionVertical(
}
return absoluteTop;
} else if (percent) {
- const { height: pageHeight, marginBottom, marginTop } = page;
+ const { pageHeight, marginBottom, marginTop } = page;
if (relativeFrom === ObjectRelativeFromV.TOP_MARGIN) {
// TODO
} else if (relativeFrom === ObjectRelativeFromV.MARGIN) {
diff --git a/packages/base-render/src/Component/Docs/DocComponent.ts b/packages/base-render/src/Component/Docs/DocComponent.ts
index 8cc4f74998..488263c576 100644
--- a/packages/base-render/src/Component/Docs/DocComponent.ts
+++ b/packages/base-render/src/Component/Docs/DocComponent.ts
@@ -11,10 +11,6 @@ import { DOCS_EXTENSION_TYPE } from './DocExtension';
import { DocumentSkeleton } from './DocSkeleton';
export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE> {
- pageWidth: number = 100;
-
- pageHeight: number = 100;
-
pageMarginLeft: number = 0;
pageMarginTop: number = 0;
diff --git a/packages/base-render/src/Component/Docs/DocSkeleton.ts b/packages/base-render/src/Component/Docs/DocSkeleton.ts
index cb1fba4b36..2ff5dd9bfd 100644
--- a/packages/base-render/src/Component/Docs/DocSkeleton.ts
+++ b/packages/base-render/src/Component/Docs/DocSkeleton.ts
@@ -8,7 +8,6 @@ import {
ISectionColumnProperties,
LocaleService,
Nullable,
- Observable,
PageOrientType,
SectionType,
VerticalAlign,
@@ -48,7 +47,7 @@ export enum DocumentSkeletonState {
}
export class DocumentSkeleton extends Skeleton {
- onRecalculateChangeObservable = new Observable<IDocumentSkeletonCached>();
+ // onRecalculateChangeObservable = new Observable<IDocumentSkeletonCached>();
private _docModel!: DocumentModelOrSimple;
@@ -85,13 +84,51 @@ export class DocumentSkeleton extends Skeleton {
}
this._skeletonData = this._createSkeleton(bounds);
- this.onRecalculateChangeObservable.notifyObservers(this._skeletonData);
+ // this.onRecalculateChangeObservable.notifyObservers(this._skeletonData);
}
getSkeletonData() {
return this._skeletonData;
}
+ getActualSize() {
+ const skeletonData = this.getSkeletonData();
+
+ let actualWidth = -Infinity;
+ let actualHeight = 0;
+
+ skeletonData?.pages.forEach((page) => {
+ const { width, height } = page;
+ actualWidth = Math.max(actualWidth, width);
+
+ actualHeight += height;
+ });
+
+ return {
+ actualWidth,
+ actualHeight,
+ };
+ }
+
+ private _getPageActualWidth(page: IDocumentSkeletonPage) {
+ let maxWidth = -Infinity;
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ let lineWidth = 0;
+ for (const divide of line.divides) {
+ for (const span of divide.spanGroup) {
+ lineWidth += span.width;
+ }
+ }
+ maxWidth = Math.max(maxWidth, lineWidth);
+ }
+ }
+ }
+
+ return maxWidth;
+ }
+
getPageSize() {
return this._docModel.documentStyle.pageSize;
}
@@ -167,66 +204,6 @@ export class DocumentSkeleton extends Skeleton {
const nodes = this._findNodeIterator(charIndex);
return nodes?.span;
-
- // const skeletonData = this.getSkeletonData();
-
- // if (!skeletonData) {
- // return;
- // }
-
- // const pages = skeletonData.pages;
-
- // for (const page of pages) {
- // const { sections, st, ed } = page;
-
- // if (charIndex < st || charIndex > ed) {
- // continue;
- // }
-
- // for (const section of sections) {
- // const { columns, st, ed } = section;
-
- // if (charIndex < st || charIndex > ed) {
- // continue;
- // }
-
- // for (const column of columns) {
- // const { lines, st, ed } = column;
-
- // if (charIndex < st || charIndex > ed) {
- // continue;
- // }
-
- // for (const line of lines) {
- // const { divides, lineHeight, st, ed } = line;
- // const divideLength = divides.length;
-
- // if (charIndex < st || charIndex > ed) {
- // continue;
- // }
-
- // for (let i = 0; i < divideLength; i++) {
- // const divide = divides[i];
- // const { spanGroup, st, ed } = divide;
-
- // if (charIndex < st || charIndex > ed) {
- // continue;
- // }
-
- // if (spanGroup[0].spanType === SpanType.LIST) {
- // charIndex++;
- // }
-
- // const span = spanGroup[charIndex - st];
-
- // if (span) {
- // return span;
- // }
- // }
- // }
- // }
- // }
- // }
}
findSpanByPosition(position: Nullable<INodePosition>) {
@@ -287,12 +264,12 @@ export class DocumentSkeleton extends Skeleton {
for (let i = 0, len = pages.length; i < len; i++) {
const page = pages[i];
- const { startX, startY, endX, endY } = this._getPageBoundingBox(page, pageLayoutType);
+ // const { startX, startY, endX, endY } = this._getPageBoundingBox(page, pageLayoutType);
- if (!(x >= startX && x <= endX && y >= startY && y <= endY)) {
- this._translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
- continue;
- }
+ // if (!(x >= startX && x <= endX && y >= startY && y <= endY)) {
+ // this._translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ // continue;
+ // }
this._findLiquid.translatePagePadding(page);
@@ -303,7 +280,7 @@ export class DocumentSkeleton extends Skeleton {
this._findLiquid.translateSection(section);
- const { y: startY } = this._findLiquid;
+ // const { y: startY } = this._findLiquid;
// if (!(y >= startY && y <= startY + height)) {
// continue;
@@ -314,7 +291,7 @@ export class DocumentSkeleton extends Skeleton {
this._findLiquid.translateColumn(column);
- const { x: startX } = this._findLiquid;
+ // const { x: startX } = this._findLiquid;
// if (!(x >= startX && x <= startX + columnWidth)) {
// continue;
@@ -465,27 +442,6 @@ export class DocumentSkeleton extends Skeleton {
this._findLiquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
}
- // updateDocumentDataPageSize(width?: number, height?: number) {
- // const documentStyle = this._docModel.documentStyle;
- // if (!documentStyle.pageSize) {
- // width = width ?? Infinity;
- // height = height ?? Infinity;
- // documentStyle.pageSize = {
- // width,
- // height,
- // };
- // return;
- // }
-
- // if (width !== undefined) {
- // documentStyle.pageSize.width = width;
- // }
-
- // if (height !== undefined) {
- // documentStyle.pageSize.height = height;
- // }
- // }
-
/**
* \v COLUMN_BREAK
* \f PAGE_BREAK
diff --git a/packages/base-render/src/Component/Docs/Document.ts b/packages/base-render/src/Component/Docs/Document.ts
index a9f737564f..5d828019da 100644
--- a/packages/base-render/src/Component/Docs/Document.ts
+++ b/packages/base-render/src/Component/Docs/Document.ts
@@ -83,7 +83,7 @@ export class Documents extends DocComponent {
this._initialDefaultExtension();
- this._addSkeletonChangeObserver(documentSkeleton);
+ // this._addSkeletonChangeObserver(documentSkeleton);
this.makeDirty(true);
}
@@ -103,8 +103,6 @@ export class Documents extends DocComponent {
this.pageLayoutType = config?.pageLayoutType || PageLayoutType.VERTICAL;
- // this._hasEditor = config?.hasEditor || false;
-
this.setAllowCache(config?.allowCache || false);
}
@@ -119,132 +117,53 @@ export class Documents extends DocComponent {
};
}
- // getEditor(): Nullable<DocsEditor> {
- // return this._editor;
- // }
-
- // getActiveSelection() {
- // return this._editor?.getActiveTextSelection();
- // }
-
- // getSelection() {
- // return this._editor?.getTextSelectionList();
- // }
-
- calculatePagePosition() {
- const scene = this.getScene() as Scene;
-
- const parent = scene?.getParent();
- const { width: docsWidth, height: docsHeight, pageMarginLeft, pageMarginTop } = this;
- if (parent == null) {
- return this;
- }
- const { width: engineWidth, height: engineHeight } = parent;
- let docsLeft = 0;
- let docsTop = 0;
-
- let sceneWidth = 0;
-
- let sceneHeight = 0;
-
- if (engineWidth > docsWidth) {
- docsLeft = engineWidth / 2 - docsWidth / 2;
- sceneWidth = engineWidth - 30;
- } else {
- docsLeft = pageMarginLeft;
- sceneWidth = docsWidth + pageMarginLeft * 2;
- }
-
- if (engineHeight > docsHeight) {
- docsTop = engineHeight / 2 - docsHeight / 2;
- sceneHeight = engineHeight - 30;
- } else {
- docsTop = pageMarginTop;
- sceneHeight = docsHeight + pageMarginTop * 2;
- }
-
- this.docsLeft = docsLeft;
-
- this.docsTop = docsTop;
-
- scene.resize(sceneWidth, sceneHeight + 200);
-
- this.translate(docsLeft, docsTop);
-
- return this;
- }
-
- override getEngine() {
- return (this.getScene() as Scene).getEngine();
- }
+ // calculatePagePosition() {
+ // const scene = this.getScene() as Scene;
- // enableEditor() {
- // if (this._hasEditor) {
- // return;
+ // const parent = scene?.getParent();
+ // const { width: docsWidth, height: docsHeight, pageMarginLeft, pageMarginTop } = this;
+ // if (parent == null || docsWidth === Infinity || docsHeight === Infinity) {
+ // return this;
// }
+ // const { width: engineWidth, height: engineHeight } = parent;
+ // let docsLeft = 0;
+ // let docsTop = 0;
- // this._editor = DocsEditor.create(this);
- // this._hasEditor = true;
- // }
+ // let sceneWidth = 0;
- // disableEditor() {
- // this._editor?.dispose();
- // this._hasEditor = false;
- // }
+ // let sceneHeight = 0;
- // getEditorInputEvent() {
- // if (!this._hasEditor || this._editor == null) {
- // return;
+ // if (engineWidth > docsWidth) {
+ // docsLeft = engineWidth / 2 - docsWidth / 2;
+ // sceneWidth = engineWidth - 30;
+ // } else {
+ // docsLeft = pageMarginLeft;
+ // sceneWidth = docsWidth + pageMarginLeft * 2;
// }
- // const {
- // onInputObservable,
- // onCompositionstartObservable,
- // onCompositionupdateObservable,
- // onCompositionendObservable,
- // onKeydownObservable,
- // onSelectionStartObservable,
- // } = this._editor;
- // return {
- // onInputObservable,
- // onCompositionstartObservable,
- // onCompositionupdateObservable,
- // onCompositionendObservable,
- // onKeydownObservable,
- // onSelectionStartObservable,
- // };
- // }
- // override remainActiveSelection() {
- // if (!this._hasEditor) {
- // return;
+ // if (engineHeight > docsHeight) {
+ // docsTop = engineHeight / 2 - docsHeight / 2;
+ // sceneHeight = engineHeight - 30;
+ // } else {
+ // docsTop = pageMarginTop;
+ // sceneHeight = docsHeight + pageMarginTop * 2;
// }
- // return this._editor?.remain();
- // }
- // addSelection(textSelection: TextSelection) {
- // if (!this._hasEditor) {
- // return;
- // }
- // return this._editor?.add(textSelection);
- // }
+ // this.docsLeft = docsLeft;
- // override syncSelection() {
- // if (!this._hasEditor) {
- // return;
- // }
+ // this.docsTop = docsTop;
- // return this._editor?.sync();
- // }
+ // scene.resize(sceneWidth, sceneHeight + 200);
- // override scrollBySelection() {
- // if (this._hasEditor == null) {
- // return;
- // }
+ // this.translate(docsLeft, docsTop);
- // this._editor?.scroll();
+ // return this;
// }
- // eslint-disable-next-line max-lines-per-function
+ override getEngine() {
+ return (this.getScene() as Scene).getEngine();
+ }
+
override draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
const documentSkeleton = this.getSkeleton();
if (!documentSkeleton) {
@@ -271,8 +190,8 @@ export class Documents extends DocComponent {
extension.clearCache();
}
+ // broadcasting the pageTop and pageLeft for each page in the document with multiple pages.
let pageTop = 0;
-
let pageLeft = 0;
for (let i = 0, len = pages.length; i < len; i++) {
@@ -283,8 +202,8 @@ export class Documents extends DocComponent {
marginBottom: pagePaddingBottom = 0,
marginLeft: pagePaddingLeft = 0,
marginRight: pagePaddingRight = 0,
- width: pageWidth,
- height: pageHeight,
+ width: actualWidth,
+ height: actualHeight,
renderConfig = {},
} = page;
const {
@@ -297,13 +216,13 @@ export class Documents extends DocComponent {
} = renderConfig;
const horizontalOffsetNoAngle = this._horizontalHandler(
- pageWidth,
+ actualWidth,
pagePaddingLeft,
pagePaddingRight,
horizontalAlign
);
const verticalOffsetNoAngle = this._verticalHandler(
- pageHeight,
+ actualHeight,
pagePaddingTop,
pagePaddingBottom,
verticalAlign
@@ -500,224 +419,12 @@ export class Documents extends DocComponent {
}
changeSkeleton(newSkeleton: DocumentSkeleton) {
- this._disposeSkeletonChangeObserver(this.getSkeleton());
+ // this._disposeSkeletonChangeObserver(this.getSkeleton());
this.setSkeleton(newSkeleton);
- this._addSkeletonChangeObserver(newSkeleton);
+ // this._addSkeletonChangeObserver(newSkeleton);
return this;
}
- // eslint-disable-next-line max-lines-per-function
- // override findNodeByCoord(offsetX: number, offsetY: number): Nullable<INodeInfo> {
- // const scene = this.getScene() as Scene;
- // const originCoord = scene.transformToSceneCoord(Vector2.FromArray([offsetX, offsetY]));
-
- // if (!originCoord) {
- // return;
- // }
-
- // const coord = this._getInverseCoord(originCoord);
- // const { x, y } = coord;
- // const skeleton = this.getSkeleton();
-
- // if (!skeleton) {
- // return;
- // }
-
- // this._findLiquid.reset();
-
- // const skeletonData = skeleton.getSkeletonData();
-
- // if (skeletonData == null) {
- // return;
- // }
-
- // const pages = skeletonData.pages;
-
- // let nearestNodeList: INodeInfo[] = [];
-
- // let nearestNodeDistanceList: number[] = [];
-
- // let nearestNodeDistanceY = Infinity;
-
- // for (let i = 0, len = pages.length; i < len; i++) {
- // const page = pages[i];
-
- // const { startX, startY, endX, endY } = this._getPageBoundingBox(page);
-
- // if (!(x >= startX && x <= endX && y >= startY && y <= endY)) {
- // this._translatePage(page);
- // continue;
- // }
-
- // this._findLiquid.translatePagePadding(page);
-
- // const sections = page.sections;
-
- // for (const section of sections) {
- // const { columns, height } = section;
-
- // this._findLiquid.translateSection(section);
-
- // const { y: startY } = this._findLiquid;
-
- // // if (!(y >= startY && y <= startY + height)) {
- // // continue;
- // // }
-
- // for (const column of columns) {
- // const { lines, width: columnWidth } = column;
-
- // this._findLiquid.translateColumn(column);
-
- // const { x: startX } = this._findLiquid;
-
- // // if (!(x >= startX && x <= startX + columnWidth)) {
- // // continue;
- // // }
-
- // const linesCount = lines.length;
-
- // for (let i = 0; i < linesCount; i++) {
- // const line = lines[i];
- // const { divides, type, lineHeight = 0 } = line;
-
- // if (type === LineType.BLOCK) {
- // continue;
- // } else {
- // this._findLiquid.translateSave();
- // this._findLiquid.translateLine(line);
-
- // const { y: startY } = this._findLiquid;
-
- // const startY_fin = startY;
-
- // const endY_fin = startY + lineHeight;
-
- // const distanceY = Math.abs(y - endY_fin);
-
- // // if (!(y >= startY_fin && y <= endY_fin)) {
- // // this._findLiquid.translateRestore();
- // // continue;
- // // }
-
- // const divideLength = divides.length;
- // for (let i = 0; i < divideLength; i++) {
- // const divide = divides[i];
- // const { spanGroup, width: divideWidth } = divide;
-
- // this._findLiquid.translateSave();
- // this._findLiquid.translateDivide(divide);
-
- // const { x: startX } = this._findLiquid;
-
- // // if (!(x >= startX && x <= startX + divideWidth)) {
- // // this._findLiquid.translateRestore();
- // // continue;
- // // }
-
- // for (const span of spanGroup) {
- // if (!span.content || span.content.length === 0) {
- // continue;
- // }
-
- // const { width: spanWidth, left: spanLeft } = span;
-
- // const startX_fin = startX + spanLeft;
-
- // const endX_fin = startX + spanLeft + spanWidth;
-
- // const distanceX = Math.abs(x - endX_fin);
-
- // if (y >= startY_fin && y <= endY_fin) {
- // if (x >= startX_fin && x <= endX_fin) {
- // return {
- // node: span,
- // ratioX: x / (startX_fin + endX_fin),
- // ratioY: y / (startY_fin + endY_fin),
- // };
- // }
-
- // if (nearestNodeDistanceY !== -Infinity) {
- // nearestNodeList = [];
- // nearestNodeDistanceList = [];
- // }
- // nearestNodeList.push({
- // node: span,
- // ratioX: x / (startX_fin + endX_fin),
- // ratioY: y / (startY_fin + endY_fin),
- // });
-
- // nearestNodeDistanceList.push(distanceX);
-
- // nearestNodeDistanceY = -Infinity;
- // continue;
- // }
-
- // if (distanceY < nearestNodeDistanceY) {
- // nearestNodeDistanceY = distanceY;
- // nearestNodeList = [];
- // nearestNodeDistanceList = [];
- // }
-
- // if (distanceY === nearestNodeDistanceY) {
- // nearestNodeList.push({
- // node: span,
- // ratioX: x / (startX_fin + endX_fin),
- // ratioY: y / (startY_fin + endY_fin),
- // });
-
- // nearestNodeDistanceList.push(distanceX);
- // }
- // }
- // this._findLiquid.translateRestore();
- // }
- // this._findLiquid.translateRestore();
- // }
- // }
- // }
- // }
- // this._findLiquid.restorePagePadding(page);
- // this._translatePage(page);
- // }
-
- // return this._getNearestNode(nearestNodeList, nearestNodeDistanceList);
- // }
-
- // override findCoordByNode(span: IDocumentSkeletonSpan) {
- // const divide = span.parent;
- // const defaultCoordinate = {
- // x: -Infinity,
- // y: -Infinity,
- // };
- // if (divide == null) {
- // return defaultCoordinate;
- // }
-
- // const line = divide.parent;
-
- // if (line == null) {
- // return defaultCoordinate;
- // }
-
- // const column = line.parent;
-
- // if (column == null) {
- // return defaultCoordinate;
- // }
-
- // const section = column.parent;
-
- // if (section == null) {
- // return defaultCoordinate;
- // }
-
- // const page = section.parent;
-
- // if (page == null) {
- // return defaultCoordinate;
- // }
- // }
-
protected override _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
this.draw(ctx, bounds);
}
@@ -771,44 +478,44 @@ export class Documents extends DocComponent {
});
}
- private _addSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
- if (!skeleton) {
- return;
- }
+ // private _addSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
+ // if (!skeleton) {
+ // return;
+ // }
- this._skeletonObserver = skeleton.onRecalculateChangeObservable.add((data) => {
- const pages = data.pages;
- let width = 0;
- let height = 0;
- for (let i = 0, len = pages.length; i < len; i++) {
- const page = pages[i];
- const { pageWidth, pageHeight } = page;
- if (this.pageLayoutType === PageLayoutType.VERTICAL) {
- height += pageHeight;
- if (i !== len - 1) {
- height += this.pageMarginTop;
- }
- width = Math.max(width, pageWidth);
- } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
- width += pageWidth;
- if (i !== len - 1) {
- width += this.pageMarginLeft;
- }
- height = Math.max(height, pageHeight);
- }
- }
+ // this._skeletonObserver = skeleton.onRecalculateChangeObservable.add((data) => {
+ // const pages = data.pages;
+ // let width = 0;
+ // let height = 0;
+ // for (let i = 0, len = pages.length; i < len; i++) {
+ // const page = pages[i];
+ // const { pageWidth, pageHeight } = page;
+ // if (this.pageLayoutType === PageLayoutType.VERTICAL) {
+ // height += pageHeight;
+ // if (i !== len - 1) {
+ // height += this.pageMarginTop;
+ // }
+ // width = Math.max(width, pageWidth);
+ // } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
+ // width += pageWidth;
+ // if (i !== len - 1) {
+ // width += this.pageMarginLeft;
+ // }
+ // height = Math.max(height, pageHeight);
+ // }
+ // }
- this.resize(width, height);
- this.calculatePagePosition();
- });
- }
+ // this.resize(width, height);
+ // this.calculatePagePosition();
+ // });
+ // }
- private _disposeSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
- if (!skeleton) {
- return;
- }
- skeleton.onRecalculateChangeObservable.remove(this._skeletonObserver);
- }
+ // private _disposeSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
+ // if (!skeleton) {
+ // return;
+ // }
+ // skeleton.onRecalculateChangeObservable.remove(this._skeletonObserver);
+ // }
// private _getPageBoundingBox(page: IDocumentSkeletonPage) {
// const { pageWidth, pageHeight } = page;
diff --git a/packages/base-render/src/Component/Docs/text-selection-render-manager.ts b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
index 3794790e41..207b0d60e2 100644
--- a/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
+++ b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
@@ -3,7 +3,7 @@ import { createIdentifier } from '@wendellhu/redi';
import { BehaviorSubject, Observable } from 'rxjs';
import { CURSOR_TYPE } from '../../Basics/Const';
-import { IDocumentSkeletonCached, PageLayoutType } from '../../Basics/IDocumentSkeletonCached';
+import { PageLayoutType } from '../../Basics/IDocumentSkeletonCached';
import { IMouseEvent, IPointerEvent } from '../../Basics/IEvents';
import { INodeInfo, INodePosition } from '../../Basics/Interfaces';
import { getOffsetRectForDom, transformBoundingCoord } from '../../Basics/Position';
@@ -34,6 +34,8 @@ export interface ITextSelectionRenderManager {
readonly textSelection$: Observable<TextSelection[]>;
+ getViewPort(): Viewport;
+
enableSelection(): void;
disableSelection(): void;
@@ -74,7 +76,11 @@ export interface ITextSelectionRenderManager {
getActiveRange(): Nullable<ITextSelectionRangeWithStyle>;
- eventTrigger(evt: IPointerEvent | IMouseEvent, documentOffsetConfig: IDocumentOffsetConfig): void;
+ eventTrigger(
+ evt: IPointerEvent | IMouseEvent,
+ documentOffsetConfig: IDocumentOffsetConfig,
+ viewport: Nullable<Viewport>
+ ): void;
}
export interface IEditorInputConfig {
@@ -143,7 +149,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
- private _skeletonObserver: Nullable<Observer<IDocumentSkeletonCached>>;
+ // private _skeletonObserver: Nullable<Observer<IDocumentSkeletonCached>>;
private _viewportScrollX: number = 0;
@@ -151,8 +157,6 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private _textSelectionList: TextSelection[] = [];
- private _activeViewport: Nullable<Viewport>;
-
private _currentSegmentId: string = '';
private _documentOffsetConfig: IDocumentOffsetConfig = {
@@ -177,22 +181,29 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private _isIMEInputApply = false;
+ private _activeViewport!: Viewport;
+
constructor(
private _docSkeleton?: Nullable<DocumentSkeleton>,
- private _scene?: Nullable<Scene>
+ private _scene?: Nullable<Scene>,
+ viewport?: Nullable<Viewport>
) {
super();
this._initDOM();
// this.activeViewport = this._documents?.getFirstViewport();
if (this._docSkeleton && this._scene) {
- this.changeRuntime(this._docSkeleton, this._scene);
+ this.changeRuntime(this._docSkeleton, this._scene, viewport);
}
}
- set activeViewport(viewport: Nullable<Viewport>) {
- this._attachScrollEvent(viewport);
- this._activeViewport = viewport;
+ // set activeViewport(viewport: Nullable<Viewport>) {
+ // this._attachScrollEvent(viewport);
+ // this._activeViewport = viewport;
+ // }
+
+ getViewPort() {
+ return this._activeViewport;
}
setSegment(id: string) {
@@ -353,19 +364,23 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
}
}
- changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene) {
- this._docSkeleton?.onRecalculateChangeObservable.remove(this._skeletonObserver);
+ changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene, viewport?: Nullable<Viewport>) {
+ // this._docSkeleton?.onRecalculateChangeObservable.remove(this._skeletonObserver);
this._docSkeleton = docSkeleton;
this._scene = scene;
- this.activeViewport = scene.getViewports()[0];
+ this._activeViewport = viewport || scene.getViewports()[0];
// this._attachSelectionEvent(this._documents);
}
- eventTrigger(evt: IPointerEvent | IMouseEvent, documentOffsetConfig: IDocumentOffsetConfig) {
+ eventTrigger(
+ evt: IPointerEvent | IMouseEvent,
+ documentOffsetConfig: IDocumentOffsetConfig,
+ viewportMain: Nullable<Viewport>
+ ) {
// this._moveInObserver = documents.onPointerEnterObserver.add(() => {
// documents.cursor = CURSOR_TYPE.TEXT;
// });
@@ -383,10 +398,17 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
return;
}
+ if (viewportMain != null) {
+ this._activeViewport = viewportMain;
+ }
+
const scene = this._scene;
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- this.activeViewport = scene.getActiveViewportByCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+
+ this._attachScrollEvent(
+ viewportMain || scene.getActiveViewportByCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]))
+ );
this._documentOffsetConfig = documentOffsetConfig;
@@ -414,8 +436,6 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._activeSelectionRefresh();
- this._syncDomToSelection();
-
scene.disableEvent();
const scrollTimer = ScrollTimer.create(scene);
@@ -454,6 +474,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._textSelection$.next(this.getTextSelectionList());
scrollTimer.dispose();
+ this._syncDomToSelection();
});
// state.stopPropagation();
@@ -785,7 +806,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
}
private _attachScrollEvent(viewport: Nullable<Viewport>) {
- if (!viewport) {
+ if (viewport == null) {
return;
}
const key = viewport.viewPortKey;
@@ -918,12 +939,11 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private _getTransformCoordForDocumentOffset(evtOffsetX: number, evtOffsetY: number) {
const { documentTransform } = this._documentOffsetConfig;
- if (this._scene == null || documentTransform == null) {
+ if (this._activeViewport == null || documentTransform == null) {
return;
}
- this.activeViewport = this._scene.getActiveViewportByCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
- const originCoord = this._scene.transformToSceneCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const originCoord = this._activeViewport.getRelativeVector(Vector2.FromArray([evtOffsetX, evtOffsetY]));
if (!originCoord) {
return;
@@ -948,7 +968,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
// documents.onPointerEnterObserver.remove(this._moveInObserver);
// documents.onPointerLeaveObserver.remove(this._moveOutObserver);
// documents.onPointerDownObserver.remove(this._downObserver);
- this._docSkeleton?.onRecalculateChangeObservable.remove(this._skeletonObserver);
+ // this._docSkeleton?.onRecalculateChangeObservable.remove(this._skeletonObserver);
this._onKeydown$.complete();
this._onInput$.complete();
this._onCompositionstart$.complete();
diff --git a/packages/base-render/src/Component/Sheets/Extensions/Font.ts b/packages/base-render/src/Component/Sheets/Extensions/Font.ts
index f193bfa8b0..16524cd6fa 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/Font.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/Font.ts
@@ -1,8 +1,9 @@
import { HorizontalAlign, IColorStyle, IScale, ObjectMatrix, WrapStrategy } from '@univerjs/core';
import { fixLineWidthByScale } from '../../../Basics/Tools';
+import { Documents } from '../..';
import { SpreadsheetExtensionRegistry } from '../../Extension';
-import { fontCacheItem } from '../Interfaces';
+import { IFontCacheItem } from '../Interfaces';
import { SheetComponent } from '../SheetComponent';
import { SpreadsheetSkeleton } from '../SheetSkeleton';
import { SheetExtension } from './SheetExtension';
@@ -143,7 +144,7 @@ export class Font extends SheetExtension {
private _renderDocuments(
ctx: CanvasRenderingContext2D,
- docsConfig: fontCacheItem,
+ docsConfig: IFontCacheItem,
startX: number,
startY: number,
endX: number,
@@ -151,7 +152,7 @@ export class Font extends SheetExtension {
row: number,
column: number
) {
- const documents = this.getDocuments();
+ const documents = this.getDocuments() as Documents;
if (documents == null) {
throw new Error('documents is null');
diff --git a/packages/base-render/src/Component/Sheets/Interfaces.ts b/packages/base-render/src/Component/Sheets/Interfaces.ts
index 4a4e5b63d7..8d0cb0ac61 100644
--- a/packages/base-render/src/Component/Sheets/Interfaces.ts
+++ b/packages/base-render/src/Component/Sheets/Interfaces.ts
@@ -13,7 +13,7 @@ export interface BorderCacheItem {
color: string;
}
-export interface fontCacheItem {
+export interface IFontCacheItem {
documentSkeleton: DocumentSkeleton;
// marginTop?: number;
// marginBottom?: number;
@@ -31,7 +31,7 @@ interface backgroundCache {
}
interface fontCache {
- [key: string]: ObjectMatrix<fontCacheItem>;
+ [key: string]: ObjectMatrix<IFontCacheItem>;
}
export interface IStylesCache {
diff --git a/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
index 4ae15133f2..29d3d23926 100644
--- a/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
@@ -42,8 +42,10 @@ export interface ISelectionTransformerShapeManager {
enableSelection(): void;
disableSelection(): void;
+ getViewPort(): Viewport;
+
addControlToCurrentByRangeData(data: ISelectionWithCoordAndStyle): void;
- changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene): void;
+ changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene, viewport?: Viewport): void;
// getSpreadsheet(): void;
// getMaxIndex(): void;
getScene(): void;
@@ -119,6 +121,8 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
readonly selectionRangeWithStyle$ = this._selectionRangeWithStyle$.asObservable();
+ private _activeViewport!: Viewport;
+
static create() {
return new SelectionTransformerShapeManager();
}
@@ -155,6 +159,10 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
this._isSelectionEnabled = false;
}
+ getViewPort() {
+ return this._activeViewport;
+ }
+
/**
* add a selection
* @param selectionRange
@@ -200,9 +208,10 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
currentControls.push(control);
}
- changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene) {
+ changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene, viewport?: Viewport) {
this._skeleton = skeleton;
this._scene = scene;
+ this._activeViewport = viewport || scene.getViewports()[0];
}
// getSpreadsheet() {
@@ -355,6 +364,10 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
return;
}
+ if (viewport != null) {
+ this._activeViewport = viewport;
+ }
+
const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
let { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
@@ -504,10 +517,10 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl, rangeType, viewport);
+ this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl, rangeType);
scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl, rangeType, viewport);
+ this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl, rangeType);
});
});
@@ -615,8 +628,7 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
moveOffsetX: number,
moveOffsetY: number,
selectionControl: Nullable<SelectionTransformerShape>,
- rangeType: RANGE_TYPE,
- viewport?: Viewport
+ rangeType: RANGE_TYPE
) {
const skeleton = this._skeleton;
@@ -630,7 +642,7 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
const scrollXY = scene.getScrollXYByRelativeCoords(
Vector2.FromArray([this._startOffsetX, this._startOffsetY]),
- viewport
+ this._activeViewport
);
const { scaleX, scaleY } = scene.getAncestorScale();
diff --git a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
index 91f5a52c68..3cd0d6b30f 100644
--- a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
+++ b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
@@ -1,5 +1,7 @@
import {
BooleanNumber,
+ DocumentModel,
+ DocumentModelOrSimple,
DocumentModelSimple,
getColorStyle,
HorizontalAlign,
@@ -87,8 +89,26 @@ interface IRowColumnSegment {
endColumn: number;
}
+export interface IDocumentLayoutObject {
+ documentModel: Nullable<DocumentModelOrSimple>;
+ fontString: string;
+ textRotation: ITextRotation;
+ wrapStrategy: WrapStrategy;
+ verticalAlign: VerticalAlign;
+ horizontalAlign: HorizontalAlign;
+ paddingData: IPaddingData;
+ fill?: Nullable<string>;
+}
+
const DEFAULT_ROTATE_ANGLE = 90;
+const DEFAULT_PADDING_DATA = {
+ t: 0,
+ b: 0,
+ l: 2,
+ r: 2,
+};
+
export class SpreadsheetSkeleton extends Skeleton {
private _rowHeightAccumulation: number[] = [];
@@ -420,8 +440,8 @@ export class SpreadsheetSkeleton extends Skeleton {
// console.log('documentSkeleton', cell?.v, column, endColumn, row, column, columnCount, contentWidth);
if (horizontalAlign === HorizontalAlign.CENTER) {
- startColumn = this._getOverflowBound(row, column, 0, contentWidth / 2);
- endColumn = this._getOverflowBound(row, column, columnCount - 1, contentWidth / 2);
+ startColumn = this._getOverflowBound(row, column, 0, contentWidth / 2, horizontalAlign);
+ endColumn = this._getOverflowBound(row, column, columnCount - 1, contentWidth / 2, horizontalAlign);
} else if (horizontalAlign === HorizontalAlign.RIGHT) {
startColumn = this._getOverflowBound(row, column, 0, contentWidth);
} else {
@@ -485,6 +505,15 @@ export class SpreadsheetSkeleton extends Skeleton {
};
}
+ /**
+ *
+ * @param offsetX HTML coordinate system, mouse position x.
+ * @param offsetY HTML coordinate system, mouse position y.
+ * @param scaleX render scene scale x-axis, scene.getAncestorScale
+ * @param scaleY render scene scale y-axis, scene.getAncestorScale
+ * @param scrollXY render viewport scroll {x, y}, scene.getScrollXYByRelativeCoords, scene.getScrollXY
+ * @returns Selection data with coordinates
+ */
calculateCellIndexByPosition(
offsetX: number,
offsetY: number,
@@ -499,12 +528,12 @@ export class SpreadsheetSkeleton extends Skeleton {
/**
*
- * @param offsetX scaled offset x
- * @param offsetY scaled offset y
- * @param scaleX scale x
- * @param scaleY scale y
- * @param scrollXY
- * @returns
+ * @param offsetX HTML coordinate system, mouse position x.
+ * @param offsetY HTML coordinate system, mouse position y.
+ * @param scaleX render scene scale x-axis, scene.getAncestorScale
+ * @param scaleY render scene scale y-axis, scene.getAncestorScale
+ * @param scrollXY render viewport scroll {x, y}, scene.getScrollXYByRelativeCoords, scene.getScrollXY
+ * @returns Hit cell coordinates
*/
getCellPositionByOffset(
offsetX: number,
@@ -762,7 +791,65 @@ export class SpreadsheetSkeleton extends Skeleton {
return this.getMergeBounding(startRow, startColumn, endRow, endColumn);
}
- getCellModel(row: number, column: number) {
+ getBlankCellDocumentModel(row: number, column: number, isFull: boolean = false): IDocumentLayoutObject {
+ const documentModelObject = this.getCellDocumentModel(row, column);
+
+ if (documentModelObject != null) {
+ if (documentModelObject.documentModel == null) {
+ documentModelObject.documentModel = this._getDocumentDataByStyle('', {}, {}, isFull);
+ }
+ return documentModelObject;
+ }
+
+ const content = '';
+
+ let fontString = 'document';
+
+ const textRotation: ITextRotation = { a: 0, v: BooleanNumber.FALSE };
+ const horizontalAlign: HorizontalAlign = HorizontalAlign.UNSPECIFIED;
+ const verticalAlign: VerticalAlign = VerticalAlign.UNSPECIFIED;
+ const wrapStrategy: WrapStrategy = WrapStrategy.UNSPECIFIED;
+ const paddingData: IPaddingData = DEFAULT_PADDING_DATA;
+
+ fontString = getFontStyleString({}, this._localService).fontCache;
+
+ const documentModel = this._getDocumentDataByStyle(content, {}, {}, isFull);
+
+ return {
+ documentModel,
+ fontString,
+ textRotation,
+ wrapStrategy,
+ verticalAlign,
+ horizontalAlign,
+ paddingData,
+ };
+ }
+
+ // convert canvas content position to physical position in screen
+ convertTransformToOffsetX(offsetX: number, scaleX: number, scrollXY: { x: number; y: number }) {
+ const { x: scrollX } = scrollXY;
+
+ offsetX = (offsetX - scrollX) * scaleX;
+
+ return offsetX;
+ }
+
+ // convert canvas content position to physical position in screen
+ convertTransformToOffsetY(offsetY: number, scaleY: number, scrollXY: { x: number; y: number }) {
+ const { x: scrollY } = scrollXY;
+
+ offsetY = (offsetY - scrollY) * scaleY;
+
+ return offsetY;
+ }
+
+ getCellDocumentModel(
+ row: number,
+ column: number,
+ isFull: boolean = false,
+ isDeepClone: boolean = false
+ ): Nullable<IDocumentLayoutObject> {
const cell = this._cellData.getValue(row, column);
const style = this._styles.getStyleByCell(cell);
if (!cell) {
@@ -773,16 +860,12 @@ export class SpreadsheetSkeleton extends Skeleton {
let documentModel: Nullable<DocumentModelSimple>;
let fontString = 'document';
const cellOtherConfig = this._getOtherStyle(style) as CellOtherConfig;
- // const {
- // textRotation = { a: 0, v: BooleanNumber.FALSE },
- // horizontalAlign = HorizontalAlign.UNSPECIFIED,
- // verticalAlign = VerticalAlign.UNSPECIFIED,
- // wrapStrategy = WrapStrategy.UNSPECIFIED,
- // }= CellOtherConfig;
+
const textRotation: ITextRotation = cellOtherConfig.textRotation || { a: 0, v: BooleanNumber.FALSE };
const horizontalAlign: HorizontalAlign = cellOtherConfig.horizontalAlign || HorizontalAlign.UNSPECIFIED;
const verticalAlign: VerticalAlign = cellOtherConfig.verticalAlign || VerticalAlign.UNSPECIFIED;
const wrapStrategy: WrapStrategy = cellOtherConfig.wrapStrategy || WrapStrategy.UNSPECIFIED;
+ const paddingData: IPaddingData = cellOtherConfig.paddingData || DEFAULT_PADDING_DATA;
if (cell.p) {
const { a: angle = 0, v: isVertical = BooleanNumber.FALSE } = textRotation;
let centerAngle = 0;
@@ -791,20 +874,38 @@ export class SpreadsheetSkeleton extends Skeleton {
centerAngle = DEFAULT_ROTATE_ANGLE;
vertexAngle = DEFAULT_ROTATE_ANGLE;
}
- documentModel = this._updateRenderConfigAndHorizon(cell.p, horizontalAlign, {
+ documentModel = this._updateRenderConfigAndHorizon(
+ isDeepClone ? Tools.deepClone(cell.p) : cell.p,
horizontalAlign,
- verticalAlign,
- centerAngle,
- vertexAngle,
- wrapStrategy,
- });
+ {
+ horizontalAlign,
+ verticalAlign,
+ centerAngle,
+ vertexAngle,
+ wrapStrategy,
+ },
+ isFull
+ );
} else if (content) {
const textStyle = this._getFontFormat(style);
fontString = getFontStyleString(textStyle, this._localService).fontCache;
- documentModel = this._getDocumentDataByStyle(content.toString(), textStyle, cellOtherConfig);
+ documentModel = this._getDocumentDataByStyle(content.toString(), textStyle, cellOtherConfig, isFull);
}
+ /**
+ * the alignment mode is returned with respect to the offset of the sheet cell,
+ * because the document needs to render the layout for cells and
+ * support alignment across multiple cells (e.g., horizontal alignment of long text in overflow mode).
+ * The alignment mode of the document itself cannot meet this requirement,
+ * so an additional renderConfig needs to be added during the rendering of the document component.
+ * This means that there are two coexisting alignment modes.
+ * In certain cases, such as in an editor, conflicts may arise,
+ * requiring only one alignment mode to be retained.
+ * By removing the relevant configurations in renderConfig,
+ * the alignment mode of the sheet cell can be modified.
+ * The alternative alignment mode is applied to paragraphs within the document.
+ */
return {
documentModel,
fontString,
@@ -812,6 +913,8 @@ export class SpreadsheetSkeleton extends Skeleton {
wrapStrategy,
verticalAlign,
horizontalAlign,
+ paddingData,
+ fill: style?.bg?.rgb,
};
}
@@ -998,66 +1101,20 @@ export class SpreadsheetSkeleton extends Skeleton {
};
}
- // private _calculateOverflowCache() {
- // const { font: fontList } = this.stylesCache;
- // // const mergeRangeCache = this._getMergeRangeCache();
- // const overflowCache = new ObjectMatrix<IRange>();
- // const columnCount = this.getColumnCount();
- // fontList &&
- // Object.keys(fontList).forEach((fontFormat: string) => {
- // const fontObjectArray = fontList[fontFormat];
- // fontObjectArray.forEach((row, fontArray) => {
- // fontArray.forEach((column, docsSkeleton) => {
- // // overflow handler
- // const { documentSkeleton, angle, verticalAlign, horizontalAlign, wrapStrategy } = docsSkeleton;
- // const cell = this._cellData.getValue(row, column);
- // if (wrapStrategy !== WrapStrategy.OVERFLOW || cell?.n === BooleanNumber.TRUE) {
- // return true;
- // }
-
- // if (horizontalAlign === HorizontalAlign.JUSTIFIED) {
- // return true;
- // }
-
- // let contentSize = documentSkeleton.getLastPageSize(angle);
-
- // if (!contentSize) {
- // return true;
- // }
-
- // // if(angle!==0){
- // // contentSize = {
- // // width: contentSize.width,
-
- // // }
- // // }
-
- // const position = this.getOverflowPosition(contentSize, horizontalAlign, row, column, columnCount);
-
- // const { startColumn, endColumn } = position;
- // overflowCache.setValue(row, column, {
- // startRow: row,
- // endRow: row,
- // startColumn,
- // endColumn,
- // });
-
- // // console.log('appendToOverflowCache', angle, contentSize, { row, column, startColumn, endColumn });
- // });
- // });
- // });
-
- // return overflowCache;
- // }
-
- private _getOverflowBound(row: number, startColumn: number, endColumn: number, contentWidth: number) {
+ private _getOverflowBound(
+ row: number,
+ startColumn: number,
+ endColumn: number,
+ contentWidth: number,
+ horizontalAlign = HorizontalAlign.LEFT
+ ) {
let cumWidth = 0;
if (startColumn > endColumn) {
const columnCount = this._columnWidthAccumulation.length - 1;
for (let i = startColumn; i >= endColumn; i--) {
const column = i;
const cell = this._cellData.getValue(row, column);
- if ((!isEmptyCell(cell) && column !== startColumn) || this._intersectMergeRange(row, column)) {
+ if ((!isEmptyCell(cell) && column !== startColumn) || this.intersectMergeRange(row, column)) {
if (column === startColumn) {
return column;
}
@@ -1069,7 +1126,14 @@ export class SpreadsheetSkeleton extends Skeleton {
this.rowHeightAccumulation,
this.columnWidthAccumulation
);
- cumWidth += endX - startX;
+
+ // For center alignment, the current cell's width needs to be divided in half for comparison.
+ if (horizontalAlign === HorizontalAlign.CENTER && column === startColumn) {
+ cumWidth += (endX - startX) / 2;
+ } else {
+ cumWidth += endX - startX;
+ }
+
if (contentWidth < cumWidth) {
return column;
}
@@ -1079,7 +1143,7 @@ export class SpreadsheetSkeleton extends Skeleton {
for (let i = startColumn; i <= endColumn; i++) {
const column = i;
const cell = this._cellData.getValue(row, column);
- if ((!isEmptyCell(cell) && column !== startColumn) || this._intersectMergeRange(row, column)) {
+ if ((!isEmptyCell(cell) && column !== startColumn) || this.intersectMergeRange(row, column)) {
if (column === startColumn) {
return column;
}
@@ -1092,7 +1156,13 @@ export class SpreadsheetSkeleton extends Skeleton {
this.rowHeightAccumulation,
this.columnWidthAccumulation
);
- cumWidth += endX - startX;
+
+ if (horizontalAlign === HorizontalAlign.CENTER && column === startColumn) {
+ cumWidth += (endX - startX) / 2;
+ } else {
+ cumWidth += endX - startX;
+ }
+
if (contentWidth < cumWidth) {
return column;
}
@@ -1100,9 +1170,8 @@ export class SpreadsheetSkeleton extends Skeleton {
return endColumn;
}
- private _intersectMergeRange(row: number, column: number) {
+ intersectMergeRange(row: number, column: number) {
const dataMergeCache = this.dataMergeCache;
- let isIntersected = false;
for (const dataCache of dataMergeCache) {
const {
startRow: startRowMargeIndex,
@@ -1116,8 +1185,7 @@ export class SpreadsheetSkeleton extends Skeleton {
column >= startColumnMargeIndex &&
column <= endColumnMargeIndex
) {
- isIntersected = true;
- return false;
+ return true;
}
}
// dataMergeCache?.forEach((r, dataMergeRow) => {
@@ -1125,7 +1193,7 @@ export class SpreadsheetSkeleton extends Skeleton {
// });
// });
- return isIntersected;
+ return false;
}
// private _getMergeRangeCache() {
@@ -1228,7 +1296,7 @@ export class SpreadsheetSkeleton extends Skeleton {
this._setBorderProps(r, c, BORDER_TYPE.RIGHT, style, cache);
}
- const modelObject = this.getCellModel(r, c);
+ const modelObject = this.getCellDocumentModel(r, c);
if (modelObject == null) {
return;
@@ -1267,24 +1335,25 @@ export class SpreadsheetSkeleton extends Skeleton {
}
private _updateRenderConfigAndHorizon(
- document: IDocumentData,
+ documentData: IDocumentData,
horizontalAlign: HorizontalAlign,
- renderConfig?: IDocumentRenderConfig
+ renderConfig?: IDocumentRenderConfig,
+ isFull: boolean = false
) {
if (!renderConfig) {
return;
}
- if (!document.body?.dataStream) {
+ if (!documentData.body?.dataStream) {
return;
}
- if (!document.documentStyle) {
- document.documentStyle = {};
+ if (!documentData.documentStyle) {
+ documentData.documentStyle = {};
}
- document.documentStyle.renderConfig = renderConfig;
+ documentData.documentStyle.renderConfig = renderConfig;
- const paragraphs = document.body.paragraphs || [];
+ const paragraphs = documentData.body.paragraphs || [];
for (const paragraph of paragraphs) {
if (!paragraph.paragraphStyle) {
@@ -1294,10 +1363,18 @@ export class SpreadsheetSkeleton extends Skeleton {
paragraph.paragraphStyle.horizontalAlign = horizontalAlign;
}
- return new DocumentModelSimple(document);
+ if (isFull === false) {
+ return new DocumentModelSimple(documentData);
+ }
+ return new DocumentModel(documentData);
}
- private _getDocumentDataByStyle(content: string, textStyle: ITextStyle, config: CellOtherConfig) {
+ private _getDocumentDataByStyle(
+ content: string,
+ textStyle: ITextStyle,
+ config: CellOtherConfig,
+ isFull: boolean = false
+ ) {
const contentLength = content.length;
const {
textRotation = { a: 0, v: BooleanNumber.FALSE },
@@ -1362,7 +1439,10 @@ export class SpreadsheetSkeleton extends Skeleton {
},
};
- return new DocumentModelSimple(documentData);
+ if (isFull === false) {
+ return new DocumentModelSimple(documentData);
+ }
+ return new DocumentModel(documentData);
}
private _setBorderProps(r: number, c: number, type: BORDER_TYPE, style: IStyleData, cache: IStylesCache) {
@@ -1431,6 +1511,12 @@ export class SpreadsheetSkeleton extends Skeleton {
};
}
+ /**
+ * Cache the merged cells on the current screen to improve computational performance.
+ * @param mergeData all marge data
+ * @param rowColumnSegment current screen range, include row and column
+ * @returns
+ */
private _getMergeCells(mergeData: IRange[], rowColumnSegment?: IRowColumnSegment) {
// const rowColumnSegment = this._rowColumnSegment;
const endColumnLast = this.columnWidthAccumulation.length - 1;
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index d9b2a1177a..7a35cc4fe5 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -310,6 +310,12 @@ export class Spreadsheet extends SheetComponent {
// this._hasSelection = false;
// }
+ /**
+ * Obtain the height and width of a cell's text, taking into account scenarios with rotated text.
+ * @param documentSkeleton Data of the document's ViewModel
+ * @param angle The rotation angle of an Excel cell
+ * @returns
+ */
getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angle: number = 0) {
const skeletonData = documentSkeleton?.getSkeletonData();
@@ -528,7 +534,11 @@ export class Spreadsheet extends SheetComponent {
// return horizontalAlign;
// }
- // eslint-disable-next-line max-lines-per-function
+ /**
+ * Calculate the overflow of cell text. If there is no value on either side of the cell,
+ * the text content of this cell can be drawn to both sides, not limited by the cell's width.
+ * Overflow on the left or right is aligned according to the text's horizontal alignment.
+ */
private _calculateOverflow() {
const overflowCache = new ObjectMatrix<IRange>();
const spreadsheetSkeleton = this.getSkeleton();
@@ -542,107 +552,104 @@ export class Spreadsheet extends SheetComponent {
fontList &&
Object.keys(fontList).forEach((fontFormat: string) => {
const fontObjectArray = fontList[fontFormat];
- fontObjectArray.forEach((row, fontArray) => {
- fontArray.forEach((column, docsConfig) => {
- // wrap and angle handler
- const {
- documentSkeleton,
- angle = 0,
- verticalAlign,
- horizontalAlign,
- wrapStrategy,
- } = docsConfig;
- const cell = spreadsheetSkeleton.getCellData().getValue(row, column);
-
- const sheetSkeleton = this.getSkeleton();
- if (!sheetSkeleton) {
- return true;
- }
-
- const { t: cellValueType = CellValueType.STRING } = cell || {};
+ fontObjectArray.forValue((row, column, docsConfig) => {
+ // Merged cells do not support overflow.
+ if (spreadsheetSkeleton.intersectMergeRange(row, column)) {
+ return true;
+ }
- if (
- wrapStrategy === WrapStrategy.OVERFLOW &&
- cellValueType !== CellValueType.NUMBER &&
- cellValueType !== CellValueType.BOOLEAN &&
- horizontalAlign !== HorizontalAlign.JUSTIFIED
- ) {
- let contentSize = this.getDocsSkeletonPageSize(documentSkeleton, angle);
+ // wrap and angle handler
+ const { documentSkeleton, angle = 0, verticalAlign, horizontalAlign, wrapStrategy } = docsConfig;
+ const cell = spreadsheetSkeleton.getCellData().getValue(row, column);
- if (!contentSize) {
- return true;
- }
+ const sheetSkeleton = this.getSkeleton();
+ if (!sheetSkeleton) {
+ return true;
+ }
- if (angle !== 0) {
- const { startY, endY, startX, endX } = getCellByIndex(
- row,
- column,
- rowHeightAccumulation,
- columnWidthAccumulation,
- mergeData
- );
- const cellWidth = endX - startX;
- const cellHeight = endY - startY;
-
- if (contentSize.height > cellHeight) {
- contentSize = {
- width: cellHeight / Math.tan(Math.abs(angle)) + cellWidth,
- height: cellHeight,
- };
- // if (angle > 0) {
- // horizontalAlign = HorizontalAlign.LEFT;
- // } else {
- // horizontalAlign = HorizontalAlign.RIGHT;
- // }
- }
- }
+ const { t: cellValueType = CellValueType.STRING } = cell || {};
- const position = spreadsheetSkeleton.getOverflowPosition(
- contentSize,
- horizontalAlign,
- row,
- column,
- columnCount
- );
+ if (
+ wrapStrategy === WrapStrategy.OVERFLOW &&
+ cellValueType !== CellValueType.NUMBER &&
+ cellValueType !== CellValueType.BOOLEAN &&
+ horizontalAlign !== HorizontalAlign.JUSTIFIED
+ ) {
+ let contentSize = this.getDocsSkeletonPageSize(documentSkeleton, angle);
- const { startColumn, endColumn } = position;
+ if (!contentSize) {
+ return true;
+ }
- overflowCache.setValue(row, column, {
- startRow: row,
- endRow: row,
- startColumn,
- endColumn,
- });
- } else if (wrapStrategy === WrapStrategy.WRAP && angle !== 0) {
- const { startY, endY } = getCellByIndex(
+ if (angle !== 0) {
+ const { startY, endY, startX, endX } = getCellByIndex(
row,
column,
rowHeightAccumulation,
columnWidthAccumulation,
mergeData
);
-
+ const cellWidth = endX - startX;
const cellHeight = endY - startY;
- documentSkeleton.getModel().updateDocumentDataPageSize(cellHeight);
- documentSkeleton.calculate();
- const contentSize = this.getDocsSkeletonPageSize(documentSkeleton, angle);
- if (!contentSize) {
- return true;
+ if (contentSize.height > cellHeight) {
+ contentSize = {
+ width: cellHeight / Math.tan(Math.abs(angle)) + cellWidth,
+ height: cellHeight,
+ };
+ // if (angle > 0) {
+ // horizontalAlign = HorizontalAlign.LEFT;
+ // } else {
+ // horizontalAlign = HorizontalAlign.RIGHT;
+ // }
}
+ }
- const { startColumn, endColumn } = sheetSkeleton.getOverflowPosition(
- contentSize,
- horizontalAlign,
- row,
- column,
- sheetSkeleton.getColumnCount()
- );
- overflowCache.setValue(row, column, { startRow: row, endRow: row, startColumn, endColumn });
+ const position = spreadsheetSkeleton.getOverflowPosition(
+ contentSize,
+ horizontalAlign,
+ row,
+ column,
+ columnCount
+ );
+
+ const { startColumn, endColumn } = position;
+
+ overflowCache.setValue(row, column, {
+ startRow: row,
+ endRow: row,
+ startColumn,
+ endColumn,
+ });
+ } else if (wrapStrategy === WrapStrategy.WRAP && angle !== 0) {
+ const { startY, endY } = getCellByIndex(
+ row,
+ column,
+ rowHeightAccumulation,
+ columnWidthAccumulation,
+ mergeData
+ );
+
+ const cellHeight = endY - startY;
+ documentSkeleton.getModel().updateDocumentDataPageSize(cellHeight);
+ documentSkeleton.calculate();
+ const contentSize = this.getDocsSkeletonPageSize(documentSkeleton, angle);
+
+ if (!contentSize) {
+ return true;
}
- // console.log('appendToOverflowCache', cellHeight, angle, contentSize, { rowIndex, columnIndex, startColumn, endColumn });
- });
+ const { startColumn, endColumn } = sheetSkeleton.getOverflowPosition(
+ contentSize,
+ horizontalAlign,
+ row,
+ column,
+ sheetSkeleton.getColumnCount()
+ );
+ overflowCache.setValue(row, column, { startRow: row, endRow: row, startColumn, endColumn });
+ }
+
+ // console.log('appendToOverflowCache', cellHeight, angle, contentSize, { rowIndex, columnIndex, startColumn, endColumn });
});
});
diff --git a/packages/base-render/src/Render-manager.service.ts b/packages/base-render/src/Render-manager.service.ts
index fa705b0619..4de8654aab 100644
--- a/packages/base-render/src/Render-manager.service.ts
+++ b/packages/base-render/src/Render-manager.service.ts
@@ -21,6 +21,7 @@ export interface IRenderManagerService {
setCurrent(unitId: string): void;
getCurrent(): Nullable<IRender>;
getRenderById(unitId: string): Nullable<IRender>;
+ getRenderAll(): Map<string, IRender>;
defaultEngine: Engine;
}
@@ -147,6 +148,10 @@ export class RenderManagerService implements IRenderManagerService {
return this._renderMap.get(unitId);
}
+ getRenderAll() {
+ return this._renderMap;
+ }
+
private _disposeItem(item: Nullable<IRender>, shouldDestroyEngine: boolean = true) {
if (item == null) {
return;
diff --git a/packages/base-render/src/Scene.ts b/packages/base-render/src/Scene.ts
index 450e4e8d85..a2d9f68a69 100644
--- a/packages/base-render/src/Scene.ts
+++ b/packages/base-render/src/Scene.ts
@@ -534,11 +534,21 @@ export class Scene extends ThinScene {
}
getScrollXYByRelativeCoords(coord: Vector2, viewPort?: Viewport) {
- let x = 0;
- let y = 0;
if (!viewPort) {
viewPort = this.getActiveViewportByRelativeCoord(coord);
}
+ if (!viewPort) {
+ return {
+ x: 0,
+ y: 0,
+ };
+ }
+ return this.getScrollXY(viewPort);
+ }
+
+ getScrollXY(viewPort: Viewport) {
+ let x = 0;
+ let y = 0;
if (viewPort) {
const actualX = viewPort.actualScrollX || 0;
const actualY = viewPort.actualScrollY || 0;
@@ -584,10 +594,10 @@ export class Scene extends ThinScene {
return coord;
}
- transformToSceneCoord(coord: Vector2) {
- const pickedViewport = this.getActiveViewportByCoord(coord);
- return pickedViewport?.getRelativeVector(coord);
- }
+ // transformToSceneCoord(coord: Vector2) {
+ // const pickedViewport = this.getActiveViewportByCoord(coord);
+ // return pickedViewport?.getRelativeVector(coord);
+ // }
clearLayer() {
this._layers = [];
diff --git a/packages/base-render/src/Shape/ScrollBar.ts b/packages/base-render/src/Shape/ScrollBar.ts
index f5335ff5d3..51bec9996d 100644
--- a/packages/base-render/src/Shape/ScrollBar.ts
+++ b/packages/base-render/src/Shape/ScrollBar.ts
@@ -1,4 +1,4 @@
-import { EventState, Nullable } from '@univerjs/core';
+import { EventState, Nullable, Observer } from '@univerjs/core';
import { COLORS, EVENT_TYPE } from '../Basics/Const';
import { IMouseEvent, IPointerEvent } from '../Basics/IEvents';
@@ -47,6 +47,14 @@ export class ScrollBar extends BaseScrollBar {
private _isVerticalMove = false;
+ private _horizonPointerMoveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _horizonPointerUpObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _verticalPointerMoveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _verticalPointerUpObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
constructor(view: Viewport, props?: IScrollBarProps) {
super(props);
if (!view) {
@@ -61,6 +69,16 @@ export class ScrollBar extends BaseScrollBar {
return new ScrollBar(view, props);
}
+ override dispose() {
+ super.dispose();
+ this._mainScene?.onPointerMoveObserver.remove(this._horizonPointerMoveObserver);
+ this._mainScene?.onPointerMoveObserver.remove(this._verticalPointerMoveObserver);
+ this._mainScene?.onPointerUpObserver.remove(this._horizonPointerUpObserver);
+ this._mainScene?.onPointerUpObserver.remove(this._verticalPointerUpObserver);
+ this._mainScene = null;
+ this._view.removeScrollBar();
+ }
+
override render(ctx: CanvasRenderingContext2D, left: number = 0, top: number = 0) {
const { scrollX, scrollY } = this._view;
ctx.save();
@@ -299,7 +317,7 @@ export class ScrollBar extends BaseScrollBar {
this.makeViewDirty(true);
state.stopPropagation();
});
- mainScene.on(EVENT_TYPE.PointerMove, (evt: unknown, state: EventState) => {
+ this._verticalPointerMoveObserver = mainScene.on(EVENT_TYPE.PointerMove, (evt: unknown, state: EventState) => {
const e = evt as IPointerEvent | IMouseEvent;
if (!this._isVerticalMove) {
return;
@@ -309,7 +327,7 @@ export class ScrollBar extends BaseScrollBar {
});
this._lastY = e.offsetY;
});
- mainScene.on(EVENT_TYPE.PointerUp, (evt: unknown, state: EventState) => {
+ this._verticalPointerUpObserver = mainScene.on(EVENT_TYPE.PointerUp, (evt: unknown, state: EventState) => {
const e = evt as IPointerEvent | IMouseEvent;
const srcElement = this.verticalThumbRect;
this._isVerticalMove = false;
@@ -378,7 +396,7 @@ export class ScrollBar extends BaseScrollBar {
mainScene.disableEvent();
state.stopPropagation();
});
- mainScene.on(EVENT_TYPE.PointerMove, (evt: unknown, state: EventState) => {
+ this._horizonPointerMoveObserver = mainScene.on(EVENT_TYPE.PointerMove, (evt: unknown, state: EventState) => {
const e = evt as IPointerEvent | IMouseEvent;
if (!this._isHorizonMove) {
return;
@@ -388,7 +406,7 @@ export class ScrollBar extends BaseScrollBar {
});
this._lastX = e.offsetX;
});
- mainScene.on(EVENT_TYPE.PointerUp, (evt: unknown, state: EventState) => {
+ this._horizonPointerUpObserver = mainScene.on(EVENT_TYPE.PointerUp, (evt: unknown, state: EventState) => {
const e = evt as IPointerEvent | IMouseEvent;
const srcElement = this.horizonThumbRect;
this._isHorizonMove = false;
diff --git a/packages/base-render/src/Viewport.ts b/packages/base-render/src/Viewport.ts
index d7fdcc19eb..0b02afba21 100644
--- a/packages/base-render/src/Viewport.ts
+++ b/packages/base-render/src/Viewport.ts
@@ -287,6 +287,10 @@ export class Viewport {
this._resizeCacheCanvasAndScrollBar();
}
+ removeScrollBar() {
+ this._scrollBar = null;
+ }
+
resize(position: IViewPosition) {
const positionKeys = Object.keys(position);
if (positionKeys.length === 0) {
diff --git a/packages/base-sheets/src/Controller/Selection.controller.ts b/packages/base-sheets/src/Controller/Selection.controller.ts
index 3e51a4d43f..90db5c0ac7 100644
--- a/packages/base-sheets/src/Controller/Selection.controller.ts
+++ b/packages/base-sheets/src/Controller/Selection.controller.ts
@@ -202,7 +202,9 @@ export class SelectionController extends Disposable {
const { scene } = currentRender;
- this._selectionTransformerShapeManager.changeRuntime(skeleton, scene);
+ const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+
+ this._selectionTransformerShapeManager.changeRuntime(skeleton, scene, viewportMain);
this._selectionManagerService.setCurrentSelection({
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
diff --git a/packages/base-sheets/src/Controller/editor-bridge.controller.ts b/packages/base-sheets/src/Controller/editor-bridge.controller.ts
deleted file mode 100644
index eb3eac35f9..0000000000
--- a/packages/base-sheets/src/Controller/editor-bridge.controller.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import {
- DeviceInputEventType,
- DocumentSkeleton,
- IMouseEvent,
- IPointerEvent,
- IRenderManagerService,
- ISelectionTransformerShapeManager,
-} from '@univerjs/base-render';
-import {
- Disposable,
- ICommandService,
- IUniverInstanceService,
- LifecycleStages,
- LocaleService,
- OnLifecycle,
-} from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
-import { Nullable } from 'vitest';
-
-import { getSheetObject } from '../Basics/component-tools';
-import { IEditorBridgeService } from '../services/editor-bridge.service';
-import { SelectionManagerService } from '../services/selection-manager.service';
-import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
-
-@OnLifecycle(LifecycleStages.Rendered, EditorBridgeController)
-export class EditorBridgeController extends Disposable {
- constructor(
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @ISelectionTransformerShapeManager
- private readonly _selectionTransformerShapeManager: ISelectionTransformerShapeManager,
- @Inject(LocaleService) protected readonly _localService: LocaleService
- ) {
- super();
-
- this._initialize();
-
- this._commandExecutedListener();
- }
-
- override dispose(): void {}
-
- private _initialize() {
- this._initialSelectionListener();
-
- this._initialDblclickListener();
- }
-
- private _initialSelectionListener() {
- this._selectionManagerService.selectionInfo$.subscribe((params) => {
- const currentSkeletonManager = this._sheetSkeletonManagerService.getCurrent();
- this._editorBridgeService.hide();
- if (currentSkeletonManager == null) {
- return;
- }
-
- const { skeleton, unitId, sheetId } = currentSkeletonManager;
-
- if (params == null || params.length === 0 || skeleton == null) {
- return;
- }
-
- const { primary } = params[params.length - 1];
-
- if (primary == null) {
- return;
- }
-
- const { startRow, startColumn } = primary;
-
- const primaryWithCoord = this._selectionTransformerShapeManager.convertCellRangeToInfo(primary);
-
- if (primaryWithCoord == null) {
- return;
- }
-
- let documentSkeleton: Nullable<DocumentSkeleton> = null;
-
- const documentModel = skeleton.getCellModel(startRow, startColumn)?.documentModel;
-
- if (documentModel != null) {
- documentSkeleton = DocumentSkeleton.create(documentModel, this._localService);
- }
-
- this._editorBridgeService.setState({
- primaryWithCoord,
- unitId,
- sheetId,
- docSkeleton: documentSkeleton,
- });
- });
- }
-
- private _initialDblclickListener() {
- const sheetObject = this._getSheetObject();
- if (sheetObject == null) {
- return;
- }
-
- const { spreadsheet } = sheetObject;
-
- spreadsheet.onDblclickObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._editorBridgeService.show(DeviceInputEventType.Dblclick);
- // const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- // const scene = this._getSheetObject()?.scene;
- // if (scene == null || skeleton == null) {
- // return;
- // }
- // const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- // const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
- // const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords);
- // const { scaleX, scaleY } = scene.getAncestorScale();
- // const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
- // const selectionData = this._getSelectedRangeWithMerge(
- // newEvtOffsetX,
- // newEvtOffsetY,
- // scaleX,
- // scaleY,
- // scrollXY
- // );
- // if (!selectionData) {
- // return false;
- // }
- // const { rangeWithCoord: actualRangeWithCoord, primaryWithCoord } = selectionData;
- // const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualRangeWithCoord;
- });
- }
-
- private _getSheetObject() {
- return getSheetObject(this._currentUniverService, this._renderManagerService);
- }
-
- private _commandExecutedListener() {}
-}
diff --git a/packages/base-sheets/src/Controller/sheet-render.controller.ts b/packages/base-sheets/src/Controller/sheet-render.controller.ts
index abc0599342..43e6367263 100644
--- a/packages/base-sheets/src/Controller/sheet-render.controller.ts
+++ b/packages/base-sheets/src/Controller/sheet-render.controller.ts
@@ -39,6 +39,9 @@ interface ISetWorksheetMutationParams {
@OnLifecycle(LifecycleStages.Rendered, SheetRenderController)
export class SheetRenderController extends Disposable {
+ private _previousUnitId: string = '';
+ private _previousSheetId: string = '';
+
constructor(
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@@ -81,6 +84,9 @@ export class SheetRenderController extends Disposable {
return;
}
+ this._previousUnitId = unitId;
+ this._previousSheetId = sheetId;
+
const { mainComponent, components, scene } = currentRender;
const spreadsheet = mainComponent as Spreadsheet;
@@ -134,6 +140,14 @@ export class SheetRenderController extends Disposable {
return;
}
+ if (this._previousUnitId === unitId && this._previousSheetId === sheetId) {
+ return;
+ }
+
+ this._previousUnitId = unitId;
+
+ this._previousSheetId = sheetId;
+
if (command.id !== SetWorksheetActivateMutation.id) {
this._sheetSkeletonManagerService.makeDirty(
{
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index 2534ff4c33..adecb94ff5 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -6,7 +6,6 @@ import { SetScrollOperation } from './commands/operations/scroll.operation';
import { SetSelectionsOperation } from './commands/operations/selection.operation';
import { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
import { BasicWorksheetController } from './Controller/BasicWorksheet.controller';
-import { EditorBridgeController } from './Controller/editor-bridge.controller';
import { FormulaBarController } from './Controller/FormulaBarController';
import { FreezeController } from './Controller/freeze.controller';
import { HeaderMenuController } from './Controller/header-menu.controller';
@@ -19,7 +18,6 @@ import { SheetRenderController } from './Controller/sheet-render.controller';
import { ZoomController } from './Controller/zoom.controller';
import { en } from './Locale';
import { BorderStyleManagerService } from './services/border-style-manager.service';
-import { EditorBridgeService, IEditorBridgeService } from './services/editor-bridge.service';
import { ScrollManagerService } from './services/scroll-manager.service';
import { SelectionManagerService } from './services/selection-manager.service';
import { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
@@ -65,7 +63,6 @@ export class SheetPlugin extends Plugin {
},
],
[ScrollManagerService],
- [IEditorBridgeService, { useClass: EditorBridgeService }],
// controllers
[FormulaBarController],
@@ -79,7 +76,6 @@ export class SheetPlugin extends Plugin {
[FreezeController],
[ScrollController],
[ZoomController],
- [EditorBridgeController],
];
dependencies.forEach((d) => {
diff --git a/packages/base-sheets/src/View/sheet-canvas-view.ts b/packages/base-sheets/src/View/sheet-canvas-view.ts
index 26a08e8277..e2e9fdb66a 100644
--- a/packages/base-sheets/src/View/sheet-canvas-view.ts
+++ b/packages/base-sheets/src/View/sheet-canvas-view.ts
@@ -39,6 +39,10 @@ export class SheetCanvasView {
private _currentWorkbook!: Workbook;
+ private _loadedMap = new Set();
+
+ private _isLoadedEditor = false;
+
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@@ -52,8 +56,31 @@ export class SheetCanvasView {
return;
// throw new Error('workbook is null');
}
- this._currentWorkbook = workbook;
- this._addNewRender();
+
+ const unitId = workbook.getUnitId();
+ if (!this._loadedMap.has(unitId)) {
+ this._currentWorkbook = workbook;
+ this._addNewRender();
+ this._loadedMap.add(unitId);
+ }
+
+ // if (!this._isLoadedEditor) {
+ // // create univer doc normal editor instance
+
+ // this._currentUniverService.createDoc({
+ // id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ // documentStyle: {},
+ // });
+
+ // // create univer doc formula bar editor instance
+
+ // this._currentUniverService.createDoc({
+ // id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ // documentStyle: {},
+ // });
+
+ // this._isLoadedEditor = true;
+ // }
});
}
@@ -76,7 +103,6 @@ export class SheetCanvasView {
} else {
this._renderManagerService.createRender(unitId);
}
- this._renderManagerService.setCurrent(unitId);
const currentRender = this._renderManagerService.getRenderById(unitId);
@@ -104,6 +130,8 @@ export class SheetCanvasView {
scene.render();
});
}
+
+ this._renderManagerService.setCurrent(unitId);
}
private _addComponent(currentRender: IRender) {
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 87ce2fea76..8016f9a878 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -140,10 +140,5 @@ export { SetScrollOperation } from './commands/operations/scroll.operation';
export { SetSelectionsOperation } from './commands/operations/selection.operation';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
export * from './Locale';
-export {
- EditorBridgeService,
- IEditorBridgeService,
- type IEditorBridgeServiceVisibleParam,
-} from './services/editor-bridge.service';
-
+export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
// #endregion
diff --git a/packages/base-slides/src/View/Render/Adaptors/DocsAdaptor.ts b/packages/base-slides/src/View/Render/Adaptors/DocsAdaptor.ts
index f3651ce315..45ad20992d 100644
--- a/packages/base-slides/src/View/Render/Adaptors/DocsAdaptor.ts
+++ b/packages/base-slides/src/View/Render/Adaptors/DocsAdaptor.ts
@@ -131,7 +131,7 @@ export class DocsAdaptor extends ObjectAdaptor {
scene.addObject(documents);
- documents.calculatePagePosition();
+ // documents.calculatePagePosition();
// documents.enableEditor();
diff --git a/packages/base-ui/src/services/shortcut/keycode.ts b/packages/base-ui/src/services/shortcut/keycode.ts
index 9f9139db85..7dcacc736b 100644
--- a/packages/base-ui/src/services/shortcut/keycode.ts
+++ b/packages/base-ui/src/services/shortcut/keycode.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-magic-numbers */
// Useful keyboard event inspection tool https://www.toptal.com/developers/keycode
/** KeyCode that maps to browser standard keycode. */
diff --git a/packages/core/src/Docs/Domain/DataStreamTreeNode.ts b/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
index f07f02b762..ea25fc64f8 100644
--- a/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
+++ b/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
@@ -26,6 +26,14 @@ export class DataStreamTreeNode {
return new DataStreamTreeNode(nodeType, content);
}
+ dispose() {
+ this.children.forEach((child) => {
+ child.dispose();
+ });
+ this.parent = null;
+ this.blocks = [];
+ }
+
getProps() {
return {
children: this.children,
diff --git a/packages/core/src/Docs/Domain/DocumentBodyModel.ts b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
index 2fd0db6f5f..51e9f6c3bc 100644
--- a/packages/core/src/Docs/Domain/DocumentBodyModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
@@ -28,6 +28,9 @@ export class DocumentBodyModelSimple implements IDisposable {
dispose(): void {
this._modelChange$.complete();
+ this.children.forEach((child) => {
+ child.dispose();
+ });
}
resetCache() {}
@@ -61,6 +64,14 @@ export class DocumentBodyModelSimple implements IDisposable {
return 0;
}
+ getLastIndex() {
+ return this.children[this.children.length - 1].endIndex;
+ }
+
+ getBody() {
+ return this.body;
+ }
+
protected _transformToTree(dataStream: string) {
const dataStreamLen = dataStream.length;
diff --git a/packages/core/src/Docs/Domain/DocumentModel.ts b/packages/core/src/Docs/Domain/DocumentModel.ts
index 4b3213be3d..cc198f5e78 100644
--- a/packages/core/src/Docs/Domain/DocumentModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentModel.ts
@@ -1,5 +1,6 @@
import { Tools } from '../../Shared/Tools';
-import { IDocumentData } from '../../Types/Interfaces/IDocumentData';
+import { IDocumentData, IDocumentRenderConfig } from '../../Types/Interfaces/IDocumentData';
+import { IPaddingData } from '../../Types/Interfaces/IStyleData';
import { DocumentBodyModel } from './DocumentBodyModel';
export const DEFAULT_DOC = {
@@ -49,6 +50,18 @@ export class DocumentModelSimple {
return this.snapshot.body;
}
+ dispose() {
+ this.bodyModel.dispose();
+
+ this.headerTreeMap.forEach((headerTree) => {
+ headerTree.dispose();
+ });
+
+ this.footerTreeMap.forEach((headerTree) => {
+ headerTree.dispose();
+ });
+ }
+
getShouldRenderLoopImmediately() {
const should = this.snapshot.shouldStartRenderingImmediately;
return should !== false;
@@ -82,6 +95,42 @@ export class DocumentModelSimple {
return this.snapshot;
}
+ updateDocumentId(unitId: string) {
+ this.snapshot.id = unitId;
+ }
+
+ updateDocumentRenderConfig(config: IDocumentRenderConfig) {
+ const documentStyle = this.snapshot.documentStyle;
+ if (documentStyle.renderConfig == null) {
+ documentStyle.renderConfig = config;
+ } else {
+ documentStyle.renderConfig = {
+ ...documentStyle.renderConfig,
+ ...config,
+ };
+ }
+ }
+
+ updateDocumentDataMargin(data: IPaddingData) {
+ const { t, l, b, r } = data;
+ const documentStyle = this.snapshot.documentStyle;
+ if (t != null) {
+ documentStyle.marginTop = t;
+ }
+
+ if (l != null) {
+ documentStyle.marginLeft = l;
+ }
+
+ if (b != null) {
+ documentStyle.marginBottom = b;
+ }
+
+ if (r != null) {
+ documentStyle.marginRight = r;
+ }
+ }
+
updateDocumentDataPageSize(width?: number, height?: number) {
const documentStyle = this.snapshot.documentStyle;
if (!documentStyle.pageSize) {
@@ -148,13 +197,18 @@ export class DocumentModel extends DocumentModelSimple {
this.snapshot = { ...DEFAULT_DOC, ...snapshot };
this._initializeRowColTree();
- this.bodyModel.reset(snapshot.body ?? { dataStream: '\r\n\0' });
+ this.bodyModel.reset(snapshot.body ?? { dataStream: '\r\n' });
}
getUnitId(): string {
return this._unitId;
}
+ override updateDocumentId(unitId: string) {
+ super.updateDocumentId(unitId);
+ this._unitId = unitId;
+ }
+
private _initializeRowColTree() {
this.headerTreeMap = new Map();
this.footerTreeMap = new Map();
diff --git a/packages/core/src/Shared/Common.ts b/packages/core/src/Shared/Common.ts
index bb5b6868b5..1ccb334083 100644
--- a/packages/core/src/Shared/Common.ts
+++ b/packages/core/src/Shared/Common.ts
@@ -106,7 +106,7 @@ export function isEmptyCell(cell: Nullable<ICellData>) {
return true;
}
- const content = cell?.m || '';
+ const content = cell?.m || cell?.v?.toString() || '';
if (content.length === 0 && !cell.p) {
return true;
}
diff --git a/packages/core/src/Shared/KeyboardUtil.ts b/packages/core/src/Shared/KeyboardUtil.ts
deleted file mode 100644
index 1c9292b690..0000000000
--- a/packages/core/src/Shared/KeyboardUtil.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { KEYBOARD_KEYS } from '../Types/Const/KEYBOARD_KEYS';
-
-const allKeys = Object.keys(KEYBOARD_KEYS).reduce(
- (acc, category) => [...acc, ...KEYBOARD_KEYS[category]],
- [] as string[]
-);
-
-/**
- * Reference of non-printable Keyboard Event.key values
- *
- * https://www.aarongreenlee.com/blog/list-of-non-printable-keys-for-keyboard-events-when-using-event-key/
- */
-export function isKeyPrintable(key: string) {
- return allKeys.indexOf(key) === -1;
-}
diff --git a/packages/core/src/Shared/index.ts b/packages/core/src/Shared/index.ts
index 67a26089c7..973898122c 100644
--- a/packages/core/src/Shared/index.ts
+++ b/packages/core/src/Shared/index.ts
@@ -13,7 +13,6 @@ export * from './GroupModel';
export * from './HashAlgorithm';
export * from './IOHttp';
export * from './IOSocket';
-export * from './KeyboardUtil';
export * from './Locale';
export * from './Logger';
export * from './LRU/index';
diff --git a/packages/core/src/Types/Const/KEYBOARD_KEYS.ts b/packages/core/src/Types/Const/KEYBOARD_KEYS.ts
deleted file mode 100644
index 8fdbecd0f6..0000000000
--- a/packages/core/src/Types/Const/KEYBOARD_KEYS.ts
+++ /dev/null
@@ -1,338 +0,0 @@
-/**
- *
- * Reference of non-printable Keyboard Event.key values
- *
- * reference:https://www.aarongreenlee.com/blog/list-of-non-printable-keys-for-keyboard-events-when-using-event-key/
- */
-export const KEYBOARD_KEYS: { [key: string]: string[] } = {
- modifier: [
- 'Alt', //The Alt (Alternative) key. This key enables the alternate modifier function for interpreting concurrent or subsequent keyboard input. .This key value is also used for the Apple Option key.
- 'AltGraph', //The Alternate Graphics (AltGr or AltGraph) key. This key is used enable the ISO Level 3 shift modifier (the standard Shift key is the level 2 modifier). See [ISO9995-1].
- 'CapsLock', //The Caps Lock (Capital) key. Toggle capital character lock function for interpreting subsequent keyboard input event.
- 'Control', //The Control or Ctrl key, to enable control modifier function for interpreting concurrent or subsequent keyboard input.
- 'Fn', //The Function switch Fn key. Activating this key simultaneously with another key changes that key’s value to an alternate character or function. This key is often handled directly in the keyboard hardware and does not usually generate key events.
- 'FnLock', //The Function-Lock (FnLock or F-Lock) key. Activating this key switches the mode of the keyboard to changes some keys' values to an alternate character or function. This key is often handled directly in the keyboard hardware and does not usually generate key events.
- 'Meta', //The Meta key, to enable meta modifier function for interpreting concurrent or subsequent keyboard input. This key value is used for the Windows Logo key and the Apple Command or ⌘ key.
- 'NumLock', //The NumLock or Number Lock key, to toggle numpad mode function for interpreting subsequent keyboard input.
- 'ScrollLock', //The Scroll Lock key, to toggle between scrolling and cursor movement modes.
- 'Shift', //The Shift key, to enable shift modifier function for interpreting concurrent or subsequent keyboard input.
- 'Symbol', //The Symbol modifier key (used on some virtual keyboards).
- 'SymbolLock', //The Symbol Lock key.
- ],
- legacyModifier: [
- 'Hyper', //The Hyper key.
- 'Super', //The Super key.
- ],
- whiteSpace: [
- 'Enter', //The Enter or ↵ key, to activate current selection or accept current input. This key value is also used for the Return (Macintosh numpad) key. This key value is also used for the Android KEYCODE_DPAD_CENTER.
- 'Tab', //The Horizontal Tabulation Tab key. The space or spacebar key is encoded as " ".
- ],
- navigation: [
- 'ArrowDown', //The down arrow key, to navigate or traverse downward. (KEYCODE_DPAD_DOWN)
- 'ArrowLeft', //The left arrow key, to navigate or traverse leftward. (KEYCODE_DPAD_LEFT)
- 'ArrowRight', //The right arrow key, to navigate or traverse rightward. (KEYCODE_DPAD_RIGHT)
- 'ArrowUp', //The up arrow key, to navigate or traverse upward. (KEYCODE_DPAD_UP)
- 'End', //The End key, used with keyboard entry to go to the end of content (KEYCODE_MOVE_END).
- 'Home', //The Home key, used with keyboard entry, to go to start of content (KEYCODE_MOVE_HOME). For the mobile phone Home key (which goes to the phone’s main screen), use "GoHome".
- 'PageDown', //The Page Down key, to scroll down or display next page of content.
- 'PageUp', //The Page Up key, to scroll up or display previous page of content.
- ],
- editing: [
- 'Backspace', //The Backspace key. This key value is also used for the key labeled Delete on MacOS keyboards.
- 'Clear', //Remove the currently selected input.
- 'Copy', //Copy the current selection. (APPCOMMAND_COPY)
- 'CrSel', //The Cursor Select (Crsel) key.
- 'Cut', //Cut the current selection. (APPCOMMAND_CUT)
- 'Delete', //The Delete (Del) Key. This key value is also used for the key labeled Delete on MacOS keyboards when modified by the Fn key.
- 'EraseEof', //The Erase to End of Field key. This key deletes all characters from the current cursor position to the end of the current field.
- 'ExSel', //The Extend Selection (Exsel) key.
- 'Insert', //The Insert (Ins) key, to toggle between text modes for insertion or overtyping. (KEYCODE_INSERT)
- 'Paste', //The Paste key. (APPCOMMAND_PASTE)
- 'Redo', //Redo the last action. (APPCOMMAND_REDO)
- 'Undo', //Undo the last action. (APPCOMMAND_UNDO)
- ],
- ui: [
- 'Accept', //The Accept (Commit, OK) key. Accept current option or input method sequence conversion.
- 'Again', //The Again key, to redo or repeat an action.
- 'Attn', //The Attention (Attn) key.
- 'Cancel', //The Cancel key.
- 'ContextMenu', //Show the application’s context menu. This key is commonly found between the right Meta key and the right Control key.
- 'Escape', //The Esc key. This key was originally used to initiate an escape sequence, but is now more generally used to exit or "escape" the current context, such as closing a dialog or exiting full screen mode.
- 'Execute', //The Execute key.
- 'Find', //Open the Find dialog. (APPCOMMAND_FIND)
- 'Help', //Open a help dialog or toggle display of help information. (APPCOMMAND_HELP, KEYCODE_HELP)
- 'Pause', //Pause the current state or application (as appropriate). Do not use this value for the Pause button on media controllers. Use "MediaPause" instead.
- 'Play', //Play or resume the current state or application (as appropriate). Do not use this value for the Play button on media controllers. Use "MediaPlay" instead.
- 'Props', //The properties (Props) key.
- 'Select', //The Select key.
- 'ZoomIn', //The ZoomIn key. (KEYCODE_ZOOM_IN)
- 'ZoomOut', //The ZoomOut key. (KEYCODE_ZOOM_OUT)
- ],
- device: [
- 'BrightnessDown', //The Brightness Down key. Typically controls the display brightness. (KEYCODE_BRIGHTNESS_DOWN)
- 'BrightnessUp', //The Brightness Up key. Typically controls the display brightness. (KEYCODE_BRIGHTNESS_UP)
- 'Eject', //Toggle removable media to eject (open) and insert (close) state. (KEYCODE_MEDIA_EJECT)
- 'LogOff', //The LogOff key.
- 'Power', //Toggle power state. (KEYCODE_POWER) Note: Some devices might not expose this key to the operating environment.
- 'PowerOff', //The PowerOff key. Sometime called PowerDown.
- 'PrintScreen', //The Print Screen or SnapShot key, to initiate print-screen function.
- 'Hibernate', //The Hibernate key. This key saves the current state of the computer to disk so that it can be restored. The computer will then shutdown.
- 'Standby', //The Standby key. This key turns off the display and places the computer into a low-power mode without completely shutting down. It is sometimes labelled Suspend or Sleep key. (KEYCODE_SLEEP)
- 'WakeUp', //The WakeUp key. (KEYCODE_WAKEUP)
- ],
- imeCompositionKeys: [
- 'AllCandidates', //The All Candidates key, to initate the multi-candidate mode.
- 'Alphanumeric', //The Alphanumeric key.
- 'CodeInput', //The Code Input key, to initiate the Code Input mode to allow characters to be entered by their code points.
- 'Compose', //The Compose key, also known as Multi_key on the X Window System. This key acts in a manner similar to a dead key, triggering a mode where subsequent key presses are combined to produce a different character.
- 'Convert', //The Convert key, to convert the current input method sequence.
- 'Dead', //A dead key combining key. It may be any combining key from any keyboard layout. For example, on a PC/AT French keyboard, using a French mapping and without any modifier activiated, this is the key value U+0302 COMBINING CIRCUMFLEX ACCENT. In another layout this might be a different unicode combining key. For applications that need to differentiate between specific combining characters, the associated compositionupdate event’s data attribute provides the specific key value.
- 'FinalMode', //The Final Mode Final key used on some Asian keyboards, to enable the final mode for IMEs.
- 'GroupFirst', //Switch to the first character group. (ISO/IEC 9995)
- 'GroupLast', //Switch to the last character group. (ISO/IEC 9995)
- 'GroupNext', //Switch to the next character group. (ISO/IEC 9995)
- 'GroupPrevious', //Switch to the previous character group. (ISO/IEC 9995)
- 'ModeChange', //The Mode Change key, to toggle between or cycle through input modes of IMEs.
- 'NextCandidate', //The Next Candidate function key.
- 'NonConvert', //The NonConvert ("Don’t Convert") key, to accept current input method sequence without conversion in IMEs.
- 'PreviousCandidate', //The Previous Candidate function key.
- 'Process', //The Process key.
- 'SingleCandidate', //The Single Candidate function key.
- ],
- koreanSpecific: [
- 'HangulMode', //The Hangul (Korean characters) Mode key, to toggle between Hangul and English modes.
- 'HanjaMode', //The Hanja (Korean characters) Mode key.
- 'JunjaMode', //The Junja (Korean characters) Mode key.
- ],
- japaneseSpecific: [
- 'Eisu', //The Eisu key. This key may close the IME, but its purpose is defined by the current IME. (KEYCODE_EISU)
- 'Hankaku', //The (Half-Width) Characters key.
- 'Hiragana', //The Hiragana (Japanese Kana characters) key.
- 'HiraganaKatakana', //The Hiragana/Katakana toggle key. (KEYCODE_KATAKANA_HIRAGANA)
- 'KanaMode', //The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from romaji mode).
- 'KanjiMode', //The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key is typically used to switch to a hiragana keyboard for the purpose of converting input into kanji. (KEYCODE_KANA)
- 'Katakana', //The Katakana (Japanese Kana characters) key.
- 'Romaji', //The Roman characters function key.
- 'Zenkaku', //The Zenkaku (Full-Width) Characters key.
- 'ZenkakuHankaku', //The Zenkaku/Hankaku (full-width/half-width) toggle key. (KEYCODE_ZENKAKU_HANKAKU)
- ],
- // The exact number of these general purpose function keys varies on different platforms, and only the first few are defined explicitly here. Additional function key names are implicitly defined by incrementing the base-10 index at the end of the function key name. Thus, "F24" and "Soft8" are all valid key values.
- commonFunction: [
- 'F1', //The F1 key, a general purpose function key, as index 1.
- 'F2', //The F2 key, a general purpose function key, as index 2.
- 'F3', //The F3 key, a general purpose function key, as index 3.
- 'F4', //The F4 key, a general purpose function key, as index 4.
- 'F5', //The F5 key, a general purpose function key, as index 5.
- 'F6', //The F6 key, a general purpose function key, as index 6.
- 'F7', //The F7 key, a general purpose function key, as index 7.
- 'F8', //The F8 key, a general purpose function key, as index 8.
- 'F9', //The F9 key, a general purpose function key, as index 9.
- 'F10', //The F10 key, a general purpose function key, as index 10.
- 'F11', //The F11 key, a general purpose function key, as index 11.
- 'F12', //The F12 key, a general purpose function key, as index 12.
- 'Soft1', //General purpose virtual function key, as index 1.
- 'Soft2', //General purpose virtual function key, as index 2.
- 'Soft3', //General purpose virtual function key, as index 3.
- 'Soft4', //General purpose virtual function key, as index 4.
- ],
- // These are extra keys found on "multimedia" keyboards.
- multimedia: [
- 'ChannelDown', //Select next (numerically or logically) lower channel. (APPCOMMAND_MEDIA_CHANNEL_DOWN, KEYCODE_CHANNEL_DOWN)
- 'ChannelUp', //Select next (numerically or logically) higher channel. (APPCOMMAND_MEDIA_CHANNEL_UP, KEYCODE_CHANNEL_UP)
- 'Close', //Close the current document or message (Note: This doesn’t close the application). (APPCOMMAND_CLOSE)
- 'MailForward', //Open an editor to forward the current message. (APPCOMMAND_FORWARD_MAIL)
- 'MailReply', //Open an editor to reply to the current message. (APPCOMMAND_REPLY_TO_MAIL)
- 'MailSend', //Send the current message. (APPCOMMAND_SEND_MAIL)
- 'MediaClose', //Close the current media, for example to close a CD or DVD tray. (KEYCODE_MEDIA_CLOSE)
- 'MediaFastForward', //Initiate or continue forward playback at faster than normal speed, or increase speed if already fast forwarding. (APPCOMMAND_MEDIA_FAST_FORWARD, KEYCODE_MEDIA_FAST_FORWARD)
- 'MediaPause', //Pause the currently playing media. (APPCOMMAND_MEDIA_PAUSE, KEYCODE_MEDIA_PAUSE) Media controller devices should use this value rather than "Pause" for their pause keys.
- 'MediaPlay', //Initiate or continue media playback at normal speed, if not currently playing at normal speed. (APPCOMMAND_MEDIA_PLAY, KEYCODE_MEDIA_PLAY)
- 'MediaPlayPause', //Toggle media between play and pause states. (APPCOMMAND_MEDIA_PLAY_PAUSE, KEYCODE_MEDIA_PLAY_PAUSE)
- 'MediaRecord', //Initiate or resume recording of currently selected media. (APPCOMMAND_MEDIA_RECORD, KEYCODE_MEDIA_RECORD)
- 'MediaRewind', //Initiate or continue reverse playback at faster than normal speed, or increase speed if already rewinding. (APPCOMMAND_MEDIA_REWIND, KEYCODE_MEDIA_REWIND)
- 'MediaStop', //Stop media playing, pausing, forwarding, rewinding, or recording, if not already stopped. (APPCOMMAND_MEDIA_STOP, KEYCODE_MEDIA_STOP)
- 'MediaTrackNext', //Seek to next media or program track. (APPCOMMAND_MEDIA_NEXTTRACK, KEYCODE_MEDIA_NEXT)
- 'MediaTrackPrevious', //Seek to previous media or program track. (APPCOMMAND_MEDIA_PREVIOUSTRACK, KEYCODE_MEDIA_PREVIOUS)
- 'New', //Open a new document or message. (APPCOMMAND_NEW)
- 'Open', //Open an existing document or message. (APPCOMMAND_OPEN)
- 'Print', //Print the current document or message. (APPCOMMAND_PRINT)
- 'Save', //Save the current document or message. (APPCOMMAND_SAVE)
- 'SpellCheck', //Spellcheck the current document or selection. (APPCOMMAND_SPELL_CHECK)
- ],
- // The normal 0 ... 9 numpad keys are encoded as "0" ... "9", but some multimedia keypads have buttons numbered from 1 ... 12. In these instances, the 10 key is often labeled 10 /0. Note: The 10 or 10 /0 key MUST be assigned a key value of "0".
- multimediaNumpad: [
- 'Key11', //The 11 key found on media numpads that have buttons from 1 ... 12.
- 'Key12', //The 12 key found on media numpads that have buttons from 1 ... 12.
- ],
- // Multimedia keys related to audio.
- audio: [
- 'AudioBalanceLeft', //Adjust audio balance leftward. (VK_AUDIO_BALANCE_LEFT)
- 'AudioBalanceRight', //Adjust audio balance rightward. (VK_AUDIO_BALANCE_RIGHT)
- 'AudioBassBoostDown', //Decrease audio bass boost or cycle down through bass boost states. (APPCOMMAND_BASS_DOWN, VK_BASS_BOOST_DOWN)
- 'AudioBassBoostToggle', //Toggle bass boost on/off. (APPCOMMAND_BASS_BOOST)
- 'AudioBassBoostUp', //Increase audio bass boost or cycle up through bass boost states. (APPCOMMAND_BASS_UP, VK_BASS_BOOST_UP)
- 'AudioFaderFront', //Adjust audio fader towards front. (VK_FADER_FRONT)
- 'AudioFaderRear', //Adjust audio fader towards rear. (VK_FADER_REAR)
- 'AudioSurroundModeNext', //Advance surround audio mode to next available mode. (VK_SURROUND_MODE_NEXT)
- 'AudioTrebleDown', //Decrease treble. (APPCOMMAND_TREBLE_DOWN)
- 'AudioTrebleUp', //Increase treble. (APPCOMMAND_TREBLE_UP)
- 'AudioVolumeDown', //Decrease audio volume. (APPCOMMAND_VOLUME_DOWN, KEYCODE_VOLUME_DOWN)
- 'AudioVolumeUp', //Increase audio volume. (APPCOMMAND_VOLUME_UP, KEYCODE_VOLUME_UP)
- 'AudioVolumeMute', //Toggle between muted state and prior volume level. (APPCOMMAND_VOLUME_MUTE, KEYCODE_VOLUME_MUTE)
- 'MicrophoneToggle', //Toggle the microphone on/off. (APPCOMMAND_MIC_ON_OFF_TOGGLE)
- 'MicrophoneVolumeDown', //Decrease microphone volume. (APPCOMMAND_MICROPHONE_VOLUME_DOWN)
- 'MicrophoneVolumeUp', //Increase microphone volume. (APPCOMMAND_MICROPHONE_VOLUME_UP)
- 'MicrophoneVolumeMute', //Mute the microphone. (APPCOMMAND_MICROPHONE_VOLUME_MUTE, KEYCODE_MUTE)
- ],
- // Multimedia keys related to speech recognition.
- speech: [
- 'SpeechCorrectionList', //Show correction list when a word is incorrectly identified. (APPCOMMAND_CORRECTION_LIST)
- 'SpeechInputToggle', //Toggle between dictation mode and command/control mode. (APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE)
- ],
- // The Application Keys are special keys that are assigned to launch a particular application. Additional application key names can be defined by concatenating "Launch" with the name of the application.
- application: [
- 'LaunchApplication1', //The first generic "LaunchApplication" key. This is commonly associated with launching "My Computer", and may have a computer symbol on the key. (APPCOMMAND_LAUNCH_APP1)
- 'LaunchApplication2', //The second generic "LaunchApplication" key. This is commonly associated with launching "Calculator", and may have a calculator symbol on the key. (APPCOMMAND_LAUNCH_APP2, KEYCODE_CALCULATOR)
- 'LaunchCalendar', //The "Calendar" key. (KEYCODE_CALENDAR)
- 'LaunchContacts', //The "Contacts" key. (KEYCODE_CONTACTS)
- 'LaunchMail', //The "Mail" key. (APPCOMMAND_LAUNCH_MAIL)
- 'LaunchMediaPlayer', //The "Media Player" key. (APPCOMMAND_LAUNCH_MEDIA_SELECT)
- 'LaunchMusicPlayer', //The "Music Player" key.
- 'LaunchPhone', //The "Phone" key.
- 'LaunchScreenSaver', //The "Screen Saver" key.
- 'LaunchSpreadsheet', //The "Sheets" key.
- 'LaunchWebBrowser', //The "Web Browser" key.
- 'LaunchWebCam', //The "WebCam" key.
- 'LaunchWordProcessor', //The "Word Processor" key.
- ],
- browser: [
- 'BrowserBack', //Navigate to previous content or page in current history. (APPCOMMAND_BROWSER_BACKWARD)
- 'BrowserFavorites', //Open the list of browser favorites. (APPCOMMAND_BROWSER_FAVORITES)
- 'BrowserForward', //Navigate to next content or page in current history. (APPCOMMAND_BROWSER_FORWARD)
- 'BrowserHome', //Go to the user’s preferred home page. (APPCOMMAND_BROWSER_HOME)
- 'BrowserRefresh', //Refresh the current page or content. (APPCOMMAND_BROWSER_REFRESH)
- 'BrowserSearch', //Call up the user’s preferred search page. (APPCOMMAND_BROWSER_SEARCH)
- 'BrowserStop', //Stop loading the current page or content. (APPCOMMAND_BROWSER_STOP)
- ],
- mobilePhone: [
- 'AppSwitch', //The Application switch key, which provides a list of recent apps to switch between. (KEYCODE_APP_SWITCH)
- 'Call', //The Call key. (KEYCODE_CALL)
- 'Camera', //The Camera key. (KEYCODE_CAMERA)
- 'CameraFocus', //The Camera focus key. (KEYCODE_FOCUS)
- 'EndCall', //The End Call key. (KEYCODE_ENDCALL)
- 'GoBack', //The Back key. (KEYCODE_BACK)
- 'GoHome', //The Home key, which goes to the phone’s main screen. (KEYCODE_HOME)
- 'HeadsetHook', //The Headset Hook key. (KEYCODE_HEADSETHOOK)
- 'LastNumberRedial', //The Last Number Redial key.
- 'Notification', //The Notification key. (KEYCODE_NOTIFICATION)
- 'MannerMode', //Toggle between manner mode state: silent, vibrate, ring, ... (KEYCODE_MANNER_MODE)
- 'VoiceDial', //The Voice Dial key.
- ],
- tv: [
- 'TV', //Switch to viewing TV. (KEYCODE_TV)
- 'TV3DMode', //TV 3D Mode. (KEYCODE_3D_MODE)
- 'TVAntennaCable', //Toggle between antenna and cable input. (KEYCODE_TV_ANTENNA_CABLE)
- 'TVAudioDescription', //Audio description. (KEYCODE_TV_AUDIO_DESCRIPTION)
- 'TVAudioDescriptionMixDown', //Audio description mixing volume down. (KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN)
- 'TVAudioDescriptionMixUp', //Audio description mixing volume up. (KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP)
- 'TVContentsMenu', //Contents menu. (KEYCODE_TV_CONTENTS_MENU)
- 'TVDataService', //Contents menu. (KEYCODE_TV_DATA_SERVICE)
- 'TVInput', //Switch the input mode on an external TV. (KEYCODE_TV_INPUT)
- 'TVInputComponent1', //Switch to component input #1. (KEYCODE_TV_INPUT_COMPONENT_1)
- 'TVInputComponent2', //Switch to component input #2. (KEYCODE_TV_INPUT_COMPONENT_2)
- 'TVInputComposite1', //Switch to composite input #1. (KEYCODE_TV_INPUT_COMPOSITE_1)
- 'TVInputComposite2', //Switch to composite input #2. (KEYCODE_TV_INPUT_COMPOSITE_2)
- 'TVInputHDMI1', //Switch to HDMI input #1. (KEYCODE_TV_INPUT_HDMI_1)
- 'TVInputHDMI2', //Switch to HDMI input #2. (KEYCODE_TV_INPUT_HDMI_2)
- 'TVInputHDMI3', //Switch to HDMI input #3. (KEYCODE_TV_INPUT_HDMI_3)
- 'TVInputHDMI4', //Switch to HDMI input #4. (KEYCODE_TV_INPUT_HDMI_4)
- 'TVInputVGA1', //Switch to VGA input #1. (KEYCODE_TV_INPUT_VGA_1)
- 'TVMediaContext', //Media context menu. (KEYCODE_TV_MEDIA_CONTEXT_MENU)
- 'TVNetwork', //Toggle network. (KEYCODE_TV_NETWORK)
- 'TVNumberEntry', //Number entry. (KEYCODE_TV_NUMBER_ENTRY)
- 'TVPower', //Toggle the power on an external TV. (KEYCODE_TV_POWER)
- 'TVRadioService', //Radio. (KEYCODE_TV_RADIO_SERVICE)
- 'TVSatellite', //Satellite. (KEYCODE_TV_SATELLITE)
- 'TVSatelliteBS', //Broadcast Satellite. (KEYCODE_TV_SATELLITE_BS)
- 'TVSatelliteCS', //Communication Satellite. (KEYCODE_TV_SATELLITE_CS)
- 'TVSatelliteToggle', //Toggle between available satellites. (KEYCODE_TV_SATELLITE_SERVICE)
- 'TVTerrestrialAnalog', //Analog Terrestrial. (KEYCODE_TV_TERRESTRIAL_ANALOG)
- 'TVTerrestrialDigital', //Digital Terrestrial. (KEYCODE_TV_TERRESTRIAL_DIGITAL)
- 'TVTimer', //Timer programming. (KEYCODE_TV_TIMER_PROGRAMMING)
- ],
- // The key attribute values for media controllers (e.g. remote controls for television, audio systems, and set-top boxes) are derived in part from the consumer electronics technical specifications:
- mediaControls: [
- 'AVRInput', //Switch the input mode on an external AVR (audio/video receiver). (KEYCODE_AVR_INPUT)
- 'AVRPower', //Toggle the power on an external AVR (audio/video receiver). (KEYCODE_AVR_POWER)
- 'ColorF0Red', //General purpose color-coded media function key, as index 0 (red). (VK_COLORED_KEY_0, KEYCODE_PROG_RED)
- 'ColorF1Green', //General purpose color-coded media function key, as index 1 (green). (VK_COLORED_KEY_1, KEYCODE_PROG_GREEN)
- 'ColorF2Yellow', //General purpose color-coded media function key, as index 2 (yellow). (VK_COLORED_KEY_2, KEYCODE_PROG_YELLOW)
- 'ColorF3Blue', //General purpose color-coded media function key, as index 3 (blue). (VK_COLORED_KEY_3, KEYCODE_PROG_BLUE)
- 'ColorF4Grey', //General purpose color-coded media function key, as index 4 (grey). (VK_COLORED_KEY_4)
- 'ColorF5Brown', //General purpose color-coded media function key, as index 5 (brown). (VK_COLORED_KEY_5)
- 'ClosedCaptionToggle', //Toggle the display of Closed Captions. (VK_CC, KEYCODE_CAPTIONS)
- 'Dimmer', //Adjust brightness of device, by toggling between or cycling through states. (VK_DIMMER)
- 'DisplaySwap', //Swap video sources. (VK_DISPLAY_SWAP)
- 'DVR', //Select Digital Video Rrecorder. (KEYCODE_DVR)
- 'Exit', //Exit the current application. (VK_EXIT)
- 'FavoriteClear0', //Clear program or content stored as favorite 0. (VK_CLEAR_FAVORITE_0)
- 'FavoriteClear1', //Clear program or content stored as favorite 1. (VK_CLEAR_FAVORITE_1)
- 'FavoriteClear2', //Clear program or content stored as favorite 2. (VK_CLEAR_FAVORITE_2)
- 'FavoriteClear3', //Clear program or content stored as favorite 3. (VK_CLEAR_FAVORITE_3)
- 'FavoriteRecall0', //Select (recall) program or content stored as favorite 0. (VK_RECALL_FAVORITE_0)
- 'FavoriteRecall1', //Select (recall) program or content stored as favorite 1. (VK_RECALL_FAVORITE_1)
- 'FavoriteRecall2', //Select (recall) program or content stored as favorite 2. (VK_RECALL_FAVORITE_2)
- 'FavoriteRecall3', //Select (recall) program or content stored as favorite 3. (VK_RECALL_FAVORITE_3)
- 'FavoriteStore0', //Store current program or content as favorite 0. (VK_STORE_FAVORITE_0)
- 'FavoriteStore1', //Store current program or content as favorite 1. (VK_STORE_FAVORITE_1)
- 'FavoriteStore2', //Store current program or content as favorite 2. (VK_STORE_FAVORITE_2)
- 'FavoriteStore3', //Store current program or content as favorite 3. (VK_STORE_FAVORITE_3)
- 'Guide', //Toggle display of program or content guide. (VK_GUIDE, KEYCODE_GUIDE)
- 'GuideNextDay', //If guide is active and displayed, then display next day’s content. (VK_NEXT_DAY)
- 'GuidePreviousDay', //If guide is active and displayed, then display previous day’s content. (VK_PREV_DAY)
- 'Info', //Toggle display of information about currently selected context or media. (VK_INFO, KEYCODE_INFO)
- 'InstantReplay', //Toggle instant replay. (VK_INSTANT_REPLAY)
- 'Link', //Launch linked content, if available and appropriate. (VK_LINK)
- 'ListProgram', //List the current program. (VK_LIST)
- 'LiveContent', //Toggle display listing of currently available live content or programs. (VK_LIVE)
- 'Lock', //Lock or unlock current content or program. (VK_LOCK)
- 'MediaApps', //Show a list of media applications: audio/video players and image viewers. (VK_APPS) Do not confuse this key value with the Windows' VK_APPS / VK_CONTEXT_MENU key, which is encoded as "ContextMenu".
- 'MediaAudioTrack', //Audio track key. (KEYCODE_MEDIA_AUDIO_TRACK)
- 'MediaLast', //Select previously selected channel or media. (VK_LAST, KEYCODE_LAST_CHANNEL)
- 'MediaSkipBackward', //Skip backward to next content or program. (KEYCODE_MEDIA_SKIP_BACKWARD)
- 'MediaSkipForward', //Skip forward to next content or program. (VK_SKIP, KEYCODE_MEDIA_SKIP_FORWARD)
- 'MediaStepBackward', //Step backward to next content or program. (KEYCODE_MEDIA_STEP_BACKWARD)
- 'MediaStepForward', //Step forward to next content or program. (KEYCODE_MEDIA_STEP_FORWARD)
- 'MediaTopMenu', //Media top menu. (KEYCODE_MEDIA_TOP_MENU)
- 'NavigateIn', //Navigate in. (KEYCODE_NAVIGATE_IN)
- 'NavigateNext', //Navigate to next key. (KEYCODE_NAVIGATE_NEXT)
- 'NavigateOut', //Navigate out. (KEYCODE_NAVIGATE_OUT)
- 'NavigatePrevious', //Navigate to previous key. (KEYCODE_NAVIGATE_PREVIOUS)
- 'NextFavoriteChannel', //Cycle to next favorite channel (in favorites list). (VK_NEXT_FAVORITE_CHANNEL)
- 'NextUserProfile', //Cycle to next user profile (if there are multiple user profiles). (VK_USER)
- 'OnDemand', //Access on-demand content or programs. (VK_ON_DEMAND)
- 'Pairing', //Pairing key to pair devices. (KEYCODE_PAIRING)
- 'PinPDown', //Move picture-in-picture window down. (VK_PINP_DOWN)
- 'PinPMove', //Move picture-in-picture window. (VK_PINP_MOVE)
- 'PinPToggle', //Toggle display of picture-in-picture window. (VK_PINP_TOGGLE)
- 'PinPUp', //Move picture-in-picture window up. (VK_PINP_UP)
- 'PlaySpeedDown', //Decrease media playback speed. (VK_PLAY_SPEED_DOWN)
- 'PlaySpeedReset', //Reset playback to normal speed. (VK_PLAY_SPEED_RESET)
- 'PlaySpeedUp', //Increase media playback speed. (VK_PLAY_SPEED_UP)
- 'RandomToggle', //Toggle random media or content shuffle mode. (VK_RANDOM_TOGGLE)
- 'RcLowBattery', //Not a physical key, but this key code is sent when the remote control battery is low. (VK_RC_LOW_BATTERY)
- 'RecordSpeedNext', //Toggle or cycle between media recording speeds. (VK_RECORD_SPEED_NEXT)
- 'RfBypass', //Toggle RF (radio frequency) input bypass mode (pass RF input directly to the RF output). (VK_RF_BYPASS)
- 'ScanChannelsToggle', //Toggle scan channels mode. (VK_SCAN_CHANNELS_TOGGLE)
- 'ScreenModeNext', //Advance display screen mode to next available mode. (VK_SCREEN_MODE_NEXT)
- 'Settings', //Toggle display of device settings screen. (VK_SETTINGS, KEYCODE_SETTINGS)
- 'SplitScreenToggle', //Toggle split screen mode. (VK_SPLIT_SCREEN_TOGGLE)
- 'STBInput', //Switch the input mode on an external STB (set top box). (KEYCODE_STB_INPUT)
- 'STBPower', //Toggle the power on an external STB (set top box). (KEYCODE_STB_POWER)
- 'Subtitle', //Toggle display of subtitles, if available. (VK_SUBTITLE)
- 'Teletext', //Toggle display of teletext, if available (VK_TELETEXT, KEYCODE_TV_TELETEXT).
- 'VideoModeNext', //Advance video mode to next available mode. (VK_VIDEO_MODE_NEXT)
- 'Wink', //Cause device to identify itself in some manner, e.g., audibly or visibly. (VK_WINK)
- 'ZoomToggle', //Toggle between full-screen and scaled content, or alter magnification level. (VK_ZOOM, KEYCODE_TV_ZOOM_MODE)
- ],
-};
diff --git a/packages/core/src/Types/Const/index.ts b/packages/core/src/Types/Const/index.ts
index 3621f8fb50..5c69bf9445 100644
--- a/packages/core/src/Types/Const/index.ts
+++ b/packages/core/src/Types/Const/index.ts
@@ -1,8 +1,7 @@
-// @index('./*.ts', f => `export * from '${f.path}'`)
-export * from './ACTION_NAMES';
-export * from './CONST';
-export * from './EXTENSION_NAMES';
-export * from './KEYBOARD_KEYS';
-export * from './PLUGIN_NAMES';
-export * from './THEME_COLOR_MAP';
-// @endindex
+// @index('./*.ts', f => `export * from '${f.path}'`)
+export * from './ACTION_NAMES';
+export * from './CONST';
+export * from './EXTENSION_NAMES';
+export * from './PLUGIN_NAMES';
+export * from './THEME_COLOR_MAP';
+// @endindex
diff --git a/packages/core/src/Types/Interfaces/IDocumentData.ts b/packages/core/src/Types/Interfaces/IDocumentData.ts
index 61f3113f56..c5143bce61 100644
--- a/packages/core/src/Types/Interfaces/IDocumentData.ts
+++ b/packages/core/src/Types/Interfaces/IDocumentData.ts
@@ -308,6 +308,19 @@ export interface IDocumentStyle extends IDocStyleBase, IDocumentLayout, IHeaderA
textStyle?: ITextStyle; // 文字默认样式
}
+/**
+ * the alignment mode is returned with respect to the offset of the sheet cell,
+ * because the document needs to render the layout for cells and
+ * support alignment across multiple cells (e.g., horizontal alignment of long text in overflow mode).
+ * The alignment mode of the document itself cannot meet this requirement,
+ * so an additional renderConfig needs to be added during the rendering of the document component.
+ * This means that there are two coexisting alignment modes.
+ * In certain cases, such as in an editor, conflicts may arise,
+ * requiring only one alignment mode to be retained.
+ * By removing the relevant configurations in renderConfig,
+ * the alignment mode of the sheet cell can be modified.
+ * The alternative alignment mode is applied to paragraphs within the document.
+ */
export interface IDocumentRenderConfig {
// The following are the attributes used for secondary processing of skeleton, generally not related to word
verticalAlign?: VerticalAlign; // VerticalAlignment, only valid for pages, word does not have this arrangement, used for secondary calculation
@@ -808,6 +821,9 @@ export enum characterSpacingControlType {
doNotCompress,
}
+/**
+ * Paper orientation, whether it's portrait (vertical) or landscape (horizontal)
+ */
export enum PageOrientType {
PORTRAIT,
LANDSCAPE,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 50c1294dea..670ceec9f2 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -16,7 +16,7 @@ export {
sequenceExecute,
} from './services/command/command.service';
export { IConfigService } from './services/config/config.service';
-export { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from './services/context/context';
+export * from './services/context/context';
export { IContextService } from './services/context/context.service';
export { IUniverInstanceService } from './services/instance/instance.service';
export { LifecycleStages, OnLifecycle } from './services/lifecycle/lifecycle';
diff --git a/packages/core/src/services/context/context.service.ts b/packages/core/src/services/context/context.service.ts
index 2f0e450087..11256a0527 100644
--- a/packages/core/src/services/context/context.service.ts
+++ b/packages/core/src/services/context/context.service.ts
@@ -8,7 +8,6 @@ export interface IContextService {
getContextValue(key: string): boolean;
setContextValue(key: string, value: boolean): void;
- matchContextValue(matchKey: string): boolean;
}
export const IContextService = createIdentifier<IContextService>('univer.context-service');
@@ -29,17 +28,17 @@ export class ContextService extends Disposable implements IContextService {
return this._contextMap.get(key) ?? false;
}
- matchContextValue(matchKey: string): boolean {
- let resultKey = '';
- for (const [key] of this._contextMap) {
- if (key.indexOf(matchKey) > -1) {
- resultKey = key;
- break;
- }
- }
-
- return this._contextMap.get(resultKey) ?? false;
- }
+ // matchContextValue(matchKey: string): boolean {
+ // let resultKey = '';
+ // for (const [key] of this._contextMap) {
+ // if (key.indexOf(matchKey) > -1) {
+ // resultKey = key;
+ // break;
+ // }
+ // }
+
+ // return this._contextMap.get(resultKey) ?? false;
+ // }
setContextValue(key: string, value: boolean): void {
this._contextMap.set(key, value);
diff --git a/packages/core/src/services/context/context.ts b/packages/core/src/services/context/context.ts
index 8100d89675..87e2647dd4 100644
--- a/packages/core/src/services/context/context.ts
+++ b/packages/core/src/services/context/context.ts
@@ -2,3 +2,4 @@ export const FOCUSING_SHEET = 'FOCUSING_SHEET';
export const FOCUSING_DOC = 'FOCUSING_DOC';
export const FOCUSING_SLIDE = 'FOCUSING_SLIDE';
export const FOCUSING_EDITOR = 'FOCUSING_EDITOR';
+export const FOCUSING_EDITOR_FORMULA = 'FOCUSING_EDITOR_FORMULA';
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index a22e687f1a..c27b26a617 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -38,7 +38,7 @@ export interface IUniverInstanceService {
getFocusedUniverInstance(): Workbook | DocumentModel | Slide | null;
createDoc(data: Partial<IDocumentData>): DocumentModel;
-
+ changeDoc(unitId: string, doc: DocumentModel): void;
addDoc(doc: DocumentModel): void;
addSheet(sheet: Workbook): void;
addSlide(slide: Slide): void;
@@ -134,6 +134,15 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
this.setCurrentUniverSheetInstance(sheet.getUnitId());
}
+ changeDoc(unitId: string, doc: DocumentModel): void {
+ const oldDoc = this._docs.find((doc) => doc.getUnitId() === unitId);
+ if (oldDoc != null) {
+ const index = this._docs.indexOf(oldDoc);
+ this._docs.splice(index, 1);
+ }
+ this.addDoc(doc);
+ }
+
addDoc(doc: DocumentModel): void {
this._docs.push(doc);
this._docAdded$.next(doc);
diff --git a/packages/sheets-plugin-formula/src/Controller/keyCode.ts b/packages/sheets-plugin-formula/src/Controller/keyCode.ts
deleted file mode 100644
index 3ac8fe797d..0000000000
--- a/packages/sheets-plugin-formula/src/Controller/keyCode.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Code of key in keyboard
- */
-export enum KeyCode {
- BACKSPACE = 8,
- TAB = 9,
- ENTER = 13,
- SHIFT = 16,
- CTRL = 17,
- PAUSE = 19,
- CAPS_LOCK = 20,
- ESC = 27,
-
- SPACE = 33,
- PAGE_UP = 33,
- PAGE_DOWN = 34,
- END = 35,
- HOME = 36,
- LEFT = 37,
- UP = 38,
- RIGHT = 39,
- DOWN = 40,
- INSERT = 45,
- DELETE = 46,
-
- WIN = 91,
- WIN_R = 92,
- MENU = 93,
-
- F1 = 112,
- F2 = 113,
- F3 = 114,
- F4 = 115,
- F5 = 116,
- F6 = 117,
- F7 = 118,
- F8 = 119,
- F9 = 120,
- F10 = 121,
- F11 = 122,
- F12 = 123,
- NUM_LOCK = 144,
- SCROLL_LOCK = 145,
-}
-
-/**
- * https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/
- */
-export enum KeyboardKeyType {
- Backspace = 'Backspace',
- Delete = 'Delete',
- Enter = 'Enter',
- Copy = 'c',
- Paste = 'v',
- ArrowUp = 'ArrowUp',
- ArrowDown = 'ArrowDown',
- ArrowLeft = 'ArrowLeft',
- ArrowRight = 'ArrowRight',
-}
diff --git a/packages/ui-plugin-sheets/src/View/EditorContainer/EditorContainer.tsx b/packages/ui-plugin-sheets/src/View/EditorContainer/EditorContainer.tsx
index f821103772..801b51dc17 100644
--- a/packages/ui-plugin-sheets/src/View/EditorContainer/EditorContainer.tsx
+++ b/packages/ui-plugin-sheets/src/View/EditorContainer/EditorContainer.tsx
@@ -1,6 +1,7 @@
import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, IRenderManagerService } from '@univerjs/base-render';
import { useDependency } from '@wendellhu/redi/react-bindings';
import { useEffect, useRef, useState } from 'react';
+import { Subscription } from 'rxjs';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
import styles from './index.module.less';
@@ -16,6 +17,8 @@ const EDITOR_DEFAULT_POSITION = {
left: HIDDEN_EDITOR_POSITION,
};
+let isLoaded = false;
+
export const EditorContainer: React.FC<ICellIEditorProps> = () => {
const [state, setState] = useState({
...EDITOR_DEFAULT_POSITION,
@@ -34,35 +37,45 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
return;
}
- const engine = renderManagerService.getRenderById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.engine;
+ let subscription: Subscription;
- const subscription = cellEditorManagerService.state$.subscribe((param) => {
- if (param == null) {
+ renderManagerService.currentRender$.subscribe((unitId) => {
+ if (unitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY || isLoaded === true) {
return;
}
- const {
- startX = HIDDEN_EDITOR_POSITION,
- startY = HIDDEN_EDITOR_POSITION,
- endX = 0,
- endY = 0,
- show = false,
- } = param;
-
- if (show === false) {
- setState({
- ...EDITOR_DEFAULT_POSITION,
- });
- } else {
- setState({
- width: endX - startX,
- height: endY - startY,
- left: startX,
- top: startY,
- });
- }
- });
- engine?.setContainer(editor);
+ const engine = renderManagerService.getRenderById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.engine;
+
+ subscription = cellEditorManagerService.state$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+ const {
+ startX = HIDDEN_EDITOR_POSITION,
+ startY = HIDDEN_EDITOR_POSITION,
+ endX = 0,
+ endY = 0,
+ show = false,
+ } = param;
+
+ if (show === false) {
+ setState({
+ ...EDITOR_DEFAULT_POSITION,
+ });
+ } else {
+ setState({
+ width: endX - startX,
+ height: endY - startY,
+ left: startX - 1,
+ top: startY - 1,
+ });
+ }
+ });
+
+ engine?.setContainer(editor);
+
+ isLoaded = true;
+ });
// Clean up on unmount
return () => {
@@ -70,6 +83,10 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
};
}, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
+ useEffect(() => {
+ cellEditorManagerService.setFocus(true);
+ }, [state]);
+
return (
<div
className={styles.editorContainer}
diff --git a/packages/ui-plugin-sheets/src/View/EditorContainer/index.module.less b/packages/ui-plugin-sheets/src/View/EditorContainer/index.module.less
index b3f55dd00f..fd90becea3 100644
--- a/packages/ui-plugin-sheets/src/View/EditorContainer/index.module.less
+++ b/packages/ui-plugin-sheets/src/View/EditorContainer/index.module.less
@@ -3,9 +3,9 @@
.editor-container {
display: flex;
position: absolute;
- border: 2px solid #409f11;
+ border: 1px solid #409f11;
box-shadow: none;
- outline: 2px solid #49b811;
+ outline: 1px solid #49b811;
z-index: 10;
left: 100px;
diff --git a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
index ae81cd6aad..cafa7631b5 100644
--- a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
+++ b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
@@ -1,8 +1,8 @@
import { CopyCommand, CutCommand, IClipboardInterfaceService, PasteCommand } from '@univerjs/base-ui';
-import { CommandType, FOCUSING_SHEET, IContextService, ILogService, IMultiCommand } from '@univerjs/core';
+import { CommandType, ILogService, IMultiCommand } from '@univerjs/core';
+import { whenEditorNotActivated } from '../../controller/shortcuts/utils';
import { ISheetClipboardService } from '../../services/clipboard/clipboard.service';
-import { SHEET_EDITOR_ACTIVATED } from '../../services/context/context';
export const SheetCopyCommand: IMultiCommand = {
id: CopyCommand.id,
@@ -10,8 +10,7 @@ export const SheetCopyCommand: IMultiCommand = {
type: CommandType.COMMAND,
multi: true,
priority: 1000,
- preconditions: (contextService: IContextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.matchContextValue(SHEET_EDITOR_ACTIVATED),
+ preconditions: whenEditorNotActivated,
handler: async (accessor) => {
const sheetClipboardService = accessor.get(ISheetClipboardService);
return sheetClipboardService.copy();
@@ -24,8 +23,7 @@ export const SheetCutCommand: IMultiCommand = {
type: CommandType.COMMAND,
multi: true,
priority: 1000,
- preconditions: (contextService: IContextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.matchContextValue(SHEET_EDITOR_ACTIVATED),
+ preconditions: whenEditorNotActivated,
handler: async (accessor, params) => {
const sheetClipboardService = accessor.get(ISheetClipboardService);
return sheetClipboardService.cut();
@@ -38,8 +36,7 @@ export const SheetPasteCommand: IMultiCommand = {
multi: true,
name: 'sheet.command.paste',
priority: 1000,
- preconditions: (contextService: IContextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.matchContextValue(SHEET_EDITOR_ACTIVATED),
+ preconditions: whenEditorNotActivated,
handler: async (accessor) => {
const logService = accessor.get(ILogService);
diff --git a/packages/ui-plugin-sheets/src/commands/operations/activate-cell-edit.operation.ts b/packages/ui-plugin-sheets/src/commands/operations/activate-cell-edit.operation.ts
new file mode 100644
index 0000000000..11fe2866db
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/commands/operations/activate-cell-edit.operation.ts
@@ -0,0 +1,17 @@
+// This file provide operations to change selection of sheets.
+
+import { CommandType, IOperation } from '@univerjs/core';
+
+import { IEditorBridgeService, IEditorBridgeServiceParam } from '../../services/editor-bridge.service';
+
+export const SetActivateCellEditOperation: IOperation<IEditorBridgeServiceParam> = {
+ id: 'sheet.operation.set-activate-cell-edit',
+ type: CommandType.OPERATION,
+ handler: async (accessor, params) => {
+ const editorBridgeService = accessor.get(IEditorBridgeService);
+
+ editorBridgeService.setState(params!);
+
+ return true;
+ },
+};
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
new file mode 100644
index 0000000000..d8721ebe34
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts
@@ -0,0 +1,21 @@
+// This file provide operations to change selection of sheets.
+
+import { CommandType, IOperation } from '@univerjs/core';
+
+import { IEditorBridgeService, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+
+export const SetCellEditOperation: IOperation<IEditorBridgeServiceVisibleParam> = {
+ id: 'sheet.operation.set-cell-edit',
+ type: CommandType.OPERATION,
+ handler: async (accessor, params) => {
+ const editorBridgeService = accessor.get(IEditorBridgeService);
+
+ if (params?.visible === true) {
+ editorBridgeService.show(params.eventType);
+ } else {
+ editorBridgeService.hide();
+ }
+
+ return true;
+ },
+};
diff --git a/packages/ui-plugin-sheets/src/controller/editor-bridge.controller.ts b/packages/ui-plugin-sheets/src/controller/editor-bridge.controller.ts
new file mode 100644
index 0000000000..036403163c
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/controller/editor-bridge.controller.ts
@@ -0,0 +1,174 @@
+import { DeviceInputEventType, IRenderManagerService, ISelectionTransformerShapeManager } from '@univerjs/base-render';
+import { getSheetObject, SelectionManagerService, SheetSkeletonManagerService } from '@univerjs/base-sheets';
+import {
+ Disposable,
+ ICommandService,
+ IUniverInstanceService,
+ LifecycleStages,
+ makeCellToSelection,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import { SetActivateCellEditOperation } from '../commands/operations/activate-cell-edit.operation';
+import { SetCellEditOperation } from '../commands/operations/cell-edit.operation';
+import { IEditorBridgeService } from '../services/editor-bridge.service';
+
+@OnLifecycle(LifecycleStages.Rendered, EditorBridgeController)
+export class EditorBridgeController extends Disposable {
+ constructor(
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @ISelectionTransformerShapeManager
+ private readonly _selectionTransformerShapeManager: ISelectionTransformerShapeManager
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ override dispose(): void {}
+
+ private _initialize() {
+ this._initialSelectionListener();
+
+ this._initialEventListener();
+ }
+
+ private _initialSelectionListener() {
+ this._selectionManagerService.selectionInfo$.subscribe((params) => {
+ const currentSkeletonManager = this._sheetSkeletonManagerService.getCurrent();
+
+ const sheetObject = this._getSheetObject();
+
+ if (currentSkeletonManager == null || sheetObject == null) {
+ return;
+ }
+
+ const { skeleton, unitId, sheetId } = currentSkeletonManager;
+
+ const { scene } = sheetObject;
+
+ if (params == null || params.length === 0 || skeleton == null) {
+ return;
+ }
+
+ const { primary } = params[params.length - 1];
+
+ if (primary == null) {
+ return;
+ }
+
+ const { startRow, startColumn } = primary;
+
+ const primaryWithCoord = this._selectionTransformerShapeManager.convertCellRangeToInfo(primary);
+
+ if (primaryWithCoord == null) {
+ return;
+ }
+
+ const actualRangeWithCoord = makeCellToSelection(primaryWithCoord);
+
+ if (actualRangeWithCoord == null) {
+ return;
+ }
+
+ let { startX, startY, endX, endY } = actualRangeWithCoord;
+
+ const { scaleX, scaleY } = scene.getAncestorScale();
+ const scrollXY = scene.getScrollXY(this._selectionTransformerShapeManager.getViewPort());
+
+ startX = skeleton.convertTransformToOffsetX(startX, scaleX, scrollXY) - scrollXY.x * scaleX;
+
+ startY = skeleton.convertTransformToOffsetY(startY, scaleY, scrollXY) - scrollXY.y * scaleY;
+
+ endX = skeleton.convertTransformToOffsetX(endX, scaleX, scrollXY) - scrollXY.x * scaleX;
+
+ endY = skeleton.convertTransformToOffsetY(endY, scaleY, scrollXY) - scrollXY.y * scaleY;
+
+ let documentLayoutObject = skeleton.getCellDocumentModel(startRow, startColumn, true, true);
+
+ if (documentLayoutObject == null || documentLayoutObject.documentModel == null) {
+ documentLayoutObject = skeleton.getBlankCellDocumentModel(startRow, startColumn, true);
+ }
+
+ // let documentModel = documentModelObject?.documentModel;
+
+ // if (documentModel == null) {
+ // documentModel = skeleton.getBlankCellDocumentModel(startRow, startColumn).documentModel;
+ // }
+
+ // documentModelObject.documentModel = documentModel;
+
+ // this._editorBridgeService.setState({
+ // position: {
+ // startX,
+ // startY,
+ // endX,
+ // endY,
+ // },
+ // unitId,
+ // sheetId,
+ // documentLayoutObject,
+ // });
+
+ this._commandService.executeCommand(SetActivateCellEditOperation.id, {
+ position: {
+ startX,
+ startY,
+ endX,
+ endY,
+ },
+ row: startRow,
+ column: startColumn,
+ unitId,
+ sheetId,
+ documentLayoutObject,
+ });
+ });
+ }
+
+ private _initialEventListener() {
+ const sheetObject = this._getSheetObject();
+ if (sheetObject == null) {
+ return;
+ }
+
+ const { spreadsheet, scene, spreadsheetColumnHeader, spreadsheetLeftTopPlaceholder, spreadsheetRowHeader } =
+ sheetObject;
+
+ spreadsheet.onDblclickObserver.add(() => {
+ // this._editorBridgeService.show(DeviceInputEventType.Dblclick);
+
+ this._commandService.executeCommand(SetCellEditOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ });
+ });
+
+ spreadsheet.onPointerDownObserver.add(this._hideEditor.bind(this));
+ spreadsheetColumnHeader.onPointerDownObserver.add(this._hideEditor.bind(this));
+ spreadsheetLeftTopPlaceholder.onPointerDownObserver.add(this._hideEditor.bind(this));
+ spreadsheetRowHeader.onPointerDownObserver.add(this._hideEditor.bind(this));
+ }
+
+ private _hideEditor() {
+ if (this._editorBridgeService.isVisible().visible === true) {
+ this._commandService.executeCommand(SetCellEditOperation.id, {
+ visible: false,
+ });
+ }
+ }
+
+ private _getSheetObject() {
+ return getSheetObject(this._currentUniverService, this._renderManagerService);
+ }
+
+ private _commandExecutedListener() {}
+}
diff --git a/packages/ui-plugin-sheets/src/controller/editor/editing.controller.ts b/packages/ui-plugin-sheets/src/controller/editor/editing.controller.ts
index a2ad652b3d..9af0c3bf6e 100644
--- a/packages/ui-plugin-sheets/src/controller/editor/editing.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/editor/editing.controller.ts
@@ -1,7 +1,12 @@
import { DocSkeletonManagerService, getDocObject, TextSelectionManagerService } from '@univerjs/base-docs';
import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import { SetRangeValuesCommand } from '@univerjs/base-sheets';
+import { KeyCode } from '@univerjs/base-ui';
import {
Disposable,
+ DocumentModel,
+ ICellData,
+ ICommandInfo,
ICommandService,
IUniverInstanceService,
LifecycleStages,
@@ -11,8 +16,11 @@ import {
import { Inject } from '@wendellhu/redi';
import { Subscription } from 'rxjs';
-@OnLifecycle(LifecycleStages.Rendered, NormalInputController)
-export class NormalInputController extends Disposable {
+import { SetCellEditOperation } from '../../commands/operations/cell-edit.operation';
+import { IEditorBridgeService, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+
+@OnLifecycle(LifecycleStages.Steady, EditingController)
+export class EditingController extends Disposable {
private _onInputSubscription: Nullable<Subscription>;
constructor(
@@ -21,7 +29,8 @@ export class NormalInputController extends Disposable {
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService
) {
super();
@@ -40,7 +49,76 @@ export class NormalInputController extends Disposable {
private _initialNormalInput() {}
- private _commandExecutedListener() {}
+ private _commandExecutedListener() {
+ const updateCommandList = [SetCellEditOperation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ const params = command.params as IEditorBridgeServiceVisibleParam;
+ const { visible, keycode, eventType } = params;
+
+ if (visible === true) {
+ return;
+ }
+
+ if (keycode === KeyCode.ESC) {
+ return;
+ }
+
+ const state = this._editorBridgeService.getState();
+
+ if (state == null) {
+ return;
+ }
+
+ const { unitId, sheetId, row, column, documentLayoutObject } = state;
+
+ if (documentLayoutObject == null) {
+ return;
+ }
+
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+
+ const worksheet = workbook?.getSheetBySheetId(sheetId);
+
+ if (worksheet == null) {
+ return;
+ }
+
+ const cellData: ICellData = worksheet.getCell(row, column) || {};
+
+ const documentModel = documentLayoutObject.documentModel as DocumentModel;
+
+ const snapshot = documentModel.getSnapshot();
+
+ const body = snapshot.body;
+
+ if (body == null) {
+ return;
+ }
+
+ if (body.textRuns && body.textRuns.length > 1) {
+ cellData.p = snapshot;
+ } else {
+ cellData.v = body.dataStream;
+ }
+
+ this._commandService.executeCommand(SetRangeValuesCommand.id, {
+ worksheetId: sheetId,
+ workbookId: unitId,
+ range: {
+ startRow: row,
+ startColumn: column,
+ endRow: row,
+ endColumn: column,
+ },
+ value: cellData,
+ });
+ }
+ })
+ );
+ }
private _getDocObject() {
return getDocObject(this._currentUniverService, this._renderManagerService);
diff --git a/packages/ui-plugin-sheets/src/controller/editor/end-edit.controller.ts b/packages/ui-plugin-sheets/src/controller/editor/end-edit.controller.ts
index a2ad652b3d..5d3b6bd415 100644
--- a/packages/ui-plugin-sheets/src/controller/editor/end-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/editor/end-edit.controller.ts
@@ -1,27 +1,40 @@
-import { DocSkeletonManagerService, getDocObject, TextSelectionManagerService } from '@univerjs/base-docs';
-import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import { getDocObject } from '@univerjs/base-docs';
+import { IRenderManagerService } from '@univerjs/base-render';
+import { SetRangeValuesCommand } from '@univerjs/base-sheets';
+import { KeyCode } from '@univerjs/base-ui';
import {
Disposable,
+ DocumentModel,
+ FOCUSING_EDITOR,
+ FOCUSING_EDITOR_FORMULA,
+ ICellData,
+ ICommandInfo,
ICommandService,
+ IContextService,
IUniverInstanceService,
LifecycleStages,
Nullable,
OnLifecycle,
} from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
import { Subscription } from 'rxjs';
-@OnLifecycle(LifecycleStages.Rendered, NormalInputController)
-export class NormalInputController extends Disposable {
+import { SetCellEditOperation } from '../../commands/operations/cell-edit.operation';
+import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
+import { IEditorBridgeService, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
+
+@OnLifecycle(LifecycleStages.Steady, EndEditController)
+export class EndEditController extends Disposable {
private _onInputSubscription: Nullable<Subscription>;
+ private _editorVisiblePrevious = false;
+
constructor(
- @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @IContextService private readonly _contextService: IContextService,
+ @ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService
) {
super();
@@ -35,12 +48,127 @@ export class NormalInputController extends Disposable {
}
private _initialize() {
- this._initialNormalInput();
+ this._initialExitInput();
+ }
+
+ private _initialExitInput() {
+ this._editorBridgeService.visible$.subscribe((param) => {
+ const { visible, keycode } = param;
+
+ if (visible === this._editorVisiblePrevious) {
+ return;
+ }
+
+ this._editorVisiblePrevious = visible;
+
+ if (visible === true) {
+ return;
+ }
+
+ this._exitInput(param);
+
+ if (keycode === KeyCode.ESC) {
+ return;
+ }
+
+ const state = this._editorBridgeService.getState();
+
+ if (state == null) {
+ return;
+ }
+
+ const { unitId, sheetId, row, column, documentLayoutObject } = state;
+
+ if (documentLayoutObject == null) {
+ return;
+ }
+
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+
+ const worksheet = workbook?.getSheetBySheetId(sheetId);
+
+ if (worksheet == null) {
+ return;
+ }
+
+ const cellData: ICellData = worksheet.getCell(row, column) || {};
+
+ const documentModel = documentLayoutObject.documentModel as DocumentModel;
+
+ const snapshot = documentModel.getSnapshot();
+
+ const body = snapshot.body;
+
+ if (body == null) {
+ return;
+ }
+
+ if (body.textRuns && body.textRuns.length > 1) {
+ cellData.p = snapshot;
+ } else {
+ const data = body.dataStream;
+ const lastString = data.substring(data.length - 2, data.length);
+ const newDataStream = lastString === '\r\n' ? data.substring(0, data.length - 2) : data;
+
+ if (newDataStream === cellData.v) {
+ return;
+ }
+
+ cellData.v = newDataStream;
+ }
+
+ this._commandService.executeCommand(SetRangeValuesCommand.id, {
+ worksheetId: sheetId,
+ workbookId: unitId,
+ range: {
+ startRow: row,
+ startColumn: column,
+ endRow: row,
+ endColumn: column,
+ },
+ value: cellData,
+ });
+ });
}
- private _initialNormalInput() {}
+ private _exitInput(param: IEditorBridgeServiceVisibleParam) {
+ this._contextService.setContextValue(FOCUSING_EDITOR_FORMULA, false);
+ this._contextService.setContextValue(FOCUSING_EDITOR, false);
+ this._cellEditorManagerService.setState({
+ show: param.visible,
+ });
+ }
- private _commandExecutedListener() {}
+ private _commandExecutedListener() {
+ const updateCommandList = [SetCellEditOperation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ const params = command.params as IEditorBridgeServiceVisibleParam;
+ const { visible, keycode, eventType } = params;
+
+ if (visible === true) {
+ return;
+ }
+
+ if (keycode === KeyCode.ESC) {
+ return;
+ }
+
+ const state = this._editorBridgeService.getState();
+
+ if (state == null) {
+ return;
+ }
+
+ const { unitId } = state;
+
+ this._renderManagerService.getRenderById(unitId)?.mainComponent?.makeDirty();
+ }
+ })
+ );
+ }
private _getDocObject() {
return getDocObject(this._currentUniverService, this._renderManagerService);
diff --git a/packages/ui-plugin-sheets/src/controller/editor/initialize-editor.controller.ts b/packages/ui-plugin-sheets/src/controller/editor/initialize-editor.controller.ts
new file mode 100644
index 0000000000..6b7e657268
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/controller/editor/initialize-editor.controller.ts
@@ -0,0 +1,54 @@
+import { getDocObject } from '@univerjs/base-docs';
+import {
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ IRenderManagerService,
+} from '@univerjs/base-render';
+import { Disposable, IUniverInstanceService, LifecycleStages, Nullable, OnLifecycle } from '@univerjs/core';
+import { Subscription } from 'rxjs';
+
+@OnLifecycle(LifecycleStages.Rendered, InitializeEditorController)
+export class InitializeEditorController extends Disposable {
+ private _onInputSubscription: Nullable<Subscription>;
+
+ constructor(
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+
+ setTimeout(() => {
+ this._initialize();
+ }, 0);
+
+ this._commandExecutedListener();
+ }
+
+ override dispose(): void {
+ this._onInputSubscription?.unsubscribe();
+ }
+
+ private _initialize() {
+ this._currentUniverService.createDoc({
+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ documentStyle: {},
+ });
+
+ // this._currentUniverService.focusUniverInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+
+ // create univer doc formula bar editor instance
+
+ this._currentUniverService.createDoc({
+ id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ documentStyle: {},
+ });
+
+ // this._currentUniverService.focusUniverInstance(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ }
+
+ private _commandExecutedListener() {}
+
+ private _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
+}
diff --git a/packages/ui-plugin-sheets/src/controller/editor/start-edit.controller.ts b/packages/ui-plugin-sheets/src/controller/editor/start-edit.controller.ts
index 607826da59..96b5d52c9c 100644
--- a/packages/ui-plugin-sheets/src/controller/editor/start-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/editor/start-edit.controller.ts
@@ -1,34 +1,62 @@
-import { DocSkeletonManagerService, TextSelectionManagerService } from '@univerjs/base-docs';
+import {
+ DOCS_COMPONENT_MAIN_LAYER_INDEX,
+ DocSkeletonManagerService,
+ IRichTextEditingMutationParams,
+ NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ RichTextEditingMutation,
+ TextSelectionManagerService,
+} from '@univerjs/base-docs';
import {
DeviceInputEventType,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DocumentSkeleton,
+ IDocumentLayoutObject,
IEditorInputConfig,
IRenderManagerService,
ITextSelectionRenderManager,
+ Rect,
+ Scene,
} from '@univerjs/base-render';
-import { IEditorBridgeService } from '@univerjs/base-sheets';
import {
Disposable,
+ DocumentModel,
+ FOCUSING_EDITOR,
+ HorizontalAlign,
+ ICommandInfo,
ICommandService,
IContextService,
+ IDocumentBody,
+ IDocumentData,
+ IPosition,
+ ITextRotation,
IUniverInstanceService,
LifecycleStages,
- makeCellToSelection,
+ LocaleService,
Nullable,
OnLifecycle,
+ Tools,
+ VerticalAlign,
+ WrapStrategy,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { Subscription } from 'rxjs';
import { getEditorObject } from '../../Basics/editor/get-editor-object';
-import { SHEET_EDITOR_ACTIVATED } from '../../services/context/context';
+import { SetCellEditOperation } from '../../commands/operations/cell-edit.operation';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
+import { IEditorBridgeService } from '../../services/editor-bridge.service';
+
+const HIDDEN_EDITOR_POSITION = -1000;
+
+const EDITOR_INPUT_SELF_EXTEND_GAP = 5;
@OnLifecycle(LifecycleStages.Steady, StartEditController)
export class StartEditController extends Disposable {
private _onInputSubscription: Nullable<Subscription>;
+ private _editorVisiblePrevious = false;
+
constructor(
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IContextService private readonly _contextService: IContextService,
@@ -38,7 +66,8 @@ export class StartEditController extends Disposable {
@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(LocaleService) protected readonly _localService: LocaleService
) {
super();
@@ -55,6 +84,13 @@ export class StartEditController extends Disposable {
this._initialEditFocusListener();
this._initialStartEdit();
this._initialKeyboardListener();
+ this._initialCursorSync();
+ }
+
+ private _initialCursorSync() {
+ this._cellEditorManagerService.focus$.subscribe(() => {
+ this._textSelectionRenderManager.sync();
+ });
}
private _initialEditFocusListener() {
@@ -63,7 +99,7 @@ export class StartEditController extends Disposable {
return;
}
- const { unitId, sheetId, primaryWithCoord, docSkeleton } = param;
+ const { position, documentLayoutObject } = param;
const editorObject = this._getEditorObject();
@@ -71,54 +107,319 @@ export class StartEditController extends Disposable {
return;
}
- const { document, scene, engine } = editorObject;
+ const { document: documentComponent, scene } = editorObject;
+
+ const { startX, endX } = position;
+
+ const { textRotation, wrapStrategy, documentModel } = documentLayoutObject;
+
+ const { a: angle } = textRotation as ITextRotation;
+
+ documentModel!.updateDocumentId(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+
+ // documentModel!.updateDocumentDataMargin(paddingData);
+
+ if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {
+ documentModel!.updateDocumentDataPageSize(endX - startX);
+ }
+
+ this._currentUniverService.changeDoc(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, documentModel! as DocumentModel);
+
+ const docParam = this._docSkeletonManagerService.updateCurrent({ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY });
+
+ if (docParam == null) {
+ return;
+ }
+
+ const documentSkeleton = docParam.skeleton;
+
+ documentComponent.changeSkeleton(documentSkeleton);
+
+ this._textSelectionManagerService.setCurrentSelectionNotRefresh({
+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ unitId: docParam.unitId,
+ });
+
+ this._textSelectionRenderManager.changeRuntime(documentSkeleton, scene);
+
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: 0,
+ cursorEnd: 0,
+ isCollapse: true,
+ isEndBack: true,
+ isStartBack: true,
+ },
+ ]);
+ this._textSelectionRenderManager.active(HIDDEN_EDITOR_POSITION, HIDDEN_EDITOR_POSITION);
+ });
+ }
+
+ private _predictingSize(
+ actualRangeWithCoord: IPosition,
+ documentSkeleton: DocumentSkeleton,
+ documentLayoutObject: IDocumentLayoutObject
+ ) {
+ const { startX, endX } = actualRangeWithCoord;
+
+ const { textRotation, wrapStrategy } = documentLayoutObject;
+
+ const { a: angle } = textRotation as ITextRotation;
+
+ const clientWidth = document.body.clientWidth;
+
+ if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {
+ return documentSkeleton.getActualSize();
+ }
+ documentSkeleton.getModel().updateDocumentDataPageSize(clientWidth - startX);
+ documentSkeleton.calculate();
+
+ const size = documentSkeleton.getActualSize();
+
+ let editorWidth = endX - startX;
+
+ if (editorWidth < size.actualWidth + EDITOR_INPUT_SELF_EXTEND_GAP) {
+ editorWidth = size.actualWidth + EDITOR_INPUT_SELF_EXTEND_GAP;
+ }
+
+ documentSkeleton.getModel()!.updateDocumentDataPageSize(editorWidth);
+
+ documentSkeleton.getModel()!.updateDocumentRenderConfig({
+ horizontalAlign: HorizontalAlign.UNSPECIFIED,
+ });
+
+ return {
+ actualWidth: editorWidth,
+ actualHeight: size.actualHeight,
+ };
+ }
+
+ private _fitTextSize(
+ actualRangeWithCoord: IPosition,
+ documentSkeleton: DocumentSkeleton,
+ documentLayoutObject: IDocumentLayoutObject
+ ) {
+ const editorObject = this._getEditorObject();
+
+ if (editorObject == null) {
+ return;
+ }
+
+ const { document, scene, engine } = editorObject;
+
+ const { startX, startY, endX, endY } = actualRangeWithCoord;
+ const { actualWidth, actualHeight } = this._predictingSize(
+ actualRangeWithCoord,
+ documentSkeleton,
+ documentLayoutObject
+ );
+ const { verticalAlign, paddingData, fill } = documentLayoutObject;
+
+ let editorWidth = endX - startX;
+
+ let editorHeight = endY - startY;
+
+ if (editorWidth < actualWidth) {
+ editorWidth = actualWidth;
+ }
+
+ if (editorHeight < actualHeight) {
+ editorHeight = actualHeight;
+ // To restore the page margins for the skeleton.
+ documentSkeleton.getModel().updateDocumentDataMargin(paddingData);
+ } else {
+ // Set the top margin under vertical alignment.
+ let offsetTop = paddingData.t || 0;
+ if (verticalAlign === VerticalAlign.MIDDLE) {
+ offsetTop = (editorHeight - actualHeight) / 2;
+ } else if (verticalAlign === VerticalAlign.BOTTOM) {
+ offsetTop = editorHeight - actualHeight;
+ }
+
+ offsetTop = offsetTop < (paddingData.t || 0) ? paddingData.t || 0 : offsetTop;
+
+ documentSkeleton.getModel().updateDocumentDataMargin({
+ t: offsetTop,
+ });
+ }
+
+ // re-calculate skeleton(viewModel for component)
+ documentSkeleton.calculate();
+
+ // resize canvas
+ engine.resizeBySize(editorWidth, editorHeight);
+
+ scene.transformByState({
+ width: editorWidth,
+ height: editorHeight,
+ });
+
+ document.resize(editorWidth, editorHeight);
- // this._textSelectionRenderManager.changeRuntime(docSkeleton, scene);
+ this._addBackground(scene, editorWidth, editorHeight, fill);
- this._textSelectionRenderManager.active(-1000, -1000);
+ this._cellEditorManagerService.setState({
+ startX,
+ startY,
+ endX: editorWidth + startX,
+ endY: editorHeight + startY,
+ show: true,
});
+
+ // this._textSelectionRenderManager.sync();
+ }
+
+ private _addBackground(scene: Scene, editorWidth: number, editorHeight: number, fill?: Nullable<string>) {
+ const fillRectKey = '_backgroundRectHelperColor_';
+ const rect = scene.getObject(fillRectKey) as Rect;
+ if (rect == null && fill == null) {
+ return;
+ }
+
+ if (rect == null) {
+ scene.addObjects(
+ [
+ new Rect(fillRectKey, {
+ width: editorWidth,
+ height: editorHeight,
+ fill,
+ evented: false,
+ }),
+ ],
+ DOCS_COMPONENT_MAIN_LAYER_INDEX
+ );
+ } else if (fill == null) {
+ rect.dispose();
+ } else {
+ rect.setProps({
+ fill,
+ });
+ rect.transformByState({
+ width: editorWidth,
+ height: editorHeight,
+ });
+ }
}
private _initialStartEdit() {
- this._editorBridgeService.visible$.subscribe((state) => {
- if (state.visible === false) {
- this._contextService.setContextValue(SHEET_EDITOR_ACTIVATED, false);
- this._cellEditorManagerService.setState({
- show: state.visible,
- });
+ this._editorBridgeService.visible$.subscribe((param) => {
+ const { visible, eventType } = param;
+
+ if (visible === this._editorVisiblePrevious) {
return;
}
- const param = this._editorBridgeService.getState();
- if (param == null) {
+ this._editorVisiblePrevious = visible;
+
+ if (visible === false) {
+ return;
+ }
+
+ const state = this._editorBridgeService.getState();
+ if (state == null) {
return;
}
- const { unitId, sheetId, primaryWithCoord, docSkeleton } = param;
+ const { position, documentLayoutObject } = state;
+
+ const editorObject = this._getEditorObject();
- if (primaryWithCoord == null) {
+ if (editorObject == null) {
return;
}
- const actualRangeWithCoord = makeCellToSelection(primaryWithCoord);
+ const { document } = editorObject;
- if (actualRangeWithCoord == null) {
+ this._contextService.setContextValue(FOCUSING_EDITOR, true);
+
+ const docParam = this._docSkeletonManagerService.getCurrent();
+
+ if (docParam == null) {
return;
}
- const { startX, startY, endX, endY } = actualRangeWithCoord;
+ const { skeleton } = docParam;
- this._contextService.setContextValue(SHEET_EDITOR_ACTIVATED, true);
- this._cellEditorManagerService.setState({
- startX,
- startY,
- endX,
- endY,
- show: state.visible,
- });
+ const documentModel = skeleton.getModel() as DocumentModel;
+
+ this._fitTextSize(position, skeleton, documentLayoutObject);
+
+ // move selection
+ if (eventType === DeviceInputEventType.Keyboard) {
+ const snapshot = Tools.deepClone(documentModel.snapshot) as IDocumentData;
+ this._resetBodyStyle(snapshot.body!);
+
+ documentModel.reset(snapshot);
+
+ document.makeDirty();
+
+ // skeleton.calculate();
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: 0,
+ cursorEnd: 0,
+ isCollapse: true,
+ isEndBack: true,
+ isStartBack: true,
+ },
+ ]);
+ } else {
+ const cursor = documentModel.getBodyModel().getLastIndex() - 1 || 0;
+
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: cursor,
+ cursorEnd: cursor,
+ isCollapse: true,
+ isEndBack: true,
+ isStartBack: true,
+ },
+ ]);
+ }
});
}
+ private _resetBodyStyle(body: IDocumentBody) {
+ body.dataStream = `\r\n`;
+
+ if (body.textRuns != null) {
+ if (body.textRuns.length === 1) {
+ body.textRuns[0].st = 0;
+ body.textRuns[0].ed = 1;
+ } else {
+ body.textRuns = undefined;
+ }
+ }
+
+ if (body.paragraphs != null) {
+ if (body.paragraphs.length === 1) {
+ body.paragraphs[0].startIndex = 0;
+ } else {
+ body.paragraphs = [
+ {
+ startIndex: 0,
+ },
+ ];
+ }
+ }
+
+ if (body.sectionBreaks != null) {
+ body.sectionBreaks = undefined;
+ }
+
+ if (body.tables != null) {
+ body.tables = undefined;
+ }
+
+ if (body.customRanges != null) {
+ body.customRanges = undefined;
+ }
+
+ if (body.customBlocks != null) {
+ body.customBlocks = undefined;
+ }
+ }
+
private _initialKeyboardListener() {
this._textSelectionRenderManager.onInput$.subscribe(this._showEditorByKeyboard.bind(this));
this._textSelectionRenderManager.onCompositionstart$.subscribe(this._showEditorByKeyboard.bind(this));
@@ -128,12 +429,65 @@ export class StartEditController extends Disposable {
if (config == null) {
return;
}
- const { event, content, activeRange, selectionList } = config;
+ // const { event, content, activeRange, selectionList } = config;
- this._editorBridgeService.show(DeviceInputEventType.Keyboard);
+ // this._editorBridgeService.show(DeviceInputEventType.Keyboard);
+
+ this._commandService.executeCommand(SetCellEditOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ });
}
- private _commandExecutedListener() {}
+ private _commandExecutedListener() {
+ const updateCommandList = [RichTextEditingMutation.id];
+
+ const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ const params = command.params as IRichTextEditingMutationParams;
+ const { unitId: commandUnitId } = params;
+
+ const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+
+ if (docsSkeletonObject == null) {
+ return;
+ }
+
+ const { unitId, skeleton } = docsSkeletonObject;
+
+ if (commandUnitId !== unitId) {
+ return;
+ }
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ if (!excludeUnitList.includes(unitId)) {
+ return;
+ }
+
+ const param = this._editorBridgeService.getState();
+ if (param == null) {
+ return;
+ }
+
+ const { position, documentLayoutObject } = param;
+
+ this._fitTextSize(position, skeleton, documentLayoutObject);
+
+ // const editorObject = this._getEditorObject();
+
+ // editorObject?.document.makeDirty();
+ }
+ })
+ );
+ }
private _getEditorObject() {
return getEditorObject(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, this._renderManagerService);
diff --git a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
index 48914e8b99..4b07d39349 100644
--- a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
@@ -25,7 +25,8 @@ import { connectInjector } from '@wendellhu/redi/react-bindings';
import { SHEET_UI_PLUGIN_NAME } from '../Basics';
import { RenameSheetCommand } from '../commands/commands/rename.command';
import { ShowMenuListCommand } from '../commands/commands/unhide.command';
-import { QuitCellEditorCommand } from '../services/cell-editor/cell-editor.command';
+import { SetActivateCellEditOperation } from '../commands/operations/activate-cell-edit.operation';
+import { SetCellEditOperation } from '../commands/operations/cell-edit.operation';
import { RightMenuInput } from '../View/RightMenu/RightMenuInput';
import { RightMenuItem } from '../View/RightMenu/RightMenuItem';
import { RenderSheetContent, RenderSheetFooter, RenderSheetHeader } from '../View/SheetContainer/SheetContainer';
@@ -152,10 +153,12 @@ export class SheetUIController extends Disposable {
SetFontFamilyCommand,
SetFontSizeCommand,
- QuitCellEditorCommand,
-
ShowMenuListCommand,
RenameSheetCommand,
+
+ SetCellEditOperation,
+
+ SetActivateCellEditOperation,
].forEach((c) => {
this.disposeWithMe(this._commandService.registerCommand(c));
});
diff --git a/packages/ui-plugin-sheets/src/controller/shortcuts/editor.shortcut.ts b/packages/ui-plugin-sheets/src/controller/shortcuts/editor.shortcut.ts
index 59529c50cb..2e2bbdc76e 100644
--- a/packages/ui-plugin-sheets/src/controller/shortcuts/editor.shortcut.ts
+++ b/packages/ui-plugin-sheets/src/controller/shortcuts/editor.shortcut.ts
@@ -1,10 +1,16 @@
+import { DeviceInputEventType } from '@univerjs/base-render';
import { IShortcutItem, KeyCode } from '@univerjs/base-ui';
+import { FOCUSING_EDITOR } from '@univerjs/core';
-import { QuitCellEditorCommand } from '../../services/cell-editor/cell-editor.command';
-import { SHEET_EDITOR_ACTIVATED } from '../../services/context/context';
+import { SetCellEditOperation } from '../../commands/operations/cell-edit.operation';
export const QuitCellEditorShortcutItem: IShortcutItem = {
- id: QuitCellEditorCommand.id,
+ id: SetCellEditOperation.id,
binding: KeyCode.ENTER,
- preconditions: (contextService) => contextService.matchContextValue(SHEET_EDITOR_ACTIVATED),
+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_EDITOR),
+ staticParameters: {
+ visible: false,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.ENTER,
+ },
};
diff --git a/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.ts b/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.ts
index 7bb4c1171b..0bc05091c1 100644
--- a/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.ts
+++ b/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.ts
@@ -7,9 +7,8 @@ import {
SelectAllCommand,
} from '@univerjs/base-sheets';
import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';
-import { Direction, FOCUSING_SHEET } from '@univerjs/core';
+import { Direction } from '@univerjs/core';
-import { SHEET_EDITOR_ACTIVATED } from '../../services/context/context';
import { whenEditorNotActivated } from './utils';
export const MoveSelectionDownShortcutItem: IShortcutItem<IMoveSelectionCommandParams> = {
@@ -195,8 +194,7 @@ export const ExpandSelectionEndRightShortcutItem: IShortcutItem<IExpandSelection
export const SelectAllShortcutItem: IShortcutItem<ISelectAllCommandParams> = {
id: SelectAllCommand.id,
binding: KeyCode.A | MetaKeys.CTRL_COMMAND,
- preconditions: (contextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.matchContextValue(SHEET_EDITOR_ACTIVATED),
+ preconditions: whenEditorNotActivated,
staticParameters: {
expandToGapFirst: true,
loop: true,
diff --git a/packages/ui-plugin-sheets/src/controller/shortcuts/utils.ts b/packages/ui-plugin-sheets/src/controller/shortcuts/utils.ts
index 66d372b479..98a90d4fa9 100644
--- a/packages/ui-plugin-sheets/src/controller/shortcuts/utils.ts
+++ b/packages/ui-plugin-sheets/src/controller/shortcuts/utils.ts
@@ -1,7 +1,6 @@
import { FOCUSING_SHEET, IContextService } from '@univerjs/core';
-
-import { SHEET_EDITOR_ACTIVATED } from '../../services/context/context';
+import { FOCUSING_EDITOR } from '@univerjs/core/services/context/context.js';
export function whenEditorNotActivated(contextService: IContextService) {
- return contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED);
+ return contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_EDITOR);
}
diff --git a/packages/ui-plugin-sheets/src/index.ts b/packages/ui-plugin-sheets/src/index.ts
index 437bb32cc9..ed9e8b93fa 100644
--- a/packages/ui-plugin-sheets/src/index.ts
+++ b/packages/ui-plugin-sheets/src/index.ts
@@ -1,2 +1,7 @@
export * from './Basics';
+export {
+ EditorBridgeService,
+ IEditorBridgeService,
+ type IEditorBridgeServiceVisibleParam,
+} from './services/editor-bridge.service';
export { SheetUIPlugin } from './sheet-ui-plugin';
diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
deleted file mode 100644
index 33faf73c56..0000000000
--- a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
+++ /dev/null
@@ -1,407 +0,0 @@
-import './desktop.module.less';
-
-import {
- CoverCommand,
- DocsView,
- getDocObject,
- ICoverCommandParams,
- TextSelectionManagerService,
-} from '@univerjs/base-docs';
-import {
- Engine,
- IEditorInputConfig,
- IMouseEvent,
- IPointerEvent,
- IRenderManagerService,
- ISelectionTransformerShapeManager,
- ITextSelectionRenderManager,
- Layer,
- Scene,
- Viewport,
-} from '@univerjs/base-render';
-import { ISetRangeValuesCommandParams, SelectionManagerService, SetRangeValuesCommand } from '@univerjs/base-sheets';
-import {
- createEmptyDocSnapshot,
- handleJsonToDom,
- ICommandService,
- IContextService,
- IDocumentData,
- IRange,
- ISelectionCell,
- IStyleData,
- IUniverInstanceService,
- LifecycleStages,
- Nullable,
- OnLifecycle,
- RxDisposable,
- toDisposable,
-} from '@univerjs/core';
-import { Inject, Injector } from '@wendellhu/redi';
-import { takeUntil } from 'rxjs';
-
-import { SHEET_EDITOR_ACTIVATED } from '../context/context';
-import { ICellEditorService } from './cell-editor.service';
-import { getPositionOfCurrentCell, ICellPosition } from './utils';
-
-const SHEET_CELL_EDITOR_CLASS_NAME = 'univer-cell-editor-container';
-const SHEET_CELL_EDITOR_MODEL_ID = 'sheet.model.cell-editor';
-
-// TODO: active cell editor when on input or IME input. Should clear the cell editor when activate it with a keystroke.
-
-/**
- * Cell editor for Univer on desktop. Reuse by multi univer sheet documents.
- *
- * This service would also handle paste event for UniverSheet.
- */
-@OnLifecycle(LifecycleStages.Rendered, ICellEditorService)
-export class DesktopCellEditorService extends RxDisposable implements ICellEditorService {
- private _containerElement?: HTMLDivElement;
-
- private _editorEngine?: Engine;
-
- private _editorScene?: Scene;
-
- /** This flag indicated whether the cell editor is visible (as it always handles keyboard events when a UniverSheet is focused). */
- private _activated = false;
-
- private _currentEditingCell: Nullable<IRange> = null;
-
- constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
- @ISelectionTransformerShapeManager
- private readonly _selectionTransformerShapeManager: ISelectionTransformerShapeManager,
- @ICommandService private readonly _commandService: ICommandService,
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @IContextService private readonly _contextService: IContextService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
- ) {
- super();
-
- // this._mountCellEditor();
-
- // since paste event could only be triggered on an editable element such as textarea / input / contenteditable,
- // we should bind related event handler to cell editor element
- // this._initPasteHandler();
- // this._initListeners();
- // this._focusCurrentSheet();
- }
-
- override dispose(): void {
- super.dispose();
-
- document.body.removeChild(this._containerElement!);
- }
-
- async enterEditing() {
- if (this._activated) {
- return;
- }
-
- this._activated = true;
-
- // Steps of starting a cell editor:
- // 1. get cell info at the given positions
- // 2. mount cell editor at the given position.
- // 3. set quitting editor callbacks.
- const currentCell = this._selectionManagerService.getLast()?.primary;
- if (!currentCell) {
- return;
- }
-
- this._currentEditingCell = getRangeFromPrimary(currentCell);
- const position = this._positionCellEditor(currentCell);
- await this._updateDocumentModelFromCellModel(position);
-
- this._contextService.setContextValue(SHEET_EDITOR_ACTIVATED, true);
-
- this._currentUniverService.focusUniverInstance(SHEET_CELL_EDITOR_MODEL_ID); // focus the UniverDoc instance to enable rich text editing
- this._textSelectionRenderManager.activate(true);
- }
-
- quitEditing(): void {
- if (!this._activated) {
- return;
- }
-
- this._activated = false;
- this._hideCellEditor();
-
- const currentUniverSheet = this._currentUniverService.getCurrentUniverSheetInstance();
- const workbookId = currentUniverSheet.getUnitId();
- this._currentUniverService.focusUniverInstance(workbookId);
- this._contextService.setContextValue(SHEET_EDITOR_ACTIVATED, false);
-
- const model = this._currentUniverService.getUniverDocInstance(SHEET_CELL_EDITOR_MODEL_ID)!;
- const dataStream = model.getBodyModel().getText();
- this._textSelectionRenderManager.deactivate(true);
-
- this._commandService.executeCommand(SetRangeValuesCommand.id, <ISetRangeValuesCommandParams>{
- workbookId,
- worksheetId: currentUniverSheet.getActiveSheet().getSheetId(),
- range: this._currentEditingCell,
- value: {
- v: dataStream,
- },
- });
- }
-
- private _focusCurrentSheet(): void {
- this._currentUniverService.focusUniverInstance(
- this._currentUniverService.getCurrentUniverSheetInstance().getUnitId()
- );
- }
-
- private _mountCellEditor(): void {
- // container element
- const containerElement = (this._containerElement = document.createElement('div'));
- containerElement.classList.add(SHEET_CELL_EDITOR_CLASS_NAME);
- containerElement.style.position = 'fixed';
- containerElement.style.boxSizing = 'border-box';
- containerElement.style.background = 'white';
- containerElement.style.outline = '2px solid #a8c7fa';
- containerElement.style.border = '2px solid #0b57d0';
- containerElement.setAttribute('spellcheck', 'false');
-
- // set basic docModel
- // use the model to create a UniverDoc
- const cellEditorDoc = this._currentUniverService.createDoc({
- ...createEmptyDocSnapshot(),
- id: SHEET_CELL_EDITOR_MODEL_ID,
- documentStyle: {
- marginLeft: 2,
- marginTop: 2,
- marginRight: 2,
- marginBottom: 2,
- marginHeader: 2,
- marginFooter: 2,
- pageSize: {
- height: 200,
- width: 200,
- },
- },
- });
- const docModel = cellEditorDoc;
-
- // rendering engine add document canvas
- const engine = (this._editorEngine = new Engine());
- const scene = (this._editorScene = new Scene('CELL_EDITOR', engine, {
- width: 200,
- height: 100,
- }));
- scene.openTransformer();
- const viewMain = new Viewport('CELL_EDITOR', scene, {
- left: 0,
- top: 0,
- bottom: 0,
- right: 0,
- isWheelPreventDefaultX: true,
- });
- scene.addViewport(viewMain).attachControl();
- scene.addLayer(Layer.create(scene, [], 0), Layer.create(scene, [], 2));
- const docsView = this._injector.createInstance(DocsView, docModel);
- docsView.initialize(scene);
- // docsView.getDocs().enableEditor();
-
- engine.runRenderLoop(() => {
- scene.render();
- });
-
- document.body.appendChild(this._containerElement);
- engine.setContainer(this._containerElement);
- }
-
- private _initPasteHandler(): void {
- this._textSelectionRenderManager.enableSelection();
-
- // const editor = this._getCellEditor();
- // if (!editor) {
- // throw new Error('[DesktopCellEditorService]: Could not init paste handler, cell editor not found!');
- // }
-
- this._textSelectionRenderManager.onPaste$
- .pipe(takeUntil(this.dispose$))
- .subscribe((config: Nullable<IEditorInputConfig>) => {
- console.log('paste event', config?.event);
- // TODO: handle paste event from the editor input element
- });
- }
-
- private _positionCellEditor(currentCell: ISelectionCell) {
- const cellInfo = this._selectionTransformerShapeManager.convertCellRangeToInfo(currentCell)!;
-
- const render = this._renderManagerService.getCurrent();
-
- if (render == null) {
- return;
- }
-
- const position = getPositionOfCurrentCell(cellInfo, render.engine, render?.scene);
-
- this._containerElement!.style.display = 'block';
- this._containerElement!.style.left = `${position.left}px`;
- this._containerElement!.style.top = `${position.top}px`;
- this._containerElement!.style.minHeight = `${position.minHeight}px`;
- this._containerElement!.style.minWidth = `${position.minWidth}px`;
- this._containerElement!.style.maxHeight = `${position.maxHeight}px`;
- this._containerElement!.style.maxWidth = `${position.maxWidth}px`;
-
- this._editorEngine!.resize();
- this._containerElement!.focus();
-
- return position;
- }
-
- private _hideCellEditor(): void {
- this._containerElement!.style.display = 'none';
- }
-
- private _initListeners(): void {
- const render = this._renderManagerService.getCurrent();
-
- if (render == null) {
- return;
- }
-
- const main = render.mainComponent;
-
- if (main == null) {
- return;
- }
- const onDbClickObserver = main.onDblclickObserver.add((evt: IPointerEvent | IMouseEvent) => {
- if (evt.button !== 2) {
- this.enterEditing();
- evt.preventDefault();
- }
- });
- const pointerDownObserver = main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this.quitEditing();
- });
-
- this.disposeWithMe(
- toDisposable(() => {
- main.onDblclickObserver.remove(onDbClickObserver);
- main.onPointerDownObserver.remove(pointerDownObserver);
- })
- );
- }
-
- private async _updateDocumentModelFromCellModel(position: Nullable<ICellPosition>): Promise<void> {
- const cellEditorModel = this._currentUniverService.getUniverDocInstance(SHEET_CELL_EDITOR_MODEL_ID);
-
- if (!cellEditorModel) {
- throw new Error('Cell editor model not found!');
- }
-
- const cellValue = this._getCellValue();
- const snapshot: IDocumentData = {
- id: SHEET_CELL_EDITOR_MODEL_ID,
- body: {
- dataStream: `${cellValue}\r\n\0`,
- },
- documentStyle: {
- marginLeft: 2,
- marginTop: 2,
- marginRight: 2,
- marginBottom: 2,
- marginHeader: 2,
- marginFooter: 2,
- pageSize: {
- height: (position?.minHeight || 0) - 2 * 2,
- width: (position?.minWidth || 0) - 2 * 2,
- },
- },
- };
-
- return this._commandService.executeCommand<ICoverCommandParams, void>(CoverCommand.id, {
- unitId: SHEET_CELL_EDITOR_MODEL_ID,
- snapshot,
- clearUndoRedoStack: true,
- });
- }
-
- private _getCellValue(): string {
- const range = this._getActiveRange();
- if (!range) {
- return '';
- }
-
- const value = range && range.getDisplayValue();
- if (typeof value === 'string') {
- return value;
- }
-
- if (typeof value === 'object' && value !== null) {
- return handleJsonToDom(value);
- }
-
- return '';
- }
-
- private _getCellStyle(): Nullable<IStyleData> {
- return this._getActiveRange()?.getTextStyle();
- }
-
- // private _enableEditor(): void {
- // return this._getDocObject()?.document
- // .enableEditor();
- // }
-
- // private _getCellEditor(): Nullable<DocsEditor> {
- // return this._injector
- // .get(DocsViewManagerService)
- // .getDocsView(SHEET_CELL_EDITOR_MODEL_ID)
- // ?.getDocs()
- // .getEditor();
- // }
-
- private _getActiveRange() {
- const primary = this._selectionManagerService.getLast()?.primary;
- if (!primary) return;
- let { actualRow, actualColumn } = primary;
-
- if (primary.isMerged) {
- actualRow = primary.startRow;
- actualColumn = primary.startColumn;
- }
-
- return this._currentUniverService
- .getCurrentUniverSheetInstance()
-
- .getActiveSheet()
- .getRange(actualRow, actualColumn);
- }
-
- private _getDocObject() {
- return getDocObject(this._currentUniverService, this._renderManagerService);
- }
-}
-
-function getRangeFromPrimary(primary: ISelectionCell): IRange {
- let startRow: number;
- let startColumn: number;
-
- let endRow: number;
-
- let endColumn: number;
-
- if (primary.isMerged) {
- startRow = primary.startRow;
- startColumn = primary.startColumn;
-
- endRow = primary.endRow;
- endColumn = primary.endColumn;
- } else {
- startRow = endRow = primary.actualRow;
- startColumn = endColumn = primary.actualColumn;
- }
-
- return {
- startRow,
- startColumn,
- endRow,
- endColumn,
- };
-}
diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor.command.ts b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor.command.ts
deleted file mode 100644
index 13fa6f213f..0000000000
--- a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor.command.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { CommandType, ICommand } from '@univerjs/core';
-
-import { ICellEditorService } from './cell-editor.service';
-
-export const QuitCellEditorCommand: ICommand = {
- id: 'sheet.command.quit-cell-editor',
- type: CommandType.COMMAND,
- handler: async (accessor) => {
- const cellEditorService = accessor.get(ICellEditorService);
- cellEditorService.quitEditing();
-
- return true;
- },
-};
diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor.service.ts b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor.service.ts
deleted file mode 100644
index f0e10dcdae..0000000000
--- a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor.service.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { createIdentifier } from '@wendellhu/redi';
-
-// On mobile platforms cell editor maybe implemented with a very different tech
-// stack. So cell editor service must be an abstract dependency.
-
-export interface ICellEditorService {
- enterEditing(): void;
- quitEditing(): void;
-}
-
-export const ICellEditorService = createIdentifier<ICellEditorService>('univer.cell-editor-service');
diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/desktop.module.less b/packages/ui-plugin-sheets/src/services/cell-editor/desktop.module.less
deleted file mode 100644
index 6d2d89f171..0000000000
--- a/packages/ui-plugin-sheets/src/services/cell-editor/desktop.module.less
+++ /dev/null
@@ -1,3 +0,0 @@
-.univer-cell-editor-container {
- position: fixed;
-}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/utils.ts b/packages/ui-plugin-sheets/src/services/cell-editor/utils.ts
deleted file mode 100644
index 67e9b877d7..0000000000
--- a/packages/ui-plugin-sheets/src/services/cell-editor/utils.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Engine, Scene } from '@univerjs/base-render';
-import { VIEWPORT_KEY } from '@univerjs/base-sheets';
-import { ISelectionCellWithCoord } from '@univerjs/core';
-
-export interface ICellPosition {
- left: number;
- top: number;
- minWidth: number;
- minHeight: number;
- maxWidth: number;
- maxHeight: number;
-}
-
-export function getPositionOfCurrentCell(
- currentCell: ISelectionCellWithCoord,
- renderingEngine: Engine,
- scene: Scene
-): ICellPosition {
- let startX: number;
- let endX: number;
- let startY: number;
- let endY: number;
- const mergeInfo = currentCell.mergeInfo;
- if (currentCell.isMerged) {
- startX = mergeInfo.startX;
- endX = mergeInfo.endX;
- startY = mergeInfo.startY;
- endY = mergeInfo.endY;
- } else {
- startX = currentCell.startX;
- endX = currentCell.endX;
- startY = currentCell.startY;
- endY = currentCell.endY;
- }
-
- if (currentCell.isMergedMainCell) {
- endX = mergeInfo.endX;
- endY = mergeInfo.endY;
- }
-
- const mainView = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
- const scrollX = mainView?.actualScrollX || 0;
- const scrollY = mainView?.actualScrollY || 0;
-
- const canvasElement = renderingEngine.getCanvasElement();
- const sheetContentRect = canvasElement.getBoundingClientRect();
-
- return {
- left: startX - scrollX,
- top: startY - scrollY + 40, // FIXME: dirty hack here
- minWidth: endX - startX,
- minHeight: endY - startY,
- maxWidth: sheetContentRect.width - startX + scrollX,
- maxHeight: sheetContentRect.height - startY + scrollY,
- };
-}
diff --git a/packages/ui-plugin-sheets/src/services/context/context.ts b/packages/ui-plugin-sheets/src/services/context/context.ts
deleted file mode 100644
index 9dcecc2912..0000000000
--- a/packages/ui-plugin-sheets/src/services/context/context.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * The situation where sheet editor is activated (cursor blinking).
- *
- * Note tha sheet cell editor is always focused when a UniverSheet instance is focused (and other input element
- * is not `document.activeElement`).
- */
-export const SHEET_EDITOR_ACTIVATED = 'FOCUSING_DOC_SHEET_EDITOR_ACTIVATED';
-
-export const SHEET_EDITOR_ACTIVATED_FORMULA_INPUT = 'FOCUSING_DOC_SHEET_EDITOR_ACTIVATED_FORMULA_INPUT';
-
-export const SHEET_EDITOR_ACTIVATED_NORMAL_INPUT = 'FOCUSING_DOC_SHEET_EDITOR_ACTIVATED_NORMAL_INPUT';
diff --git a/packages/base-sheets/src/services/editor-bridge.service.ts b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
similarity index 83%
rename from packages/base-sheets/src/services/editor-bridge.service.ts
rename to packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
index abca0c18dd..c3239fe53d 100644
--- a/packages/base-sheets/src/services/editor-bridge.service.ts
+++ b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
@@ -1,18 +1,22 @@
-import { DeviceInputEventType, DocumentSkeleton } from '@univerjs/base-render';
-import { ISelectionCellWithCoord, Nullable } from '@univerjs/core';
+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';
export interface IEditorBridgeServiceVisibleParam {
visible: boolean;
eventType: DeviceInputEventType;
+ keycode?: KeyCode;
}
export interface IEditorBridgeServiceParam {
- unitId?: string;
- sheetId?: string;
- primaryWithCoord: Nullable<ISelectionCellWithCoord>;
- docSkeleton: Nullable<DocumentSkeleton>;
+ unitId: string;
+ sheetId: string;
+ row: number;
+ column: number;
+ position: IPosition;
+ documentLayoutObject: IDocumentLayoutObject;
}
export interface IEditorBridgeService {
@@ -23,7 +27,7 @@ export interface IEditorBridgeService {
getState(): Readonly<Nullable<IEditorBridgeServiceParam>>;
show(openType: DeviceInputEventType): void;
hide(): void;
- isVisible(): void;
+ isVisible(): IEditorBridgeServiceVisibleParam;
}
export class EditorBridgeService implements IEditorBridgeService, IDisposable {
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 6b1a5b5eb0..ffa3ccc7b1 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
@@ -8,18 +8,26 @@ export interface ICellEditorManagerParam extends Partial<IPosition> {
export interface ICellEditorManagerService {
state$: Observable<Nullable<ICellEditorManagerParam>>;
+ focus$: Observable<boolean>;
dispose(): void;
setState(param: ICellEditorManagerParam): void;
getState(): Readonly<Nullable<ICellEditorManagerParam>>;
+ setFocus(param: boolean): void;
}
export class CellEditorManagerService implements ICellEditorManagerService, IDisposable {
private _state: Nullable<ICellEditorManagerParam> = null;
+ private _focus: boolean = false;
+
private readonly _state$ = new BehaviorSubject<Nullable<ICellEditorManagerParam>>(null);
readonly state$ = this._state$.asObservable();
+ private readonly _focus$ = new BehaviorSubject<boolean>(this._focus);
+
+ readonly focus$ = this._focus$.asObservable();
+
dispose(): void {
this._state$.complete();
this._state = null;
@@ -35,6 +43,11 @@ export class CellEditorManagerService implements ICellEditorManagerService, IDis
return this._state;
}
+ setFocus(param: boolean = false) {
+ this._focus = param;
+ this._focus$.next(param);
+ }
+
private _refresh(param: ICellEditorManagerParam): void {
this._state$.next(param);
}
diff --git a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
index b0e089edd5..c5ecb38b79 100644
--- a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
@@ -5,11 +5,15 @@ import { filter } from 'rxjs/operators';
import { SHEET_UI_PLUGIN_NAME } from './Basics';
import { SheetClipboardController } from './controller/clipboard/clipboard.controller';
import { SheetContextMenuController } from './controller/contextmenu/contextmenu.controller';
+import { EndEditController } from './controller/editor/end-edit.controller';
+import { InitializeEditorController } from './controller/editor/initialize-editor.controller';
import { StartEditController } from './controller/editor/start-edit.controller';
+import { EditorBridgeController } from './controller/editor-bridge.controller';
import { SheetUIController } from './controller/sheet-ui.controller';
import { en } from './Locale';
import { ISheetClipboardService, SheetClipboardService } from './services/clipboard/clipboard.service';
import { CellEditorManagerService, ICellEditorManagerService } from './services/editor/cell-editor-manager.service';
+import { EditorBridgeService, IEditorBridgeService } from './services/editor-bridge.service';
import { ISheetBarService, SheetBarService } from './services/sheetbar/sheetbar.service';
export class SheetUIPlugin extends Plugin {
@@ -33,6 +37,7 @@ export class SheetUIPlugin extends Plugin {
[
// services
// [ICellEditorService, { useClass: DesktopCellEditorService }],
+ [IEditorBridgeService, { useClass: EditorBridgeService }],
[ISheetClipboardService, { useClass: SheetClipboardService }],
[ISheetBarService, { useClass: SheetBarService }],
// [ITextSelectionRenderManager, { useClass: TextSelectionRenderManager }],
@@ -40,10 +45,13 @@ export class SheetUIPlugin extends Plugin {
[ICellEditorManagerService, { useClass: CellEditorManagerService }],
// controllers
+ [EditorBridgeController],
[SheetClipboardController],
[SheetContextMenuController],
[SheetUIController],
+ [InitializeEditorController],
[StartEditController],
+ [EndEditController],
] as Dependency[]
).forEach((d) => injector.add(d));
}