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.

Developer doc editor (#89)

Univera823a3bd5e78
diff --git a/packages/base-docs/src/Controller/DocumentController.ts b/packages/base-docs/src/Controller/DocumentController.ts
index 651d923274..1cc5c9b29a 100644
--- a/packages/base-docs/src/Controller/DocumentController.ts
+++ b/packages/base-docs/src/Controller/DocumentController.ts
@@ -1,9 +1,10 @@
+import { Injector } from '@wendellhu/redi';
import { InputController } from './InputController';
export class DocumentController {
private readonly _inputController: InputController;
- constructor() {
- // this._inputController = new InputController();
+ constructor(injector: Injector) {
+ this._inputController = injector.createInstance(InputController) as InputController;
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-docs/src/Controller/InputController.ts b/packages/base-docs/src/Controller/InputController.ts
index 28d499ffbe..ca345fc990 100644
--- a/packages/base-docs/src/Controller/InputController.ts
+++ b/packages/base-docs/src/Controller/InputController.ts
@@ -1,27 +1,70 @@
-import { Documents, IDocumentSkeletonSpan, SpanType, TextSelection } from '@univerjs/base-render';
-import { KeyboardKeyType, Nullable } from '@univerjs/core';
+import { Documents, IDocumentSkeletonLine, IDocumentSkeletonSpan, IEditorInputConfig, SpanType, TextSelection } from '@univerjs/base-render';
+import { DataStreamTreeTokenType, DocumentModel, ICurrentUniverService, IParagraph, Nullable, Observable } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { CanvasView } from '../View/Render/CanvasView';
+import { DocsView } from '../View/Render/Views';
+
+enum KeyboardKeyType {
+ Backspace = 'Backspace',
+ Delete = 'Delete',
+ Enter = 'Enter',
+ Copy = 'c',
+ Paste = 'v',
+ ArrowUp = 'ArrowUp',
+ ArrowDown = 'ArrowDown',
+ ArrowLeft = 'ArrowLeft',
+ ArrowRight = 'ArrowRight',
+}
export class InputController {
private _previousIMEContent: string = '';
private _previousIMEStart: number;
- constructor() {
+ private _currentSpan: Nullable<IDocumentSkeletonSpan>;
+
+ private _currentSpanPosBack: boolean = false;
+
+ constructor(@Inject(CanvasView) private readonly _CanvasView: CanvasView, @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService) {
this._initialize();
}
- // eslint-disable-next-line max-lines-per-function
private _initialize() {
- const events = this._plugin.getInputEvent();
+ const docsView = this._CanvasView.getDocsView() as DocsView;
+ const events = docsView.getDocs().getEditorInputEvent();
+
+ const docsModel = this._currentUniverService.getCurrentUniverDocInstance().getDocument();
+
if (!events) {
return;
}
- const { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable } = events;
+ const { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable, onSelectionStartObservable } =
+ events;
+
+ this._initialKeydown(onKeydownObservable, docsModel);
+ this._initialInput(onInputObservable, docsModel);
+
+ this._initialComposition(onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, docsModel);
+
+ onSelectionStartObservable.add((nodeInfo) => {
+ if (nodeInfo === false) {
+ this._currentSpan = null;
+ } else {
+ this._currentSpan = nodeInfo.node;
+ }
+ });
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _initialKeydown(onKeydownObservable: Observable<IEditorInputConfig>, docsModel: DocumentModel) {
+ // eslint-disable-next-line max-lines-per-function
onKeydownObservable.add((config) => {
const { event, document, activeSelection, selectionList } = config;
const e = event as KeyboardEvent;
+ const isCtrl = e.ctrlKey;
+
const activeRange = activeSelection?.getRange();
const segmentId = activeSelection?.segmentId;
@@ -34,7 +77,7 @@ export class InputController {
const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack } = activeRange;
- if (e.key === KeyboardKeyType.backspace) {
+ if (e.key === KeyboardKeyType.Backspace) {
let cursor = cursorStart;
if (isStartBack === true) {
@@ -45,56 +88,146 @@ export class InputController {
cursor += 1;
}
- const selectionRemain = document.remainActiveSelection();
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
// const content = document.findNodeByCharIndex(cursor - 1)?.content || '';
- docsModel.deleteText(activeRange, segmentId);
+ docsModel.delete(activeRange, segmentId);
skeleton.calculate();
const span = document.findNodeByCharIndex(cursor - 1);
- this._adjustSelection(document, selectionRemain, span);
+ this._adjustSelection(document as Documents, selectionRemain, span);
this._resetIME();
+ } else if (e.key === KeyboardKeyType.Enter) {
+ // split paragraph
+ let cursor = cursorStart;
+
+ if (isStartBack === false) {
+ cursor += 1;
+ }
+
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
+
+ docsModel.insert(
+ {
+ dataStream: DataStreamTreeTokenType.PARAGRAPH,
+ paragraphs: this._generateParagraph(DataStreamTreeTokenType.PARAGRAPH),
+ },
+ activeRange,
+ segmentId
+ );
+
+ skeleton.calculate();
+
+ const span = document.findNodeByCharIndex(cursor + 1);
+
+ this._adjustSelection(document as Documents, selectionRemain, span, true);
+ } else if (e.key === KeyboardKeyType.ArrowUp) {
+ let cursor = cursorStart;
+ if (isStartBack === true) {
+ cursor -= 1;
+ }
+ const span = document.findNodeByCharIndex(cursor);
+ const newSpan = this._getTopOrBottomSpan(span, false);
+ if (newSpan == null) {
+ return;
+ }
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
+ this._adjustSelection(document as Documents, selectionRemain, newSpan, false, true);
+ } else if (e.key === KeyboardKeyType.ArrowDown) {
+ let cursor = cursorStart;
+ if (isStartBack === true) {
+ cursor -= 1;
+ }
+ const span = document.findNodeByCharIndex(cursor);
+ const newSpan = this._getTopOrBottomSpan(span, true);
+ if (newSpan == null) {
+ return;
+ }
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
+ this._adjustSelection(document as Documents, selectionRemain, newSpan, false, true);
+ } else if (e.key === KeyboardKeyType.ArrowLeft) {
+ let cursor = cursorStart;
+ if (isStartBack === true) {
+ cursor -= 1;
+ }
+ const span = document.findNodeByCharIndex(cursor - 1);
+ this._currentSpan = span;
+ if (span == null) {
+ return;
+ }
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
+ this._adjustSelection(document as Documents, selectionRemain, span, false, true);
+ } else if (e.key === KeyboardKeyType.ArrowRight) {
+ // copy handler
+ let cursor = cursorStart;
+ if (isStartBack === true) {
+ cursor -= 1;
+ }
+ const span = document.findNodeByCharIndex(cursor + 1);
+ this._currentSpan = span;
+ if (span == null) {
+ return;
+ }
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
+ this._adjustSelection(document as Documents, selectionRemain, span, false, true);
+ } else if (e.key === KeyboardKeyType.Copy && isCtrl) {
+ // copy handler
+ } else if (e.key === KeyboardKeyType.Paste && isCtrl) {
+ // paste handler
}
});
+ }
+ private _initialInput(onInputObservable: Observable<IEditorInputConfig>, docsModel: DocumentModel) {
onInputObservable.add((config) => {
const { event, content = '', document, activeSelection, selectionList } = config;
+ const e = event as InputEvent;
+
const activeRange = activeSelection?.getRange();
const skeleton = document.getSkeleton();
const segmentId = activeSelection?.segmentId;
+ if (e.data == null) {
+ return;
+ }
+
if (!skeleton || !activeRange) {
return;
}
const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack } = activeRange;
- if (isCollapse) {
- let cursor = cursorStart;
+ let cursor = cursorStart;
- if (isStartBack === false) {
- cursor += 1;
- }
+ if (isStartBack === false) {
+ cursor += 1;
+ }
- const selectionRemain = document.remainActiveSelection();
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
- docsModel.insertText(content, activeRange, segmentId);
+ docsModel.insert({ dataStream: content }, activeRange, segmentId);
- skeleton.calculate();
+ skeleton.calculate();
- const span = document.findNodeByCharIndex(cursor + content.length - 1);
+ const span = document.findNodeByCharIndex(cursor + content.length - 1);
- this._adjustSelection(document, selectionRemain, span);
- }
+ this._adjustSelection(document as Documents, selectionRemain, span);
});
+ }
+ private _initialComposition(
+ onCompositionstartObservable: Observable<IEditorInputConfig>,
+ onCompositionupdateObservable: Observable<IEditorInputConfig>,
+ onCompositionendObservable: Observable<IEditorInputConfig>,
+ docsModel: DocumentModel
+ ) {
onCompositionstartObservable.add((config) => {
const { activeSelection, selectionList } = config;
@@ -108,21 +241,21 @@ export class InputController {
let cursor = cursorStart;
- if (isStartBack === false) {
- cursor += 1;
+ if (isStartBack === true) {
+ cursor -= 1;
}
this._previousIMEStart = cursor;
-
- // console.log('_previousIMEStart', this._previousIMEStart);
});
onCompositionupdateObservable.add((config) => {
- const { event, document } = config;
+ const { event, document, activeSelection } = config;
- let cursor = this._previousIMEStart - 1;
+ const cursor = this._previousIMEStart;
const skeleton = document.getSkeleton();
+ const segmentId = activeSelection?.segmentId;
+
if (!skeleton) {
return;
}
@@ -135,32 +268,15 @@ export class InputController {
return;
}
- const selectionRemain = document.remainActiveSelection();
-
- // const increaseText = this._getIncreaseText(content, this._previousIMEContent);
-
- // docsModel.insertText(increaseText, cursor);
+ const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
- docsModel.updateText(content, this._previousIMEContent, cursor);
+ docsModel.IMEInput(content, this._previousIMEContent.length, cursor, segmentId);
skeleton.calculate();
const span = document.findNodeByCharIndex(cursor + content.length);
- this._adjustSelection(document, selectionRemain, span);
-
- console.log(
- 'Compositionupdate',
- content,
- this._previousIMEContent,
- e.data,
- this._previousIMEStart,
- cursor,
- selectionRemain,
- span,
- skeleton.getSkeletonData(),
- skeleton
- );
+ this._adjustSelection(document as Documents, selectionRemain, span);
this._previousIMEContent = content;
});
@@ -170,6 +286,195 @@ export class InputController {
});
}
+ private _getTopOrBottomSpan(span: Nullable<IDocumentSkeletonSpan>, direction: boolean) {
+ const referenceSpan = this._currentSpan;
+ if (referenceSpan == null || span == null) {
+ return;
+ }
+
+ const offsetLeft = this._getSpanLeftOffsetInLine(referenceSpan);
+
+ const line = this._getNextOrPrevLine(span, direction);
+
+ if (line == null) {
+ return;
+ }
+
+ const newSpan = this._matchSpanByLeftOffset(line, offsetLeft);
+
+ return newSpan;
+ }
+
+ private _getSpanLeftOffsetInLine(span: IDocumentSkeletonSpan) {
+ const divide = span.parent;
+
+ if (divide == null) {
+ return -Infinity;
+ }
+
+ const divideLeft = divide.left;
+
+ const { left, width } = span;
+
+ return divideLeft + left + width;
+ }
+
+ private _matchSpanByLeftOffset(line: IDocumentSkeletonLine, offsetLeft: number) {
+ const nearestNode: {
+ span?: IDocumentSkeletonSpan;
+ distance: number;
+ } = {
+ distance: Infinity,
+ };
+ for (const divide of line.divides) {
+ const divideLeft = divide.left;
+ for (const span of divide.spanGroup) {
+ const { left, width } = span;
+ const leftSide = divideLeft + left;
+ const rightSide = leftSide + width;
+ if (offsetLeft >= leftSide && offsetLeft <= rightSide) {
+ return span;
+ }
+
+ const distance = Math.abs(offsetLeft - (leftSide + rightSide) / 2);
+ if (distance < nearestNode.distance) {
+ nearestNode.span = span;
+ nearestNode.distance = distance;
+ }
+ }
+ }
+
+ return nearestNode.span;
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _getNextOrPrevLine(span: IDocumentSkeletonSpan, direction: boolean) {
+ const divide = span.parent;
+ if (divide == null) {
+ return;
+ }
+
+ const line = divide.parent;
+ if (line == null) {
+ return;
+ }
+
+ const column = line.parent;
+ if (column == null) {
+ return;
+ }
+
+ const currentLineIndex = column.lines.indexOf(line);
+
+ if (currentLineIndex === -1) {
+ return;
+ }
+
+ let newLine: IDocumentSkeletonLine;
+
+ if (direction === true) {
+ newLine = column.lines[currentLineIndex + 1];
+ } else {
+ newLine = column.lines[currentLineIndex - 1];
+ }
+
+ if (newLine != null) {
+ return newLine;
+ }
+
+ const section = column.parent;
+
+ if (section == null) {
+ return;
+ }
+
+ const currentColumnIndex = section.columns.indexOf(column);
+
+ if (currentColumnIndex === -1) {
+ return;
+ }
+
+ if (direction === true) {
+ newLine = section.columns[currentColumnIndex + 1]?.lines[0];
+ } else {
+ const prevColumnLines = section.columns?.[currentColumnIndex - 1]?.lines;
+ newLine = prevColumnLines?.[prevColumnLines.length - 1];
+ }
+
+ if (newLine != null) {
+ return newLine;
+ }
+
+ const page = section.parent;
+
+ if (page == null) {
+ return;
+ }
+
+ const currentSectionIndex = page.sections.indexOf(section);
+
+ if (currentSectionIndex === -1) {
+ return;
+ }
+
+ if (direction === true) {
+ newLine = page.sections[currentSectionIndex - 1]?.columns[0]?.lines[0];
+ } else {
+ const prevColumns = page.sections?.[currentSectionIndex - 1]?.columns;
+ const column = prevColumns?.[prevColumns.length - 1];
+ const prevColumnLines = column?.lines;
+ newLine = prevColumnLines?.[prevColumnLines.length - 1];
+ }
+
+ if (newLine != null) {
+ return newLine;
+ }
+
+ const skeleton = page.parent;
+
+ if (skeleton == null) {
+ return;
+ }
+
+ const currentPageIndex = skeleton.pages.indexOf(page);
+
+ if (currentPageIndex === -1) {
+ return;
+ }
+
+ if (direction === true) {
+ newLine = skeleton.pages[currentPageIndex + 1]?.sections[0]?.columns[0]?.lines[0];
+ } else {
+ const prevSections = skeleton.pages[currentPageIndex - 1]?.sections;
+ if (prevSections == null) {
+ return;
+ }
+ const prevColumns = prevSections[prevSections.length - 1]?.columns;
+ const column = prevColumns[prevColumns.length - 1];
+ const prevColumnLines = column?.lines;
+ newLine = prevColumnLines[prevColumnLines.length - 1];
+ }
+
+ if (newLine != null) {
+ return newLine;
+ }
+ }
+
+ private _generateParagraph(dataStream: string) {
+ const paragraphs: IParagraph[] = [];
+ for (let i = 0, len = dataStream.length; i < len; i++) {
+ const char = dataStream[i];
+ if (char !== DataStreamTreeTokenType.PARAGRAPH) {
+ continue;
+ }
+
+ paragraphs.push({
+ startIndex: i,
+ });
+ }
+ return paragraphs;
+ }
+
private _resetIME() {
this._previousIMEContent = '';
@@ -181,7 +486,7 @@ export class InputController {
return current.slice(oldLen);
}
- private _adjustSelection(document: Documents, selectionRemain?: TextSelection, span?: Nullable<IDocumentSkeletonSpan>) {
+ private _adjustSelection(document: Documents, selectionRemain?: TextSelection, span?: Nullable<IDocumentSkeletonSpan>, isBack = false, isSyncScroll = false) {
if (span == null) {
return;
}
@@ -196,7 +501,7 @@ export class InputController {
position.span += 1;
}
- const newPos = { ...position, isBack: false };
+ const newPos = { ...position, isBack };
document.addSelection(selectionRemain);
@@ -206,6 +511,10 @@ export class InputController {
selectionRemain.refresh(document);
+ if (isSyncScroll) {
+ document.scrollBySelection();
+ }
+
document.syncSelection();
}
@@ -220,4 +529,4 @@ export class InputController {
return spanGroup[0]?.spanType === SpanType.LIST;
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-docs/src/DocPlugin.ts b/packages/base-docs/src/DocPlugin.ts
index 2b7e5595b3..9fdaa64b6a 100644
--- a/packages/base-docs/src/DocPlugin.ts
+++ b/packages/base-docs/src/DocPlugin.ts
@@ -61,7 +61,7 @@ export class DocPlugin extends Plugin<DocPluginObserve> {
initController() {
this._toolbarControl = new ToolbarController();
this._infoBarControl = new InfoBarController();
- this._documentController = new DocumentController();
+ this._documentController = new DocumentController(this._injector);
}
initCanvasView() {
@@ -132,4 +132,4 @@ export class DocPlugin extends Plugin<DocPluginObserve> {
docInjector.add(d);
});
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-docs/src/View/Render/BaseView.ts b/packages/base-docs/src/View/Render/BaseView.ts
index a37d9f1623..1b0a8ada4c 100644
--- a/packages/base-docs/src/View/Render/BaseView.ts
+++ b/packages/base-docs/src/View/Render/BaseView.ts
@@ -32,4 +32,4 @@ export enum CANVAS_VIEW_KEY {
DOCS_VIEW = 'docsView',
}
-export const CanvasViewRegistry = Registry.create();
\ No newline at end of file
+export const CanvasViewRegistry = Registry.create();
diff --git a/packages/base-docs/src/View/Render/CanvasView.ts b/packages/base-docs/src/View/Render/CanvasView.ts
index 4c41cd5054..53ef5fcf90 100644
--- a/packages/base-docs/src/View/Render/CanvasView.ts
+++ b/packages/base-docs/src/View/Render/CanvasView.ts
@@ -91,4 +91,4 @@ export class CanvasView {
this._views.push(viewFactory.create(scene, this._injector));
});
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-docs/src/View/Render/Views/DocsView.ts b/packages/base-docs/src/View/Render/Views/DocsView.ts
index 6708f4f137..6ddaca0009 100644
--- a/packages/base-docs/src/View/Render/Views/DocsView.ts
+++ b/packages/base-docs/src/View/Render/Views/DocsView.ts
@@ -1,5 +1,5 @@
import { Documents, DocumentSkeleton, IDocumentSkeletonDrawing, Picture, Scene } from '@univerjs/base-render';
-import { CommandManager, DocumentModel, ICurrentUniverService, IDocumentData, LocaleService } from '@univerjs/core';
+import { CommandManager, DocumentModel, ICurrentUniverService, LocaleService } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
import { BaseView, CanvasViewRegistry, CANVAS_VIEW_KEY } from '../BaseView';
@@ -57,7 +57,7 @@ export class DocsView extends BaseView {
const docsModel = this._currentUniverService.getCurrentUniverDocInstance().getDocument();
- const documentSkeleton = this._buildSkeleton(docsModel.getSnapshot());
+ const documentSkeleton = this._buildSkeleton(docsModel);
const documents = new Documents(DOCS_VIEW_KEY.MAIN, documentSkeleton);
documents.zIndex = 1000;
@@ -117,11 +117,8 @@ export class DocsView extends BaseView {
documents.enableEditor();
}
- private _buildSkeleton(snapshot: IDocumentData) {
- const docModel = new DocumentModel(snapshot, this._commandManager);
- const docsSkeleton = DocumentSkeleton.create(docModel, this._localeService);
-
- return docsSkeleton;
+ private _buildSkeleton(model: DocumentModel) {
+ return DocumentSkeleton.create(model, this._localeService);
}
}
@@ -129,10 +126,10 @@ export class DocsViewFactory {
readonly zIndex = 0;
create(scene: Scene, injector: Injector): DocsView {
- const docsView = injector.createInstance(DocsView);
+ const docsView = injector.createInstance(DocsView) as DocsView;
docsView.initialize(scene);
return docsView;
}
}
-CanvasViewRegistry.add(new DocsViewFactory());
\ No newline at end of file
+CanvasViewRegistry.add(new DocsViewFactory());
diff --git a/packages/base-docs/src/View/Render/Views/DrawingsView.ts b/packages/base-docs/src/View/Render/Views/DrawingsView.ts
index da9352c18f..9b704b9e4b 100644
--- a/packages/base-docs/src/View/Render/Views/DrawingsView.ts
+++ b/packages/base-docs/src/View/Render/Views/DrawingsView.ts
@@ -100,11 +100,13 @@ export class DrawingsView extends BaseView {
}
class DrawingsViewFactory {
- zIndex = 3;
+ readonly zIndex = 2;
- create(_scene: Scene, injector: Injector) {
- return injector.createInstance(DrawingsView);
+ create(scene: Scene, injector: Injector) {
+ const drawingsView = injector.createInstance(DrawingsView) as DrawingsView;
+ drawingsView.initialize(scene);
+ return drawingsView;
}
}
-CanvasViewRegistry.add(new DrawingsViewFactory());
\ No newline at end of file
+CanvasViewRegistry.add(new DrawingsViewFactory());
diff --git a/packages/base-docs/src/View/Render/Views/PageView.ts b/packages/base-docs/src/View/Render/Views/PageView.ts
index e46fbf762b..4bab2810d9 100644
--- a/packages/base-docs/src/View/Render/Views/PageView.ts
+++ b/packages/base-docs/src/View/Render/Views/PageView.ts
@@ -38,9 +38,13 @@ export class PageView extends BaseView {
}
class PageViewFactory {
+ readonly zIndex = 1;
+
create(scene: Scene, injector: Injector) {
- injector.createInstance(PageView);
+ const pageView = injector.createInstance(PageView) as PageView;
+ pageView.initialize(scene);
+ return pageView;
}
}
-CanvasViewRegistry.add(new PageViewFactory());
\ No newline at end of file
+CanvasViewRegistry.add(new PageViewFactory());
diff --git a/packages/base-docs/src/View/Render/Views/TestView.ts b/packages/base-docs/src/View/Render/Views/TestView.ts
index fe60b2a68b..1532d6bd48 100644
--- a/packages/base-docs/src/View/Render/Views/TestView.ts
+++ b/packages/base-docs/src/View/Render/Views/TestView.ts
@@ -4,13 +4,12 @@ import { BaseView, CanvasViewRegistry } from '../BaseView';
const PAGE_VIEW_BACKGROUND = 'page_view_background';
export class PageView extends BaseView {
- zIndex = 3;
+ override zIndex = 3;
- viewKey = PAGE_VIEW_BACKGROUND;
+ override viewKey = PAGE_VIEW_BACKGROUND;
- protected _initialize() {
+ protected override _initialize() {
const scene = this.getScene();
- const context = this.getContext();
const polygon = new RegularPolygon('TEXT_POLYGON_KEY_PREFIX_TEST', {
pointsGroup: [
diff --git a/packages/base-render/src/BaseObject.ts b/packages/base-render/src/BaseObject.ts
index 21d87e11a6..79b556303c 100644
--- a/packages/base-render/src/BaseObject.ts
+++ b/packages/base-render/src/BaseObject.ts
@@ -165,12 +165,12 @@ export abstract class BaseObject {
}
get ancestorScaleX() {
- let pScale: number = this.getParent()?.ancestorScaleX || 1;
+ const pScale: number = this.getParent()?.ancestorScaleX || 1;
return this.scaleX * pScale;
}
get ancestorScaleY() {
- let pScale: number = this.getParent()?.ancestorScaleY || 1;
+ const pScale: number = this.getParent()?.ancestorScaleY || 1;
return this.scaleY * pScale;
}
@@ -191,6 +191,7 @@ export abstract class BaseObject {
}
get parent() {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this._parent;
}
@@ -466,6 +467,7 @@ export abstract class BaseObject {
}
getParent() {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this._parent;
}
@@ -645,7 +647,7 @@ export abstract class BaseObject {
return props;
}
- getScene() {
+ getScene(): any {
let parent: any = this.parent;
if (parent == null) {
@@ -673,7 +675,7 @@ export abstract class BaseObject {
this.getScene()?.setCursor(val);
}
- getEngine() {
+ getEngine(): any {
let parent: any = this.getParent();
while (parent != null) {
if (parent === RENDER_CLASS_TYPE.ENGINE) {
diff --git a/packages/base-render/src/Basics/IDocumentSkeletonCached.ts b/packages/base-render/src/Basics/IDocumentSkeletonCached.ts
index c5818aa868..fc611007f0 100644
--- a/packages/base-render/src/Basics/IDocumentSkeletonCached.ts
+++ b/packages/base-render/src/Basics/IDocumentSkeletonCached.ts
@@ -74,6 +74,7 @@ export interface IDocumentSkeletonPage {
ed: number; // endIndex 文本结束索引
skeDrawings: Map<string, IDocumentSkeletonDrawing>;
renderConfig?: IDocumentRenderConfig;
+ parent?: IDocumentSkeletonCached;
}
export interface IDocumentSkeletonSection {
diff --git a/packages/base-render/src/Basics/Position.ts b/packages/base-render/src/Basics/Position.ts
index adb79c6576..3fd79987df 100644
--- a/packages/base-render/src/Basics/Position.ts
+++ b/packages/base-render/src/Basics/Position.ts
@@ -2,16 +2,16 @@ import { BaseObject } from '../BaseObject';
import { IBoundRect } from './Vector2';
export function getOffsetRectForDom(ele: HTMLElement) {
- let box = ele.getBoundingClientRect();
- let body = document.body;
- let docElem = document.documentElement;
+ const box = ele.getBoundingClientRect();
+ const body = document.body;
+ const docElem = document.documentElement;
//获取页面的scrollTop,scrollLeft(兼容性写法)
- let scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
- let scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
- let clientTop = docElem.clientTop || body.clientTop;
- let clientLeft = docElem.clientLeft || body.clientLeft;
- let top = box.top + scrollTop - clientTop;
- let left = box.left + scrollLeft - clientLeft;
+ const scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
+ const scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
+ const clientTop = docElem.clientTop || body.clientTop;
+ const clientLeft = docElem.clientLeft || body.clientLeft;
+ const top = box.top + scrollTop - clientTop;
+ const left = box.left + scrollLeft - clientLeft;
return {
//Math.round 兼容火狐浏览器bug
top,
diff --git a/packages/base-render/src/Basics/Transform.ts b/packages/base-render/src/Basics/Transform.ts
index d4e308ca2c..eefda64562 100644
--- a/packages/base-render/src/Basics/Transform.ts
+++ b/packages/base-render/src/Basics/Transform.ts
@@ -57,8 +57,8 @@ export class Transform {
*/
applyPoint(point: Vector2, ignoreOffset: boolean = false): Vector2 {
const m = this._m;
- let xNew = m[0] * point.x + m[2] * point.y;
- let yNew = m[1] * point.x + m[3] * point.y;
+ const xNew = m[0] * point.x + m[2] * point.y;
+ const yNew = m[1] * point.x + m[3] * point.y;
if (ignoreOffset) {
return new Vector2(xNew, yNew);
}
@@ -104,12 +104,12 @@ export class Transform {
*/
rotate(deg: number) {
const rad = degToRad(deg);
- let c = Math.cos(rad);
- let s = Math.sin(rad);
- let m11 = this._m[0] * c + this._m[2] * s;
- let m12 = this._m[1] * c + this._m[3] * s;
- let m21 = this._m[0] * -s + this._m[2] * c;
- let m22 = this._m[1] * -s + this._m[3] * c;
+ const c = Math.cos(rad);
+ const s = Math.sin(rad);
+ const m11 = this._m[0] * c + this._m[2] * s;
+ const m12 = this._m[1] * c + this._m[3] * s;
+ const m21 = this._m[0] * -s + this._m[2] * c;
+ const m22 = this._m[1] * -s + this._m[3] * c;
this._m[0] = m11;
this._m[1] = m12;
this._m[2] = m21;
@@ -139,10 +139,10 @@ export class Transform {
* @returns {UniverSheet.Transform}
*/
skew(sx: number, sy: number) {
- let m11 = this._m[0] + this._m[2] * sy;
- let m12 = this._m[1] + this._m[3] * sy;
- let m21 = this._m[2] + this._m[0] * sx;
- let m22 = this._m[3] + this._m[1] * sx;
+ const m11 = this._m[0] + this._m[2] * sy;
+ const m12 = this._m[1] + this._m[3] * sy;
+ const m21 = this._m[2] + this._m[0] * sx;
+ const m22 = this._m[3] + this._m[1] * sx;
this._m[0] = m11;
this._m[1] = m12;
this._m[2] = m21;
@@ -158,14 +158,14 @@ export class Transform {
* @returns {UniverSheet.Transform}
*/
multiply(matrix: Transform) {
- let m11 = this._m[0] * matrix._m[0] + this._m[2] * matrix._m[1];
- let m12 = this._m[1] * matrix._m[0] + this._m[3] * matrix._m[1];
+ const m11 = this._m[0] * matrix._m[0] + this._m[2] * matrix._m[1];
+ const m12 = this._m[1] * matrix._m[0] + this._m[3] * matrix._m[1];
- let m21 = this._m[0] * matrix._m[2] + this._m[2] * matrix._m[3];
- let m22 = this._m[1] * matrix._m[2] + this._m[3] * matrix._m[3];
+ const m21 = this._m[0] * matrix._m[2] + this._m[2] * matrix._m[3];
+ const m22 = this._m[1] * matrix._m[2] + this._m[3] * matrix._m[3];
- let dx = this._m[0] * matrix._m[4] + this._m[2] * matrix._m[5] + this._m[4];
- let dy = this._m[1] * matrix._m[4] + this._m[3] * matrix._m[5] + this._m[5];
+ const dx = this._m[0] * matrix._m[4] + this._m[2] * matrix._m[5] + this._m[4];
+ const dy = this._m[1] * matrix._m[4] + this._m[3] * matrix._m[5] + this._m[5];
this._m[0] = m11;
this._m[1] = m12;
@@ -183,13 +183,13 @@ export class Transform {
* @returns {UniverSheet.Transform}
*/
invert() {
- let d = 1 / (this._m[0] * this._m[3] - this._m[1] * this._m[2]);
- let m0 = this._m[3] * d;
- let m1 = -this._m[1] * d;
- let m2 = -this._m[2] * d;
- let m3 = this._m[0] * d;
- let m4 = d * (this._m[2] * this._m[5] - this._m[3] * this._m[4]);
- let m5 = d * (this._m[1] * this._m[4] - this._m[0] * this._m[5]);
+ const d = 1 / (this._m[0] * this._m[3] - this._m[1] * this._m[2]);
+ const m0 = this._m[3] * d;
+ const m1 = -this._m[1] * d;
+ const m2 = -this._m[2] * d;
+ const m3 = this._m[0] * d;
+ const m4 = d * (this._m[2] * this._m[5] - this._m[3] * this._m[4]);
+ const m5 = d * (this._m[1] * this._m[4] - this._m[0] * this._m[5]);
this._m[0] = m0;
this._m[1] = m1;
this._m[2] = m2;
@@ -224,14 +224,14 @@ export class Transform {
* @returns {UniverSheet.Transform}
*/
setAbsolutePosition(coord: Vector2) {
- let m0 = this._m[0];
- let m1 = this._m[1];
- let m2 = this._m[2];
- let m3 = this._m[3];
- let m4 = this._m[4];
- let m5 = this._m[5];
- let yt = (m0 * (coord.y - m5) - m1 * (coord.x - m4)) / (m0 * m3 - m1 * m2);
- let xt = (coord.x - m4 - m2 * yt) / m0;
+ const m0 = this._m[0];
+ const m1 = this._m[1];
+ const m2 = this._m[2];
+ const m3 = this._m[3];
+ const m4 = this._m[4];
+ const m5 = this._m[5];
+ const yt = (m0 * (coord.y - m5) - m1 * (coord.x - m4)) / (m0 * m3 - m1 * m2);
+ const xt = (coord.x - m4 - m2 * yt) / m0;
return this.translate(xt, yt);
}
@@ -243,16 +243,16 @@ export class Transform {
* @returns {UniverSheet.Transform}
*/
decompose() {
- let a = this._m[0];
- let b = this._m[1];
- let c = this._m[2];
- let d = this._m[3];
- let e = this._m[4];
- let f = this._m[5];
+ const a = this._m[0];
+ const b = this._m[1];
+ const c = this._m[2];
+ const d = this._m[3];
+ const e = this._m[4];
+ const f = this._m[5];
- let delta = a * d - b * c;
+ const delta = a * d - b * c;
- let result = {
+ const result = {
x: e,
y: f,
angle: 0,
@@ -264,14 +264,14 @@ export class Transform {
// Apply the QR-like decomposition.
if (a !== 0 || b !== 0) {
- let r = Math.sqrt(a * a + b * b);
+ const r = Math.sqrt(a * a + b * b);
result.angle = b > 0 ? Math.acos(a / r) : -Math.acos(a / r);
result.scaleX = r;
result.scaleY = delta / r;
result.skewX = (a * c + b * d) / delta;
result.skewY = 0;
} else if (c !== 0 || d !== 0) {
- let s = Math.sqrt(c * c + d * d);
+ const s = Math.sqrt(c * c + d * d);
result.angle = Math.PI / 2 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s));
result.scaleX = delta / s;
result.scaleY = s;
diff --git a/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.Ruler.ts b/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.Ruler.ts
index d1067036de..29e3c60c5e 100644
--- a/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.Ruler.ts
+++ b/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.Ruler.ts
@@ -76,7 +76,7 @@ function _convertRoman(num: number, uppercase = false) {
lookup = upperLookup;
}
let romanStr = '';
- for (let i in lookup) {
+ for (const i in lookup) {
while (num >= lookup[i]) {
romanStr += i;
num -= lookup[i];
diff --git a/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.ts b/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.ts
index 28670a0f14..588244fae6 100644
--- a/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.ts
+++ b/packages/base-render/src/Component/Docs/Block/Paragraph/Bullet.ts
@@ -9,7 +9,7 @@ export function dealWidthBullet(
bullet?: IBullet,
lists?: ILists,
listLevelAncestors?: Array<Nullable<IDocumentSkeletonBullet>>,
- fontLocale?: IFontLocale,
+ fontLocale?: IFontLocale
): IDocumentSkeletonBullet | undefined {
if (!bullet || !lists) {
return;
@@ -29,7 +29,7 @@ export function dealWidthBullet(
return getDefaultBulletSke(listId, listLevelAncestors?.[nestingLevel]?.startIndexItem, fontLocale);
}
- const bulletSke = _getBulletSke(listId, nestingLevel, list.nestingLevel, listLevelAncestors, textStyle, fontLocale, context);
+ const bulletSke = _getBulletSke(listId, nestingLevel, list.nestingLevel, listLevelAncestors, textStyle, fontLocale);
return bulletSke;
}
@@ -66,7 +66,7 @@ function _getBulletSke(
nestings: INestingLevel[],
listLevelAncestors?: Array<Nullable<IDocumentSkeletonBullet>>,
textStyleConfig?: ITextStyle,
- fontLocale?: IFontLocale,
+ fontLocale?: IFontLocale
): IDocumentSkeletonBullet {
const nesting = nestings[nestingLevel];
const { bulletAlignment, glyphFormat, textStyle: textStyleFirst, startNumber, glyphType, glyphSymbol, indentFirstLine, hanging, indentStart } = nesting;
@@ -81,7 +81,7 @@ function _getBulletSke(
symbolContent = glyphSymbol;
} else {
// 有序列表
- symbolContent = __generateOrderedListSymbol(glyphFormat, nestingLevel, nestings, listLevelAncestors, context); // 有序列表的处理
+ symbolContent = __generateOrderedListSymbol(glyphFormat, nestingLevel, nestings, listLevelAncestors); // 有序列表的处理
}
const bBox = FontCache.getTextSize(symbolContent, fontStyle);
@@ -103,12 +103,7 @@ function _getBulletSke(
};
}
-function __generateOrderedListSymbol(
- glyphFormat: string,
- nestingLevel: number,
- nestings: INestingLevel[],
- listLevelAncestors?: Array<Nullable<IDocumentSkeletonBullet>>,
-) {
+function __generateOrderedListSymbol(glyphFormat: string, nestingLevel: number, nestings: INestingLevel[], listLevelAncestors?: Array<Nullable<IDocumentSkeletonBullet>>) {
// const indexNumber = startNumber + startIndex;
// parse <prefix>%[nestingLevelMinusOne]<suffix>, return symbolContent
// <w:lvl w:ilvl="0">
@@ -127,7 +122,7 @@ function __generateOrderedListSymbol(
if (level !== nestingLevel && listLevelAncestors?.[level] !== null) {
startIndexItem -= 1;
}
- const singleSymbol = ___getSymbolByBesting(startIndexItem, nestings[level], context);
+ const singleSymbol = ___getSymbolByBesting(startIndexItem, nestings[level]);
// console.log(
// '___getSymbolByBesting',
// singleSymbol,
@@ -155,7 +150,7 @@ function ___getSymbolByBesting(startIndex: number = 1, nesting: INestingLevel) {
return '\u25CF';
}
- return getBulletOrderedSymbol(startIndex, startNumber, glyphType, context);
+ return getBulletOrderedSymbol(startIndex, startNumber, glyphType);
}
function ___getLevelAndSuffix(levelAndSuffixPre: string) {
diff --git a/packages/base-render/src/Component/Docs/Common/TextSelection.ts b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
index 324a044c6a..f3be36d1e4 100644
--- a/packages/base-render/src/Component/Docs/Common/TextSelection.ts
+++ b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
@@ -101,7 +101,7 @@ export class TextSelection {
const lastCursor = cursorList[cursorList.length - 1];
- let isCollapse = cursorList.length === 1 && firstCursor.isCollapse;
+ const isCollapse = cursorList.length === 1 && firstCursor.isCollapse;
return {
cursorStart: firstCursor.cursorStart,
@@ -414,7 +414,7 @@ export class TextSelection {
private _pushToPoints(position: IPosition) {
const { startX, startY, endX, endY } = position;
- const points = [];
+ const points: Array<{ x: number; y: number }> = [];
points.push({
x: startX,
y: startY,
@@ -452,7 +452,7 @@ export class TextSelection {
const keys = Object.keys(NodePositionMap);
- for (let key of keys) {
+ for (const key of keys) {
const startNodeValue = start[key as keyof INodePosition] as number;
const endNodeValue = end[key as keyof INodePosition] as number;
@@ -563,9 +563,9 @@ export class TextSelection {
const lastSpanLeft = lastSpan?.left || 0;
const lastSpanWidth = lastSpan?.width || 0;
- let isCurrentList = firstSpan?.spanType === SpanType.LIST;
+ const isCurrentList = firstSpan?.spanType === SpanType.LIST;
- let hasList = spanGroup[0]?.spanType === SpanType.LIST;
+ const hasList = spanGroup[0]?.spanType === SpanType.LIST;
let cursorStart = start_sp + st;
diff --git a/packages/base-render/src/Component/Docs/Common/Tools.ts b/packages/base-render/src/Component/Docs/Common/Tools.ts
index d64d8be992..074ad774b8 100644
--- a/packages/base-render/src/Component/Docs/Common/Tools.ts
+++ b/packages/base-render/src/Component/Docs/Common/Tools.ts
@@ -270,31 +270,31 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
// }
let prePageStartIndex = start;
- for (let page of pages) {
+ for (const page of pages) {
const { sections } = page;
- let pageStartIndex = prePageStartIndex;
- let pageEndIndex = pageStartIndex;
+ const pageStartIndex = prePageStartIndex;
+ const pageEndIndex = pageStartIndex;
let preSectionStartIndex = pageStartIndex;
let maxPageWidth = -Infinity;
let pageHeight = 0;
- for (let section of sections) {
+ for (const section of sections) {
const { columns } = section;
- let sectionStartIndex = preSectionStartIndex;
- let sectionEndIndex = pageStartIndex;
+ const sectionStartIndex = preSectionStartIndex;
+ const sectionEndIndex = pageStartIndex;
let preColumnStartIndex = sectionStartIndex;
let maxSectionHeight = -Infinity;
- for (let column of columns) {
+ for (const column of columns) {
const { lines } = column;
- let columStartIndex = preColumnStartIndex;
- let columnEndIndex = columStartIndex;
+ const columStartIndex = preColumnStartIndex;
+ const columnEndIndex = columStartIndex;
let preLineStartIndex = columStartIndex;
let columnHeight = 0;
let maxColumnWidth = -Infinity;
let preLine: Nullable<IDocumentSkeletonLine> = null;
- for (let line of lines) {
+ for (const line of lines) {
const { divides, lineHeight } = line;
- let lineStartIndex = preLineStartIndex;
- let lineEndIndex = lineStartIndex;
+ const lineStartIndex = preLineStartIndex;
+ const lineEndIndex = lineStartIndex;
let preDivideStartIndex = lineStartIndex;
let actualWidth = 0;
let maxLineAsc = 0;
@@ -308,9 +308,9 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
continue;
}
- let divStartIndex = preDivideStartIndex;
+ const divStartIndex = preDivideStartIndex;
let divEndIndex = divStartIndex;
- for (let span of spanGroup) {
+ for (const span of spanGroup) {
const increaseValue = span.spanType === SpanType.LIST ? 0 : span.count || 1;
// pageEndIndex += increaseValue;
// sectionEndIndex += increaseValue;
@@ -384,23 +384,23 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
}
export function spanIterator(pages: IDocumentSkeletonPage[], iteratorFunction: (span: IDocumentSkeletonSpan) => void) {
- for (let page of pages) {
+ for (const page of pages) {
const { sections } = page;
- for (let section of sections) {
+ for (const section of sections) {
const { columns } = section;
- for (let column of columns) {
+ for (const column of columns) {
const { lines } = column;
- for (let line of lines) {
+ for (const line of lines) {
const { divides, lineHeight } = line;
const divideLength = divides.length;
for (let i = 0; i < divideLength; i++) {
const divide = divides[i];
const { spanGroup } = divide;
- for (let span of spanGroup) {
+ for (const span of spanGroup) {
if (iteratorFunction && isFunction(iteratorFunction)) {
iteratorFunction(span);
}
@@ -413,16 +413,16 @@ export function spanIterator(pages: IDocumentSkeletonPage[], iteratorFunction: (
}
export function lineIterator(pages: IDocumentSkeletonPage[], iteratorFunction: (line: IDocumentSkeletonLine) => void) {
- for (let page of pages) {
+ for (const page of pages) {
const { sections } = page;
- for (let section of sections) {
+ for (const section of sections) {
const { columns } = section;
- for (let column of columns) {
+ for (const column of columns) {
const { lines } = column;
- for (let line of lines) {
+ for (const line of lines) {
if (iteratorFunction && isFunction(iteratorFunction)) {
iteratorFunction(line);
}
@@ -433,13 +433,13 @@ export function lineIterator(pages: IDocumentSkeletonPage[], iteratorFunction: (
}
export function columnIterator(pages: IDocumentSkeletonPage[], iteratorFunction: (column: IDocumentSkeletonColumn) => void) {
- for (let page of pages) {
+ for (const page of pages) {
const { sections } = page;
- for (let section of sections) {
+ for (const section of sections) {
const { columns } = section;
- for (let column of columns) {
+ for (const column of columns) {
if (iteratorFunction && isFunction(iteratorFunction)) {
iteratorFunction(column);
}
@@ -625,7 +625,7 @@ export function getPositionHorizonBySpan(positionH: ObjectPositionH, span: IDocu
export function getSpanGroupWidth(divide: IDocumentSkeletonDivide) {
const spanGroup = divide.spanGroup;
let width = 0;
- for (let span of spanGroup) {
+ for (const span of spanGroup) {
width += span.width;
}
return width;
diff --git a/packages/base-render/src/Component/Docs/DocComponent.ts b/packages/base-render/src/Component/Docs/DocComponent.ts
index c41d585043..369eedf924 100644
--- a/packages/base-render/src/Component/Docs/DocComponent.ts
+++ b/packages/base-render/src/Component/Docs/DocComponent.ts
@@ -82,14 +82,119 @@ export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocum
};
}
+ scrollBySelection() {}
+
+ syncSelection() {}
+
getFirstViewport() {}
- findPositionBySpan(span: IDocumentSkeletonSpan): Nullable<INodeSearch> {}
+ remainActiveSelection() {}
+
+ findPositionBySpan(span: IDocumentSkeletonSpan): Nullable<INodeSearch> {
+ const divide = span.parent;
+
+ const line = divide?.parent;
+
+ const column = line?.parent;
+
+ const section = column?.parent;
+
+ const page = section?.parent;
+
+ const skeletonData = this.getSkeleton()?.getSkeletonData();
+
+ if (!divide || !column || !section || !page || !skeletonData) {
+ return;
+ }
+
+ const spanIndex = divide.spanGroup.indexOf(span);
+
+ const divideIndex = line.divides.indexOf(divide);
+
+ const lineIndex = column.lines.indexOf(line);
+
+ const columnIndex = section.columns.indexOf(column);
+
+ const sectionIndex = page.sections.indexOf(section);
+
+ const pageIndex = skeletonData.pages.indexOf(page);
+
+ return {
+ span: spanIndex,
+ divide: divideIndex,
+ line: lineIndex,
+ column: columnIndex,
+ section: sectionIndex,
+ page: pageIndex,
+ };
+ }
findNodeByCoord(offsetX: number, offsetY: number): false | INodeInfo {
return false;
}
+ findCoordByNode(span: IDocumentSkeletonSpan) {}
+
+ findNodeByCharIndex(charIndex: number): Nullable<IDocumentSkeletonSpan> {
+ const skeleton = this.getSkeleton();
+
+ if (!skeleton) {
+ return;
+ }
+
+ const skeletonData = skeleton.getSkeletonData();
+
+ 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;
+ }
+
+ const span = spanGroup[charIndex - st];
+
+ if (span) {
+ return span;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
getActiveViewportByCoord(offsetX: number, offsetY: number) {}
protected _getBounding(bounds?: IBoundRect) {}
diff --git a/packages/base-render/src/Component/Docs/DocSkeleton.ts b/packages/base-render/src/Component/Docs/DocSkeleton.ts
index 1d50685b4b..214ce2e7b3 100644
--- a/packages/base-render/src/Component/Docs/DocSkeleton.ts
+++ b/packages/base-render/src/Component/Docs/DocSkeleton.ts
@@ -308,9 +308,17 @@ export class DocumentSkeleton extends Skeleton {
// 计算页和节的位置信息
updateBlockIndex(allSkeletonPages);
+ this._setPageParent(allSkeletonPages, skeleton);
+
return skeleton;
}
+ private _setPageParent(pages: IDocumentSkeletonPage[], parent: IDocumentSkeletonCached) {
+ for (const page of pages) {
+ page.parent = parent;
+ }
+ }
+
// 一页存在多个section的情况,仅在SectionType.CONTINUOUS的情况下出现
private __addNewSectionByContinuous(curSkeletonPage: IDocumentSkeletonPage, columnProperties: ISectionColumnProperties[], columnSeparatorType: ColumnSeparatorType) {
const sections = curSkeletonPage.sections;
diff --git a/packages/base-render/src/Component/Docs/Document.Editor.ts b/packages/base-render/src/Component/Docs/Document.Editor.ts
index 6ab762d4d6..7a951537a0 100644
--- a/packages/base-render/src/Component/Docs/Document.Editor.ts
+++ b/packages/base-render/src/Component/Docs/Document.Editor.ts
@@ -33,6 +33,8 @@ export class DocsEditor {
onCompositionendObservable = new Observable<IEditorInputConfig>();
+ onSelectionStartObservable = new Observable<INodeInfo | false>();
+
private _container: HTMLDivElement;
private _inputParent: HTMLDivElement;
@@ -92,7 +94,7 @@ export class DocsEditor {
getActiveTextSelection() {
const list = this._textSelectionList;
- for (let textSelection of list) {
+ for (const textSelection of list) {
if (textSelection.isActive()) {
return textSelection;
}
@@ -121,6 +123,10 @@ export class DocsEditor {
this._syncDomToSelection();
}
+ scroll() {
+ this._scrollToSelection();
+ }
+
active(x: number, y: number) {
this._container.style.left = `${x}px`;
this._container.style.top = `${y}px`;
@@ -396,16 +402,48 @@ export class DocsEditor {
};
}
+ // Let the selection show on the current screen.
+ private _scrollToSelection() {
+ const activeTextSelection = this.getActiveTextSelection();
+ const anchor = activeTextSelection?.getAnchor();
+ if (!anchor || (anchor && !anchor.visible) || this._activeViewport == null) {
+ return;
+ }
+
+ const { left, top } = anchor;
+
+ const { tl, tr, bl } = this._activeViewport.getBounding();
+ const constantOffset = 100;
+ let offsetY = 0;
+ let offsetX = 0;
+ if (top < tl.y + constantOffset) {
+ offsetY = top - tl.y - constantOffset;
+ } else if (top > bl.y - constantOffset) {
+ offsetY = top - bl.y + constantOffset;
+ }
+
+ if (left < tl.x + constantOffset) {
+ offsetX = left - tl.x - constantOffset;
+ } else if (left > tr.x - constantOffset) {
+ offsetX = left - tr.x + constantOffset;
+ }
+
+ const config = this._activeViewport.getBarScroll(offsetX, offsetY);
+ this._activeViewport.scrollBy(config);
+ }
+
private _syncDomToSelection() {
const activeTextSelection = this.getActiveTextSelection();
const anchor = activeTextSelection?.getAnchor();
- if (!anchor || (anchor && !anchor.visible)) {
+ if (!anchor || (anchor && !anchor.visible) || this._activeViewport == null) {
return;
}
const { height, left, top } = anchor;
- const absoluteCoord = this._activeViewport?.getAbsoluteVector(Vector2.FromArray([left, top]));
+ const absoluteCoord = this._activeViewport.getAbsoluteVector(Vector2.FromArray([left, top]));
+
+ const { x, y } = absoluteCoord;
this._cursor.style.height = `${height}px`;
@@ -413,9 +451,9 @@ export class DocsEditor {
let { left: canvasLeft, top: canvasTop } = this._getCanvasOffset();
- canvasLeft += absoluteCoord?.x || 0;
+ canvasLeft += x;
- canvasTop += absoluteCoord?.y || 0;
+ canvasTop += y;
this.active(canvasLeft, canvasTop);
}
@@ -547,7 +585,6 @@ export class DocsEditor {
if (this._documents == null) {
return;
}
-
this.onInputObservable.notifyObservers({
event: e,
content,
@@ -676,6 +713,8 @@ export class DocsEditor {
this._viewportScrollX = scrollX;
this._viewportScrollY = scrollY;
+ this.onSelectionStartObservable.notifyObservers(startNode);
+
this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
this._moving(moveOffsetX, moveOffsetY, scrollTimer);
@@ -707,6 +746,7 @@ export class DocsEditor {
this.onCompositionstartObservable.clear();
this.onCompositionupdateObservable.clear();
this.onCompositionendObservable.clear();
+ this.onSelectionStartObservable.clear();
}
private _activeSelectionRefresh() {
diff --git a/packages/base-render/src/Component/Docs/Document.ts b/packages/base-render/src/Component/Docs/Document.ts
index c19d850154..eac489685c 100644
--- a/packages/base-render/src/Component/Docs/Document.ts
+++ b/packages/base-render/src/Component/Docs/Document.ts
@@ -1,6 +1,6 @@
import { BooleanNumber, HorizontalAlign, Nullable, Observable, Observer, VerticalAlign, WrapStrategy } from '@univerjs/core';
import { DocComponent } from './DocComponent';
-import { IDocumentSkeletonCached, IDocumentSkeletonPage, IDocumentSkeletonSpan, LineType, PageLayoutType } from '../../Basics/IDocumentSkeletonCached';
+import { IDocumentSkeletonCached, IDocumentSkeletonPage, LineType, PageLayoutType } from '../../Basics/IDocumentSkeletonCached';
import { IBoundRect, Vector2 } from '../../Basics/Vector2';
import { DocumentsSpanAndLineExtensionRegistry, IExtensionConfig } from '../Extension';
import { DocumentSkeleton } from './DocSkeleton';
@@ -12,7 +12,6 @@ import { DocsEditor } from './Document.Editor';
import { Liquid } from './Common/Liquid';
import { Scene } from '../../Scene';
import { TextSelection } from './Common/TextSelection';
-import { INodeSearch } from '../../Basics/Interfaces';
export interface IDocumentsConfig {
pageMarginLeft?: number;
@@ -91,7 +90,7 @@ export class Documents extends DocComponent {
calculatePagePosition() {
const scene = this.getScene() as Scene;
- let parent = scene?.getParent();
+ const parent = scene?.getParent();
const { width: docsWidth, height: docsHeight, pageMarginLeft, pageMarginTop } = this;
if (parent == null) {
return this;
@@ -160,11 +159,12 @@ export class Documents extends DocComponent {
if (!this._hasEditor) {
return;
}
- const { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable } = this._editor;
- return { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable };
+ const { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable, onSelectionStartObservable } =
+ this._editor;
+ return { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable, onSelectionStartObservable };
}
- remainActiveSelection() {
+ override remainActiveSelection() {
if (!this._hasEditor) {
return;
}
@@ -178,7 +178,7 @@ export class Documents extends DocComponent {
return this._editor.add(textSelection);
}
- syncSelection() {
+ override syncSelection() {
if (!this._hasEditor) {
return;
}
@@ -186,6 +186,14 @@ export class Documents extends DocComponent {
return this._editor.sync();
}
+ override scrollBySelection() {
+ if (this._hasEditor == null) {
+ return;
+ }
+
+ this._editor.scroll();
+ }
+
// eslint-disable-next-line max-lines-per-function
override draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
const documentSkeleton = this.getSkeleton();
@@ -205,7 +213,7 @@ export class Documents extends DocComponent {
const parentScale = this.getParentScale();
const extensions = this.getExtensionsByOrder();
const scale = getScale(parentScale);
- for (let extension of extensions) {
+ for (const extension of extensions) {
extension.clearCache();
}
@@ -253,12 +261,12 @@ export class Documents extends DocComponent {
this._startRotation(ctx, finalAngle);
- for (let section of sections) {
+ for (const section of sections) {
const { columns } = section;
this._drawLiquid.translateSection(section);
- for (let column of columns) {
+ for (const column of columns) {
const { lines, width: columnWidth } = column;
this._drawLiquid.translateColumn(column);
@@ -312,13 +320,13 @@ export class Documents extends DocComponent {
lineHeight = 0,
} = line;
- let maxLineAsc = asc;
+ const maxLineAsc = asc;
const maxLineAscSin = maxLineAsc * Math.sin(centerAngle);
const maxLineAscCos = maxLineAsc * Math.cos(centerAngle);
if (type === LineType.BLOCK) {
- for (let extension of extensions) {
+ for (const extension of extensions) {
if (extension.type === DOCS_EXTENSION_TYPE.LINE) {
extension.extensionOffset = {
alignOffset,
@@ -340,7 +348,7 @@ export class Documents extends DocComponent {
this._drawLiquid.translateSave();
this._drawLiquid.translateDivide(divide);
- for (let span of spanGroup) {
+ for (const span of spanGroup) {
if (!span.content || span.content.length === 0) {
continue;
}
@@ -374,7 +382,7 @@ export class Documents extends DocComponent {
renderConfig,
};
- for (let extension of extensions) {
+ for (const extension of extensions) {
if (extension.type === DOCS_EXTENSION_TYPE.SPAN) {
extension.extensionOffset = extensionOffset;
extension.draw(ctx, parentScale, span);
@@ -404,105 +412,6 @@ export class Documents extends DocComponent {
return this;
}
- override findPositionBySpan(span: IDocumentSkeletonSpan): Nullable<INodeSearch> {
- const divide = span.parent;
-
- const line = divide?.parent;
-
- const column = line?.parent;
-
- const section = column?.parent;
-
- const page = section?.parent;
-
- const skeletonData = this.getSkeleton()?.getSkeletonData();
-
- if (!divide || !column || !section || !page || !skeletonData) {
- return;
- }
-
- let spanIndex = divide.spanGroup.indexOf(span);
-
- const divideIndex = line.divides.indexOf(divide);
-
- const lineIndex = column.lines.indexOf(line);
-
- const columnIndex = section.columns.indexOf(column);
-
- const sectionIndex = page.sections.indexOf(section);
-
- const pageIndex = skeletonData.pages.indexOf(page);
-
- return {
- span: spanIndex,
- divide: divideIndex,
- line: lineIndex,
- column: columnIndex,
- section: sectionIndex,
- page: pageIndex,
- };
- }
-
- findNodeByCharIndex(charIndex: number): Nullable<IDocumentSkeletonSpan> {
- const skeleton = this.getSkeleton();
-
- if (!skeleton) {
- return;
- }
-
- const skeletonData = skeleton.getSkeletonData();
-
- const pages = skeletonData.pages;
-
- for (let page of pages) {
- const { sections, st, ed } = page;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- for (let section of sections) {
- const { columns, st, ed } = section;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- for (let column of columns) {
- const { lines, st, ed } = column;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- for (let 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;
- }
-
- const span = spanGroup[charIndex - st];
-
- if (span) {
- return span;
- }
- }
- }
- }
- }
- }
- }
-
// eslint-disable-next-line max-lines-per-function
override findNodeByCoord(offsetX: number, offsetY: number) {
const scene = this.getScene() as Scene;
@@ -513,7 +422,7 @@ export class Documents extends DocComponent {
}
const coord = this._getInverseCoord(originCoord);
- let { x, y } = coord;
+ const { x, y } = coord;
const skeleton = this.getSkeleton();
if (!skeleton) {
@@ -539,7 +448,7 @@ export class Documents extends DocComponent {
this._findLiquid.translatePagePadding(page);
const sections = page.sections;
- for (let section of sections) {
+ for (const section of sections) {
const { columns, height } = section;
this._findLiquid.translateSection(section);
@@ -550,7 +459,7 @@ export class Documents extends DocComponent {
continue;
}
- for (let column of columns) {
+ for (const column of columns) {
const { lines, width: columnWidth } = column;
this._findLiquid.translateColumn(column);
@@ -599,7 +508,7 @@ export class Documents extends DocComponent {
continue;
}
- for (let span of spanGroup) {
+ for (const span of spanGroup) {
if (!span.content || span.content.length === 0) {
continue;
}
@@ -634,6 +543,41 @@ export class Documents extends DocComponent {
return false;
}
+ 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);
}
@@ -718,7 +662,7 @@ export class Documents extends DocComponent {
private _getPageBoundingBox(page: IDocumentSkeletonPage) {
const { pageWidth, pageHeight } = page;
- let { x: startX, y: startY } = this._findLiquid;
+ const { x: startX, y: startY } = this._findLiquid;
let endX = -1;
let endY = -1;
diff --git a/packages/base-render/src/Component/Docs/index.ts b/packages/base-render/src/Component/Docs/index.ts
index a330b97f93..a8dd974bc5 100644
--- a/packages/base-render/src/Component/Docs/index.ts
+++ b/packages/base-render/src/Component/Docs/index.ts
@@ -1,6 +1,7 @@
export * from './Common';
export * from './Block';
export * from './DocSkeleton';
+export * from './Document.Editor';
export * from './Document';
export * from './HorizonBar';
export * from './VerticalBar';
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
new file mode 100644
index 0000000000..9f5de63ac1
--- /dev/null
+++ b/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
@@ -0,0 +1,380 @@
+import { Nullable, ISelection, ICellInfo } from '@univerjs/core';
+import { SelectionModel } from './SelectionModel';
+import { Rect } from '../../../Shape/Rect';
+import { Group } from '../../../Group';
+import { Scene } from '../../../Scene';
+import { SELECTION_TYPE } from '../../../Basics/Const';
+
+// export enum DEFAULT_SELECTION_CONFIG {
+// strokeColor = 'rgb(1,136,251)',
+// backgroundColor = 'rgba(1,136,251, 0.1)',
+// strokeWidth = 2,
+// fillSideLength = 6,
+// fillStrokeLength = 1,
+// fillStrokeColor = 'rgb(255,255,255)',
+// }
+export const DEFAULT_SELECTION_CONFIG = {
+ strokeColor: 'rgb(1,136,251)',
+ backgroundColor: 'rgba(1,136,251, 0.1)',
+ strokeWidth: 2,
+ fillSideLength: 6,
+ fillStrokeLength: 1,
+ fillStrokeColor: 'rgb(255,255,255)',
+};
+
+enum SELECTION_MANAGER_KEY {
+ Selection = '__SpreadsheetSelectionShape__',
+ top = '__SpreadsheetSelectionTopControl__',
+ bottom = '__SpreadsheetSelectionBottomControl__',
+ left = '__SpreadsheetSelectionShapeLeftControl__',
+ right = '__SpreadsheetSelectionShapeRightControl__',
+ backgroundTop = '__SpreadsheetSelectionBackgroundControlTop__',
+ backgroundMiddleLeft = '__SpreadsheetSelectionBackgroundControlMiddleLeft__',
+ backgroundMiddleRight = '__SpreadsheetSelectionBackgroundControlMiddleRight__',
+ backgroundBottom = '__SpreadsheetSelectionBackgroundControlBottom__',
+ fill = '__SpreadsheetSelectionFillControl__',
+ lineMain = '__SpreadsheetDragLineMainControl__',
+ lineContent = '__SpreadsheetDragLineContentControl__',
+ line = '__SpreadsheetDragLineControl__',
+}
+
+/**
+ * The main selection canvas component
+ */
+export class SelectionControl {
+ private _leftControl: Rect;
+
+ private _rightControl: Rect;
+
+ private _topControl: Rect;
+
+ private _bottomControl: Rect;
+
+ private _backgroundControlTop: Rect;
+
+ private _backgroundControlBottom: Rect;
+
+ private _backgroundControlMiddleLeft: Rect;
+
+ private _backgroundControlMiddleRight: Rect;
+
+ private _fillControl: Rect;
+
+ private _selectionShape: Group;
+
+ private _selectionModel: SelectionModel;
+
+ constructor(private _scene: Scene, private _zIndex: number) {
+ this._initialize();
+ }
+
+ get zIndex() {
+ return this._zIndex;
+ }
+
+ get leftControl() {
+ return this._leftControl;
+ }
+
+ get rightControl() {
+ return this._rightControl;
+ }
+
+ get topControl() {
+ return this._topControl;
+ }
+
+ get bottomControl() {
+ return this._bottomControl;
+ }
+
+ get fillControl() {
+ return this._fillControl;
+ }
+
+ get backgroundControlTop() {
+ return this._backgroundControlTop;
+ }
+
+ get backgroundControlBottom() {
+ return this._backgroundControlBottom;
+ }
+
+ get backgroundControlMiddleLeft() {
+ return this._backgroundControlMiddleLeft;
+ }
+
+ get backgroundControlMiddleRight() {
+ return this._backgroundControlMiddleRight;
+ }
+
+ get selectionShape() {
+ return this._selectionShape;
+ }
+
+ get model() {
+ return this._selectionModel;
+ }
+
+ static create(scene: Scene, zIndex: number) {
+ return new this(scene, zIndex);
+ }
+
+ static fromJson(scene: Scene, zIndex: number, newSelectionRange: ISelection) {
+ const control = SelectionControl.create(scene, zIndex);
+ control.update(newSelectionRange);
+ return control;
+ }
+
+ /**
+ * just handle the view
+ *
+ * inner update
+ */
+ _updateControl() {
+ const { startX, startY, endX, endY } = this._selectionModel;
+
+ this.leftControl.resize(undefined, endY - startY);
+ this.rightControl.transformByState({
+ height: endY - startY,
+ left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ });
+ this.topControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);
+ this.bottomControl.transformByState({
+ width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,
+ top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ });
+
+ this.fillControl.translate(endX - startX - DEFAULT_SELECTION_CONFIG.fillSideLength / 2, endY - startY - DEFAULT_SELECTION_CONFIG.fillSideLength / 2);
+
+ this._updateBackgroundControl();
+
+ this.selectionShape.show();
+ this.selectionShape.translate(startX, startY);
+
+ this.selectionShape.makeDirty(true);
+ }
+
+ update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {
+ this._selectionModel.setValue(newSelectionRange, highlight);
+ this._updateControl();
+ }
+
+ clearHighlight() {
+ this._selectionModel.clearCurrentCell();
+ this._updateControl();
+ }
+
+ getScene() {
+ return this._scene;
+ }
+
+ dispose() {
+ this._leftControl?.dispose();
+ this._rightControl?.dispose();
+ this._topControl?.dispose();
+ this._bottomControl?.dispose();
+ this._backgroundControlTop?.dispose();
+ this._backgroundControlMiddleLeft?.dispose();
+ this._backgroundControlMiddleRight?.dispose();
+ this._backgroundControlBottom?.dispose();
+ this._fillControl?.dispose();
+ this._selectionShape?.dispose();
+ }
+
+ /**
+ * Get the cell information of the current selection, considering the case of merging cells
+ */
+ getCurrentCellInfo(): Nullable<ISelection> {
+ const currentCell = this.model.currentCell;
+
+ if (currentCell) {
+ let currentRangeData: ISelection;
+
+ if (currentCell.isMerged) {
+ const mergeInfo = currentCell.mergeInfo;
+
+ currentRangeData = {
+ startRow: mergeInfo.startRow,
+ endRow: mergeInfo.endRow,
+ startColumn: mergeInfo.startColumn,
+ endColumn: mergeInfo.endColumn,
+ startX: mergeInfo.startX,
+ endX: mergeInfo.endX,
+ startY: mergeInfo.startY,
+ endY: mergeInfo.endY,
+ };
+ } else {
+ const { row, column, startX, endX, startY, endY } = currentCell;
+ currentRangeData = {
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ startX,
+ endX,
+ startY,
+ endY,
+ };
+ }
+
+ return currentRangeData;
+ }
+ }
+
+ private _initialize() {
+ this._selectionModel = new SelectionModel(SELECTION_TYPE.NORMAL);
+ const zIndex = this._zIndex;
+ this._leftControl = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {
+ top: 0,
+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ width: DEFAULT_SELECTION_CONFIG.strokeWidth,
+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,
+ zIndex,
+ });
+ this._rightControl = new Rect(SELECTION_MANAGER_KEY.right + zIndex, {
+ width: DEFAULT_SELECTION_CONFIG.strokeWidth,
+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,
+ zIndex,
+ });
+ this._topControl = new Rect(SELECTION_MANAGER_KEY.top + zIndex, {
+ top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ height: DEFAULT_SELECTION_CONFIG.strokeWidth,
+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,
+ zIndex,
+ });
+ this._bottomControl = new Rect(SELECTION_MANAGER_KEY.bottom + zIndex, {
+ height: DEFAULT_SELECTION_CONFIG.strokeWidth,
+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,
+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ zIndex,
+ });
+ this._backgroundControlTop = new Rect(SELECTION_MANAGER_KEY.backgroundTop + zIndex, {
+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+ this._backgroundControlBottom = new Rect(SELECTION_MANAGER_KEY.backgroundBottom + zIndex, {
+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+ this._backgroundControlMiddleLeft = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleLeft + zIndex, {
+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+ this._backgroundControlMiddleRight = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleRight + zIndex, {
+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+ const fillSideLength = DEFAULT_SELECTION_CONFIG.fillSideLength - DEFAULT_SELECTION_CONFIG.fillStrokeLength;
+ this._fillControl = new Rect(SELECTION_MANAGER_KEY.fill + zIndex, {
+ width: fillSideLength,
+ height: fillSideLength,
+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,
+ strokeWidth: DEFAULT_SELECTION_CONFIG.fillStrokeLength,
+ stroke: DEFAULT_SELECTION_CONFIG.fillStrokeColor,
+ zIndex: zIndex + 1,
+ });
+ this._selectionShape = new Group(
+ SELECTION_MANAGER_KEY.Selection + zIndex,
+ this._fillControl,
+ this._leftControl,
+ this._rightControl,
+ this._topControl,
+ this._bottomControl,
+ this._backgroundControlTop,
+ this._backgroundControlMiddleLeft,
+ this._backgroundControlMiddleRight,
+ this._backgroundControlBottom
+ );
+
+ this._selectionShape.hide();
+
+ this._selectionShape.evented = false;
+
+ this._selectionShape.zIndex = zIndex;
+
+ const scene = this.getScene();
+ scene.addObject(this._selectionShape);
+ }
+
+ private _updateBackgroundControl() {
+ const {
+ startColumn,
+ startRow,
+ endColumn,
+ endRow,
+
+ startX,
+ startY,
+ endX,
+ endY,
+ } = this._selectionModel;
+
+ const highlightSelection = this._selectionModel.highlightToSelection();
+
+ if (!highlightSelection) {
+ this._backgroundControlTop.resize(endX - startX, endY - startY);
+ this._backgroundControlBottom.resize(0, 0);
+ this._backgroundControlMiddleLeft.resize(0, 0);
+ this._backgroundControlMiddleRight.resize(0, 0);
+ return;
+ }
+
+ const { startX: h_startX, startY: h_startY, endX: h_endX, endY: h_endY } = highlightSelection;
+
+ const strokeOffset = DEFAULT_SELECTION_CONFIG.strokeWidth / 2;
+
+ const topConfig = {
+ left: -strokeOffset,
+ top: -strokeOffset,
+ width: endX - startX + strokeOffset * 2,
+ height: h_startY - startY + strokeOffset,
+ };
+ if (topConfig.height < 0) {
+ topConfig.width = 0;
+ topConfig.height = 0;
+ }
+ this._backgroundControlTop.transformByState(topConfig);
+
+ const middleLeftConfig = {
+ left: -strokeOffset,
+ top: h_startY - startY,
+ width: h_startX - startX + strokeOffset,
+ height: h_endY - h_startY,
+ };
+ if (middleLeftConfig.width < 0) {
+ middleLeftConfig.width = 0;
+ middleLeftConfig.height = 0;
+ }
+ this._backgroundControlMiddleLeft.transformByState(middleLeftConfig);
+
+ const middleRightConfig = {
+ left: h_endX - startX - strokeOffset,
+ top: h_startY - startY,
+ width: endX - h_endX + strokeOffset * 2,
+ height: h_endY - h_startY,
+ };
+ if (middleRightConfig.width < 0) {
+ middleRightConfig.width = 0;
+ middleRightConfig.height = 0;
+ }
+ this._backgroundControlMiddleRight.transformByState(middleRightConfig);
+
+ const middleBottomConfig = {
+ left: -strokeOffset,
+ top: h_endY - startY,
+ width: endX - startX + strokeOffset * 2,
+ height: endY - h_endY + strokeOffset,
+ };
+ if (middleBottomConfig.height < 0) {
+ middleBottomConfig.width = 0;
+ middleBottomConfig.height = 0;
+ }
+ this._backgroundControlBottom.transformByState(middleBottomConfig);
+ }
+}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
new file mode 100644
index 0000000000..4f143e7b4a
--- /dev/null
+++ b/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
@@ -0,0 +1,419 @@
+import { Nullable, Observer, ISelection, makeCellToSelection, IRangeData, IRangeCellData } from '@univerjs/core';
+import { SelectionControl } from './SelectionControl';
+import { ScrollTimer } from '../../../ScrollTimer';
+import { IMouseEvent, IPointerEvent } from '../../../Basics/IEvents';
+import { SheetComponent } from '../SheetComponent';
+import { SelectionModel } from './SelectionModel';
+import { Vector2 } from '../../../Basics/Vector2';
+import { Scene } from '../../../Scene';
+
+/**
+ * TODO 注册selection拦截,可能在有公式ArrayObject时,fx公式栏显示不同
+ *
+ * SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)
+ */
+export class SelectionManager {
+ hasSelection: boolean = false;
+
+ private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _selectionControls: SelectionControl[] = []; // sheetID:Controls
+
+ private _startSelectionRange: ISelection;
+
+ private _startOffsetX: number = 0;
+
+ private _startOffsetY: number = 0;
+
+ private _scrollTimer: ScrollTimer;
+
+ private _cancelDownObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _cancelUpObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ constructor(private _spreadsheet: SheetComponent) {
+ this._mainEventInitial();
+ }
+
+ static create(spreadsheet: SheetComponent) {
+ return new SelectionManager(spreadsheet);
+ }
+
+ /**
+ * add a selection
+ * @param selectionRange
+ * @param curCellRange
+ * @returns
+ */
+ addControlToCurrentByRangeData(selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>) {
+ const currentControls = this.getCurrentControls();
+ if (!currentControls) {
+ return;
+ }
+ const main = this._spreadsheet;
+
+ const control = SelectionControl.create(this.getScene(), currentControls.length);
+
+ let cellInfo = null;
+ if (curCellRange) {
+ cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);
+ }
+
+ const { startRow, startColumn, endRow, endColumn } = selectionRange;
+ const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);
+ const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
+
+ // update control
+ control.update(
+ {
+ startColumn,
+ startRow,
+ endColumn,
+ endRow,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ },
+ cellInfo
+ );
+
+ currentControls.push(control);
+ }
+
+ getSpreadsheet() {
+ return this._spreadsheet;
+ }
+
+ getMaxIndex() {
+ return this._spreadsheet.zIndex + 1;
+ }
+
+ getScene() {
+ return this._spreadsheet.getScene() as Scene;
+ }
+
+ getSkeleton() {
+ return this._spreadsheet.getSkeleton();
+ }
+
+ getRowAndColumnCount() {
+ const skeleton = this.getSkeleton();
+ return {
+ rowCount: skeleton?.getRowCount() || 1000,
+ columnCount: skeleton?.getColumnCount() || 50,
+ };
+ }
+
+ getCurrentControls() {
+ return this._selectionControls;
+ }
+
+ getCurrentControl() {
+ const controls = this.getCurrentControls();
+ if (controls && controls.length > 0) {
+ for (const control of controls) {
+ const currentCell = control.model.currentCell;
+ if (currentCell) {
+ return control;
+ }
+ }
+ }
+ }
+
+ clearSelectionControls() {
+ const curControls = this.getCurrentControls();
+
+ if (curControls.length > 0) {
+ for (const control of curControls) {
+ control.dispose();
+ }
+
+ curControls.length = 0; // clear currentSelectionControls
+ }
+ }
+
+ /**
+ * Returns the list of active ranges in the active sheet or null if there are no active ranges.
+ * If there is a single range selected, this behaves as a getActiveRange() call.
+ *
+ * @returns
+ */
+ getActiveRangeList(): Nullable<IRangeData[]> {
+ const controls = this.getCurrentControls();
+ if (controls && controls.length > 0) {
+ const selections = controls?.map((control: SelectionControl) => {
+ const model: SelectionModel = control.model;
+ return {
+ startRow: model.startRow,
+ startColumn: model.startColumn,
+ endRow: model.endRow,
+ endColumn: model.endColumn,
+ };
+ });
+ return selections;
+ }
+ }
+
+ /**
+ * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
+ * TODO: 默认最后一个选区为当前激活选区,或者当前激活单元格所在选区为激活选区
+ * @returns
+ */
+ getActiveRange(): Nullable<IRangeData> {
+ const controls = this.getCurrentControls();
+ const model = controls && controls[controls.length - 1].model;
+ return (
+ model && {
+ startRow: model.startRow,
+ startColumn: model.startColumn,
+ endRow: model.endRow,
+ endColumn: model.endColumn,
+ }
+ );
+ }
+
+ /**
+ * get active selection control
+ * @returns
+ */
+ getActiveSelection(): Nullable<SelectionControl> {
+ const controls = this.getCurrentControls();
+ return controls && controls[controls.length - 1];
+ }
+
+ dispose() {
+ this.clearSelectionControls();
+ this._moveObserver = null;
+ this._upObserver = null;
+ }
+
+ /**
+ * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
+ * @param moveEvt
+ * @param selectionControl
+ * @returns
+ */
+ private _moving(moveOffsetX: number, moveOffsetY: number, selectionControl: Nullable<SelectionControl>) {
+ // console.log('moving');
+ const main = this._spreadsheet;
+ // const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+ const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;
+
+ // const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
+ // const scene = this.getScene() as Scene;
+
+ // const coord = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+ // const { x: newMoveOffsetX, y: newMoveOffsetY } = coord;
+
+ const scrollXY = main.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
+
+ const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY);
+ const moveActualSelection = makeCellToSelection(moveCellInfo);
+
+ if (!moveActualSelection) {
+ return false;
+ }
+ const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow } = moveActualSelection;
+
+ const newStartRow = Math.min(moveStartRow, startRow);
+ const newStartColumn = Math.min(moveStartColumn, startColumn);
+ const newEndRow = Math.max(moveEndRow, endRow);
+ const newEndColumn = Math.max(moveEndColumn, endColumn);
+ const newBounding = main.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
+
+ if (!newBounding) {
+ return false;
+ }
+ const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
+
+ const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
+ const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
+
+ const newSelectionRange: ISelection = {
+ startColumn: finalStartColumn,
+ startRow: finalStartRow,
+ endColumn: finalEndColumn,
+ endRow: finalEndRow,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ };
+ // Only notify when the selection changes
+ const {
+ startRow: oldStartRow,
+ endRow: oldEndRow,
+ startColumn: oldStartColumn,
+ endColumn: oldEndColumn,
+ } = selectionControl?.model || { startRow: -1, endRow: -1, startColumn: -1, endColumn: -1 };
+
+ if (oldStartColumn !== finalStartColumn || oldStartRow !== finalStartRow || oldEndColumn !== finalEndColumn || oldEndRow !== finalEndRow) {
+ selectionControl && selectionControl.update(newSelectionRange);
+ }
+ }
+
+ private _endSelection(scene: Scene) {
+ scene.onPointerMoveObserver.remove(this._moveObserver);
+ scene.onPointerUpObserver.remove(this._upObserver);
+ scene.enableEvent();
+
+ this._scrollTimer?.stopScroll();
+
+ const mainScene = scene.getEngine()?.activeScene;
+ mainScene?.onPointerDownObserver.remove(this._cancelDownObserver);
+ mainScene?.onPointerUpObserver.remove(this._cancelUpObserver);
+ }
+
+ private _addCancelObserver() {
+ const scene = this.getScene() as Scene;
+ const mainScene = scene.getEngine()?.activeScene;
+ if (mainScene == null || mainScene === scene) {
+ return;
+ }
+ mainScene.onPointerDownObserver.remove(this._cancelDownObserver);
+ mainScene.onPointerUpObserver.remove(this._cancelUpObserver);
+ this._cancelDownObserver = mainScene.onPointerDownObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ this._endSelection(scene);
+ });
+
+ this._cancelUpObserver = mainScene.onPointerUpObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ this._endSelection(scene);
+ });
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _mainEventInitial() {
+ const main = this._spreadsheet;
+ // eslint-disable-next-line max-lines-per-function
+ main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+
+ const scene = this.getScene() as Scene;
+
+ const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+
+ const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
+
+ this._startOffsetX = newEvtOffsetX;
+ this._startOffsetY = newEvtOffsetY;
+
+ const scrollXY = main.getScrollXYByRelativeCoords(relativeCoords);
+
+ const cellInfo = main.calculateCellIndexByPosition(newEvtOffsetX, newEvtOffsetY, scrollXY);
+ const actualSelection = makeCellToSelection(cellInfo);
+ if (!actualSelection) {
+ return false;
+ }
+
+ const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;
+
+ const startSelectionRange = {
+ startColumn,
+ startRow,
+ endColumn,
+ endRow,
+ startY,
+ endY,
+ startX,
+ endX,
+ };
+
+ this._startSelectionRange = startSelectionRange;
+
+ let selectionControl: Nullable<SelectionControl> = this.getCurrentControl();
+
+ const curControls = this.getCurrentControls();
+
+ if (!curControls) {
+ return false;
+ }
+
+ for (const control of curControls) {
+ // right click
+ if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {
+ selectionControl = control;
+ return;
+ }
+ // Click to an existing selection
+ if (control.model.isEqual(startSelectionRange)) {
+ selectionControl = control;
+ break;
+ }
+
+ // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
+ if (!evt.shiftKey) {
+ control.clearHighlight();
+ }
+ }
+
+ // In addition to pressing the ctrl or shift key, we must clear the previous selection
+ if (curControls.length > 0 && !evt.ctrlKey && !evt.shiftKey) {
+ for (const control of curControls) {
+ control.dispose();
+ }
+
+ curControls.length = 0; // clear currentSelectionControls
+ }
+
+ const currentCell = selectionControl && selectionControl.model.currentCell;
+
+ if (selectionControl && evt.shiftKey && currentCell) {
+ const { row, column } = currentCell;
+
+ // TODO startCell position calculate error
+ const startCell = main.getNoMergeCellPositionByIndex(row, column);
+ const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
+
+ const newSelectionRange = {
+ startColumn: column,
+ startRow: row,
+ endColumn: startSelectionRange.startColumn,
+ endRow: startSelectionRange.startRow,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ };
+ selectionControl.update(newSelectionRange, currentCell);
+ } else {
+ selectionControl = SelectionControl.create(scene, curControls.length + this.getMaxIndex());
+ selectionControl.update(startSelectionRange, cellInfo);
+ curControls.push(selectionControl);
+ }
+
+ this.hasSelection = true;
+
+ scene.disableEvent();
+
+ this._endSelection(scene);
+
+ const scrollTimer = ScrollTimer.create(this.getScene());
+ scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY);
+
+ this._scrollTimer = scrollTimer;
+
+ this._addCancelObserver();
+
+ this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+
+ this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
+
+ scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
+ this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
+ });
+ });
+
+ this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
+ this._endSelection(scene);
+ });
+
+ state.stopPropagation();
+ });
+ }
+}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
new file mode 100644
index 0000000000..0a0ae7d7fa
--- /dev/null
+++ b/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
@@ -0,0 +1,157 @@
+import { ICellInfo, ISelection, Nullable, makeCellToSelection } from '@univerjs/core';
+import { SELECTION_TYPE } from '../../../Basics/Const';
+
+export class SelectionModel implements ISelection {
+ private _startColumn: number;
+
+ private _startRow: number;
+
+ private _endColumn: number;
+
+ private _endRow: number;
+
+ private _startX: number;
+
+ private _startY: number;
+
+ private _endX: number;
+
+ private _endY: number;
+
+ private _type: SELECTION_TYPE;
+
+ private _currentCell: Nullable<ICellInfo>;
+
+ constructor(type: SELECTION_TYPE = SELECTION_TYPE.NORMAL) {
+ this._type = type;
+ }
+
+ get startColumn() {
+ return this._startColumn;
+ }
+
+ get startRow() {
+ return this._startRow;
+ }
+
+ get endColumn() {
+ return this._endColumn;
+ }
+
+ get endRow() {
+ return this._endRow;
+ }
+
+ get startX() {
+ return this._startX;
+ }
+
+ get startY() {
+ return this._startY;
+ }
+
+ get endX() {
+ return this._endX;
+ }
+
+ get endY() {
+ return this._endY;
+ }
+
+ get type() {
+ return this._type;
+ }
+
+ get currentCell() {
+ return this._currentCell;
+ }
+
+ isEqual(selectionRange: ISelection) {
+ const { startColumn, startRow, endColumn, endRow, type } = this;
+ const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
+ // if (type !== newType) {
+ // return false;
+ // }
+ if (startColumn === newStartColumn && startRow === newStartRow && endColumn === newEndColumn && endRow === newEndRow) {
+ return true;
+ }
+ return false;
+ }
+
+ isInclude(selectionRange: ISelection) {
+ const { startColumn, startRow, endColumn, endRow, type } = this;
+ const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
+
+ // if (type !== newType) {
+ // return false;
+ // }
+
+ if (!(newEndColumn < startColumn || newStartColumn > endColumn || newStartRow > endRow || newEndRow < startRow)) {
+ return true;
+ }
+ return false;
+ }
+
+ highlightToSelection() {
+ return makeCellToSelection(this._currentCell);
+ }
+
+ getValue() {
+ return {
+ selection: {
+ startColumn: this._startColumn,
+ startRow: this._startRow,
+ endColumn: this._endColumn,
+ endRow: this._endRow,
+
+ startX: this._startX,
+ startY: this._startY,
+ endX: this._endX,
+ endY: this._endY,
+ },
+ cell: this._currentCell,
+ };
+ }
+
+ setValue(newSelectionRange: ISelection, currentCell: Nullable<ICellInfo>) {
+ const {
+ startColumn,
+ startRow,
+ endColumn,
+ endRow,
+
+ startX,
+ startY,
+ endX,
+ endY,
+ } = newSelectionRange;
+
+ this._startColumn = startColumn;
+
+ this._startRow = startRow;
+
+ this._endColumn = endColumn;
+
+ this._endRow = endRow;
+
+ this._startX = startX;
+
+ this._startY = startY;
+
+ this._endX = endX;
+
+ this._endY = endY;
+
+ this.setCurrentCell(currentCell);
+ }
+
+ setCurrentCell(currentCell: Nullable<ICellInfo>) {
+ if (currentCell) {
+ this._currentCell = currentCell;
+ }
+ }
+
+ clearCurrentCell() {
+ this._currentCell = null;
+ }
+}
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index 068e41bd0e..d5abba10ab 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -21,6 +21,7 @@ import { columnIterator } from '../Docs/Common/Tools';
import { DocumentSkeleton } from '../Docs/DocSkeleton';
import { IDocumentSkeletonColumn } from '../../Basics/IDocumentSkeletonCached';
import { getRotateOffsetAndFarthestHypotenuse, getRotateOrientation } from '../../Basics/Draw';
+import { SelectionManager } from './Selection/SelectionManager';
const OBJECT_KEY = '__SHEET_EXTENSION_FONT_DOCUMENT_INSTANCE__';
@@ -43,6 +44,8 @@ export class Spreadsheet extends SheetComponent {
private _hasSelection = false;
+ private _selection: SelectionManager;
+
private _documents: Documents = new Documents(OBJECT_KEY, undefined, {
pageMarginLeft: 0,
pageMarginTop: 0,
@@ -189,8 +192,9 @@ export class Spreadsheet extends SheetComponent {
}
}
- // eslint-disable-next-line prefer-const
- let { isMerged, startY, endY, startX, endX, mergeInfo, isMergedMainCell } = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCacheAll);
+ const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCacheAll);
+ const { isMerged, isMergedMainCell } = cellInfo;
+ let { startY, endY, startX, endX, mergeInfo } = cellInfo;
startY = fixLineWidthByScale(startY + columnTitleHeight, scaleY);
endY = fixLineWidthByScale(endY + columnTitleHeight, scaleY);
@@ -227,8 +231,9 @@ export class Spreadsheet extends SheetComponent {
const { scaleX = 1, scaleY = 1 } = this.getParentScale();
const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight, dataMergeCacheAll } = spreadsheetSkeleton;
- // eslint-disable-next-line prefer-const
- let { isMerged, startY, endY, startX, endX, mergeInfo, isMergedMainCell } = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCacheAll);
+ const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCacheAll);
+ const { isMerged, isMergedMainCell } = cellInfo;
+ let { startY, endY, startX, endX, mergeInfo } = cellInfo;
startY = fixLineWidthByScale(startY + columnTitleHeight, scaleY);
endY = fixLineWidthByScale(endY + columnTitleHeight, scaleY);
@@ -363,10 +368,12 @@ export class Spreadsheet extends SheetComponent {
if (this._hasSelection) {
return;
}
+ this._selection = SelectionManager.create(this);
this._hasSelection = true;
}
disableSelection() {
+ this._selection?.dispose();
this._hasSelection = false;
}
@@ -480,7 +487,7 @@ export class Spreadsheet extends SheetComponent {
let parent: any = this.parent;
while (parent) {
if (parent.classType === RENDER_CLASS_TYPE.ENGINE || parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
- return parent;
+ return parent as Nullable<Engine | SceneViewer>;
}
parent = parent?.getParent && parent?.getParent();
}
diff --git a/packages/base-render/src/Viewport.ts b/packages/base-render/src/Viewport.ts
index 7827501642..0de291e83e 100644
--- a/packages/base-render/src/Viewport.ts
+++ b/packages/base-render/src/Viewport.ts
@@ -330,9 +330,9 @@ export class Viewport {
};
}
- transformScroll() {
- let x = this.scrollX;
- let y = this.scrollY;
+ getTransformedScroll() {
+ const x = this.scrollX;
+ const y = this.scrollY;
return this.getActualScroll(x, y);
}
@@ -379,7 +379,7 @@ export class Viewport {
this._applyCache(mainCtx);
return;
}
- let sceneTrans = this._scene.transform.clone();
+ const sceneTrans = this._scene.transform.clone();
sceneTrans.multiply(Transform.create([1, 0, 0, 1, -this.actualScrollX || 0, -this.actualScrollY || 0]));
@@ -431,7 +431,7 @@ export class Viewport {
getRelativeVector(coord: Vector2) {
const sceneTrans = this.scene.transform.clone().invert();
- const scroll = this.transformScroll();
+ const scroll = this.getTransformedScroll();
const svCoord = sceneTrans.applyPoint(coord).add(Vector2.FromArray([scroll.x, scroll.y]));
return svCoord;
@@ -439,7 +439,7 @@ export class Viewport {
getAbsoluteVector(coord: Vector2) {
const sceneTrans = this.scene.transform.clone();
- const scroll = this.transformScroll();
+ const scroll = this.getTransformedScroll();
const svCoord = sceneTrans.applyPoint(coord).subtract(Vector2.FromArray([scroll.x, scroll.y]));
return svCoord;
@@ -456,7 +456,7 @@ export class Viewport {
// let magicNumber = deltaFactor < 40 ? 2 : deltaFactor < 80 ? 3 : 4;
const allWidth = this._scene.width;
const viewWidth = this.width || 1;
- let scrollNum = (viewWidth / allWidth) * deltaFactor;
+ const scrollNum = (viewWidth / allWidth) * deltaFactor;
if (evt.deltaX > 0) {
isLimitedStore = this.scrollBy({
@@ -484,7 +484,7 @@ export class Viewport {
const allHeight = this._scene.height;
const viewHeight = this.height || 1;
// let magicNumber = deltaFactor < 40 ? 2 : deltaFactor < 80 ? 3 : 4;
- let scrollNum = (viewHeight / allHeight) * deltaFactor;
+ const scrollNum = (viewHeight / allHeight) * deltaFactor;
if (evt.shiftKey) {
if (evt.deltaY > 0) {
isLimitedStore = this.scrollBy({
@@ -596,7 +596,7 @@ export class Viewport {
width = this._widthOrigin!;
} else {
const referenceWidth = parent.width;
- let containerWidth = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceWidth * parent.scaleX : referenceWidth;
+ const containerWidth = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceWidth * parent.scaleX : referenceWidth;
width = containerWidth - (this._left + this._right);
}
@@ -604,7 +604,7 @@ export class Viewport {
height = this._heightOrigin!;
} else {
const referenceHeight = parent.height;
- let containerHeight = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceHeight * parent.scaleY : referenceHeight;
+ const containerHeight = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceHeight * parent.scaleY : referenceHeight;
height = containerHeight - (this._top + this._bottom);
}
@@ -716,7 +716,7 @@ export class Viewport {
this.makeDirty(true);
}
- const scroll = this.transformScroll();
+ const scroll = this.getTransformedScroll();
this.actualScrollX = scroll.x;
this.actualScrollY = scroll.y;
@@ -738,12 +738,12 @@ export class Viewport {
}
private _calViewportRelativeBounding() {
- let ratioScrollX = this._scrollBar?.ratioScrollX ?? 1;
- let ratioScrollY = this._scrollBar?.ratioScrollY ?? 1;
- let xFrom: number = this.left;
- let xTo: number = (this.width || 0) + this.left;
- let yFrom: number = this.top;
- let yTo: number = (this.height || 0) + this.top;
+ const ratioScrollX = this._scrollBar?.ratioScrollX ?? 1;
+ const ratioScrollY = this._scrollBar?.ratioScrollY ?? 1;
+ const xFrom: number = this.left;
+ const xTo: number = (this.width || 0) + this.left;
+ const yFrom: number = this.top;
+ const yTo: number = (this.height || 0) + this.top;
let differenceX = 0;
let differenceY = 0;
diff --git a/packages/base-sheets/src/Commands/Commands/set-style.command.ts b/packages/base-sheets/src/Commands/Commands/set-style.command.ts
index 5a8529a375..74383b69c0 100644
--- a/packages/base-sheets/src/Commands/Commands/set-style.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-style.command.ts
@@ -43,7 +43,7 @@ export interface ISetStyleParams<T> {
* The command to set cell style.
* Set style to a bunch of ranges.
*/
-export const SetStyleCommand: ICommand = {
+export const SetStyleCommand: ICommand<ISetStyleParams> = {
type: CommandType.COMMAND,
id: 'sheet.command.set-style',
@@ -224,6 +224,8 @@ export const SetFontFamilyCommand: ICommand<ISetFontFamilyCommandParams> = {
return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
},
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
};
export interface ISetFontSizeCommandParams {
@@ -419,3 +421,63 @@ export const SetSpanCommand: ICommand = {
id: 'sheet.command.set-span',
handler: async (accessor, params) => true,
};
+
+export const SetFontFamilyCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-font-family',
+ handler: async (accessor) => true,
+};
+
+export const SetFontSizeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-font-family',
+ handler: async (accessor) => true,
+};
+
+export const SetTextColorCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-font-family',
+ handler: async (accessor) => true,
+};
+
+export const SetBackgroundColorCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-background-color',
+ handler: async (accessor) => true,
+};
+
+export const SetCellBorderCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-cell-border',
+ handler: async (accessor) => true,
+};
+
+export const SetSpanCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-span',
+ handler: async (params) => true,
+};
+
+export const SetVerticalTextAlignCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-vertical-text-align',
+ handler: async (params) => true,
+};
+
+export const SetHorizontalTextAlignCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-horizontal-text-align',
+ handler: async (params) => true,
+};
+
+export const SetTextWrapCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-text-wrap',
+ handler: async (params) => true,
+};
+
+export const SetTextRotationCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-text-rotation',
+ handler: async (params) => true,
+};
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
index a16e632649..7783d65dc5 100644
--- a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
+++ b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
@@ -1019,4 +1019,4 @@ export class SelectionManager {
private getWorksheetId(): string {
return this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 9317510a65..291bc2d336 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -34,8 +34,6 @@ export {
SetVerticalTextAlignCommand,
} from './Commands/Commands/set-style.command';
export { InsertSheetCommand } from './Commands/Commands/insert-sheet.command';
-export { ClearSelectionContentCommand } from './Commands/Commands/clear-selection-content.command';
-export { InsertRowCommand, InsertColCommand } from './Commands/Commands/insert-row-col.command';
export { SetWorksheetActivateCommand } from './Commands/Commands/set-worksheet-activate.command';
export { SetWorksheetOrderCommand } from './Commands/Commands/set-worksheet-order.command';
export { SetWorksheetRowHeightCommand } from './Commands/Commands/set-worksheet-row-height.command';
diff --git a/packages/base-slides/src/SlidePlugin.ts b/packages/base-slides/src/SlidePlugin.ts
index e3992d923b..b2ba8c87af 100644
--- a/packages/base-slides/src/SlidePlugin.ts
+++ b/packages/base-slides/src/SlidePlugin.ts
@@ -6,7 +6,7 @@ import { install, SlidePluginObserve, uninstall } from './Basics/Observer';
import { CanvasView } from './View/Render';
import { ToolbarController } from './Controller';
-export interface ISlidePluginConfig { }
+export interface ISlidePluginConfig {}
const DEFAULT_SLIDE_PLUGIN_DATA = {};
@@ -41,7 +41,7 @@ export class SlidePlugin extends Plugin<SlidePluginObserve> {
install(this);
// this.initConfig();
this.initController();
- this.initCanvasView();
+ this.initCanvasEngine();
// this.registerExtension();
// this.listenEventManager();
}
@@ -56,7 +56,7 @@ export class SlidePlugin extends Plugin<SlidePluginObserve> {
this._toolbarController = this._injector.get(ToolbarController);
}
- initCanvasView() {
+ initCanvasEngine() {
this._canvasEngine = this._injector.get(IRenderingEngine);
}
diff --git a/packages/base-slides/src/View/Render/Adaptors/SpreadsheetAdaptor.ts b/packages/base-slides/src/View/Render/Adaptors/SpreadsheetAdaptor.ts
index ee80432371..20793f0b18 100644
--- a/packages/base-slides/src/View/Render/Adaptors/SpreadsheetAdaptor.ts
+++ b/packages/base-slides/src/View/Render/Adaptors/SpreadsheetAdaptor.ts
@@ -13,8 +13,8 @@ import {
SpreadsheetSkeleton,
Viewport,
} from '@univerjs/base-render';
-import { EventState, ICellData, IPageElement, ObjectMatrix, PageElementType, Styles, Injector, LocaleService } from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
+import { EventState, ICellData, IPageElement, ObjectMatrix, PageElementType, Styles, LocaleService } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
import { ObjectAdaptor, CanvasObjectProviderRegistry } from '../Adaptor';
enum SHEET_VIEW_KEY {
@@ -111,6 +111,7 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
return sv;
}
+ // eslint-disable-next-line max-lines-per-function
private _updateViewport(id: string, rowTitleWidth: number, columnTitleHeight: number, scene: Scene, mainScene: Scene) {
if (mainScene == null) {
return;
diff --git a/packages/base-ui/src/Components/Menu/Menu.tsx b/packages/base-ui/src/Components/Menu/Menu.tsx
index 1a1fa83bf4..054b098cd3 100644
--- a/packages/base-ui/src/Components/Menu/Menu.tsx
+++ b/packages/base-ui/src/Components/Menu/Menu.tsx
@@ -1,9 +1,11 @@
import { Component, ComponentChild, createRef } from 'preact';
import { Subscription } from 'rxjs';
import { ICommandService } from '@univerjs/core';
-import { BaseMenuProps, BaseMenuState, BaseMenuItem, BaseMenuStyle } from '../../Interfaces';
import { joinClassNames } from '../../Utils';
import { CustomLabel } from '../CustomLabel';
+
+import { BaseMenuProps, BaseMenuState, BaseMenuItem, BaseMenuStyle } from '../../Interfaces';
+
import styles from './index.module.less';
import { IDisplayMenuItem } from '../../services/menu/menu.service';
import AppContext from '../../Common/AppContext';
@@ -107,7 +109,7 @@ export class Menu extends Component<BaseMenuProps, BaseMenuState> {
};
render() {
- const { className = '', style = '', menu, menuItems, deep = 0 } = this.props;
+ const { className = '', menuItems, style = '', menu, deep = 0 } = this.props;
const { show, posStyle } = this.state;
return (
@@ -154,7 +156,7 @@ export class Menu extends Component<BaseMenuProps, BaseMenuState> {
);
}
- protected initialize() {
+ protected override initialize() {
this.state = {
show: false,
posStyle: {},
@@ -177,16 +179,6 @@ export class MenuItem extends Component<{ menuItem: IDisplayMenuItem; index: num
};
}
- override componentDidMount(): void {
- this.disabledSubscription = this.props.menuItem.disabled$?.subscribe((disabled) => {
- this.setState({ disabled });
- });
- }
-
- override componentWillUnmount(): void {
- this.disabledSubscription?.unsubscribe();
- }
-
mouseEnter = (e: MouseEvent, index: number) => {
const { menuItem } = this.props;
if (menuItem.subMenus) {
@@ -201,6 +193,16 @@ export class MenuItem extends Component<{ menuItem: IDisplayMenuItem; index: num
}
};
+ override componentDidMount(): void {
+ this.disabledSubscription = this.props.menuItem.disabled$?.subscribe((disabled) => {
+ this.setState({ disabled });
+ });
+ }
+
+ override componentWillUnmount(): void {
+ this.disabledSubscription?.unsubscribe();
+ }
+
override render(): ComponentChild {
const { menuItem: item, index } = this.props;
const commandService: ICommandService = this.context.injector.get(ICommandService);
@@ -209,6 +211,7 @@ export class MenuItem extends Component<{ menuItem: IDisplayMenuItem; index: num
return (
<li
className={joinClassNames(styles.colsMenuitem, disabled ? styles.colsMenuitemDisabled : '')}
+ // style={{ ...style }}
onClick={() => {
this.props.onClick();
commandService.executeCommand(item.id);
diff --git a/packages/base-ui/src/Interfaces/Menu.ts b/packages/base-ui/src/Interfaces/Menu.ts
index a1764e9621..2880b2bdcb 100644
--- a/packages/base-ui/src/Interfaces/Menu.ts
+++ b/packages/base-ui/src/Interfaces/Menu.ts
@@ -1,6 +1,6 @@
import { ComponentChildren, JSX } from 'preact';
import { BaseComponent, JSXComponent } from '../BaseComponent';
-import { IDisplayMenuItem } from '../services/menu/menu.service';
+import { IDisplayMenuItem, IMenuItem } from '../services/menu/menu.service';
export interface BaseMenuItem {
className?: string;
@@ -27,6 +27,10 @@ export interface BaseMenuProps {
deep?: number;
}
+export interface TreeMenuItems extends IMenuItem {
+ subMenuItems: TreeMenuItems[];
+}
+
export type BaseMenuState = {
show: boolean;
posStyle: BaseMenuStyle;
diff --git a/packages/base-ui/src/services/menu/menu.service.ts b/packages/base-ui/src/services/menu/menu.service.ts
index bc549ef204..cc25c47797 100644
--- a/packages/base-ui/src/services/menu/menu.service.ts
+++ b/packages/base-ui/src/services/menu/menu.service.ts
@@ -1,9 +1,10 @@
import { Disposable, toDisposable } from '@univerjs/core';
import { createIdentifier, IDisposable } from '@wendellhu/redi';
import { Observable } from 'rxjs';
+import { ComponentChildren } from 'preact';
import { IShortcutService } from '../shortcut/shorcut.service';
import { ICustomLabelType } from '../../Interfaces/CustomLabel';
-import { ComponentChildren } from 'preact';
+import { BaseSelectChildrenProps } from '../../Components/Select/Select';
export type OneOrMany<T> = T | T[];
@@ -21,6 +22,22 @@ export interface IMenuItemState {
checked?: boolean;
}
+// TODO@Dushusir remove CustomLabelProps and CustomLabel in rightMenuUIController after migrate new UI system
+
+interface CustomLabelProps {
+ prefix?: string[] | string;
+ suffix?: string[] | string;
+ options?: BaseSelectChildrenProps[];
+ label?: string;
+ children?: CustomLabelProps[];
+ onKeyUp?: (e: Event) => void;
+}
+
+export interface CustomLabel {
+ name: string;
+ props?: CustomLabelProps;
+}
+
export interface IMenuItem {
id: string;
menu: OneOrMany<MenuPosition>;
@@ -89,6 +106,7 @@ export class DesktopMenuService extends Disposable implements IMenuService {
}
getMenuItems(positions: MenuPosition): IDisplayMenuItem[] {
+ // TODO: @wzhudev: compose shortcut to returned menu items.
if (this._menuByPositions.has(positions)) {
return [...this._menuByPositions.get(positions)!.values()].map((menu) => this.getDisplayMenuItems(menu));
}
diff --git a/packages/core/src/Command/Command.ts b/packages/core/src/Command/Command.ts
index 36f377b510..3cb28c1533 100644
--- a/packages/core/src/Command/Command.ts
+++ b/packages/core/src/Command/Command.ts
@@ -57,11 +57,12 @@ export class Command {
}
invoke(): void {
+ this._commonParameter.reset();
this.actionDataList.forEach((data) => {
const ActionClass = CommandManager.getAction(data.actionName);
if (!ActionClass) return;
const observers = CommandManager.getActionObservers();
- const action = new ActionClass(data, this.unit, observers, this._commonParameter.reset());
+ const action = new ActionClass(data, this.unit, observers, this._commonParameter);
this.actionList.push(action);
});
@@ -102,4 +103,4 @@ export class Command {
}
})();
}
-}
\ No newline at end of file
+}
diff --git a/packages/core/src/Docs/Action/ActionDataInterface.ts b/packages/core/src/Docs/Action/ActionDataInterface.ts
index 5b50de6d8b..4105e07172 100644
--- a/packages/core/src/Docs/Action/ActionDataInterface.ts
+++ b/packages/core/src/Docs/Action/ActionDataInterface.ts
@@ -25,12 +25,14 @@ export interface IInsertActionData extends IDocActionData {
}
export interface IRetainActionData extends IDocActionData {
- body: Nullable<IDocumentBody>;
+ body?: Nullable<IDocumentBody>;
len: number;
- coverType: UpdateDocsAttributeType;
+ coverType?: UpdateDocsAttributeType;
segmentId?: string;
}
export interface IUpdateDocumentActionData extends IDocActionData {
text: string;
}
+
+export type DocActionType = IDeleteActionData | IInsertActionData | IRetainActionData;
diff --git a/packages/core/src/Docs/Action/DeleteAction.ts b/packages/core/src/Docs/Action/DeleteAction.ts
index 3f06875062..dcad53badd 100644
--- a/packages/core/src/Docs/Action/DeleteAction.ts
+++ b/packages/core/src/Docs/Action/DeleteAction.ts
@@ -42,7 +42,7 @@ export class DeleteAction extends DocActionBase<IDeleteActionData, IInsertAction
const body = DeleteApply(document, len, commonParameter.cursor, segmentId);
- commonParameter.moveCursor(len);
+ // commonParameter.moveCursor(len);
this._observers.notifyObservers({
type: ActionType.REDO,
diff --git a/packages/core/src/Docs/Action/InsertAction.ts b/packages/core/src/Docs/Action/InsertAction.ts
index c823de809d..2eddfb0c32 100644
--- a/packages/core/src/Docs/Action/InsertAction.ts
+++ b/packages/core/src/Docs/Action/InsertAction.ts
@@ -49,7 +49,7 @@ export class InsertAction extends DocActionBase<IInsertActionData, IDeleteAction
DeleteApply(document, len, commonParameter.cursor, segmentId);
- commonParameter.moveCursor(len);
+ // commonParameter.moveCursor(len);
// DeleteTextApply(document, { ...actionData });
this._observers.notifyObservers({
diff --git a/packages/core/src/Docs/Action/RetainAction.ts b/packages/core/src/Docs/Action/RetainAction.ts
index af3337f43b..c9d754ebd2 100644
--- a/packages/core/src/Docs/Action/RetainAction.ts
+++ b/packages/core/src/Docs/Action/RetainAction.ts
@@ -28,7 +28,7 @@ export class RetainAction extends DocActionBase<IRetainActionData, IRetainAction
const document = this.getDocument();
const { len, segmentId, body, coverType } = actionData;
- let result: Nullable<IDocumentBody> = UpdateAttributeApply(document, body, len, commonParameter.cursor, coverType, segmentId);
+ const result: Nullable<IDocumentBody> = UpdateAttributeApply(document, body, len, commonParameter.cursor, coverType, segmentId);
commonParameter.moveCursor(len);
diff --git a/packages/core/src/Docs/Apply/Common.ts b/packages/core/src/Docs/Apply/Common.ts
index 68f4f4573e..5c58fbbc09 100644
--- a/packages/core/src/Docs/Apply/Common.ts
+++ b/packages/core/src/Docs/Apply/Common.ts
@@ -1,7 +1,9 @@
-import { IDocumentBody } from '../../Interfaces/IDocumentData';
-import { horizontalLineSegmentsSubtraction } from '../../Shared/Common';
+import { ICustomBlock, ICustomRange, IDocumentBody, IParagraph, ISectionBreak, ITable, ITextRun } from '../../Types/Interfaces/IDocumentData';
+import { Nullable } from '../../Shared/Types';
+import { checkParagraphHasBullet, horizontalLineSegmentsSubtraction } from '../../Shared/DocTool';
import { isSameStyleTextRun } from '../../Shared/Compare';
import { sortRulesFactory } from '../../Shared/SortRules';
+import { DataStreamTreeTokenType } from '../Domain/Types';
export function insertTextRuns(body: IDocumentBody, insertBody: IDocumentBody, textLength: number, currentIndex: number) {
const { textRuns } = body;
@@ -76,19 +78,50 @@ export function insertParagraphs(body: IDocumentBody, insertBody: IDocumentBody,
if (paragraphs == null) {
return;
}
+
+ const { paragraphs: insertParagraphs, dataStream: insertDataStream } = insertBody;
+
+ const paragraphIndexList = [];
+ let firstInsertParagraphNextIndex = -1;
for (let i = 0, len = paragraphs.length; i < len; i++) {
const paragraph = paragraphs[i];
const { startIndex } = paragraph;
if (startIndex > currentIndex) {
paragraph.startIndex += textLength;
}
+
+ if (firstInsertParagraphNextIndex === -1 && startIndex > currentIndex) {
+ firstInsertParagraphNextIndex = i;
+ }
+
+ paragraphIndexList.push(paragraph.startIndex);
}
- const insertParagraphs = insertBody.paragraphs;
+ let deleteReptIndex = -1;
if (insertParagraphs) {
for (let i = 0, len = insertParagraphs.length; i < len; i++) {
- const insertTextRun = insertParagraphs[i];
- insertTextRun.startIndex += currentIndex;
+ const insertParagraph = insertParagraphs[i];
+ insertParagraph.startIndex += currentIndex;
+ const insertIndex = insertParagraph.startIndex;
+ deleteReptIndex = paragraphIndexList.indexOf(insertIndex);
+ }
+
+ if (insertDataStream === DataStreamTreeTokenType.PARAGRAPH && insertParagraphs.length === 1) {
+ const nextParagraph = paragraphs[firstInsertParagraphNextIndex];
+ const insertParagraph = insertParagraphs[0];
+
+ const nextParagraphStyle = nextParagraph.paragraphStyle;
+ const nextBullet = nextParagraph.bullet;
+
+ nextParagraph.paragraphStyle = insertParagraph.paragraphStyle;
+ nextParagraph.bullet = insertParagraph.bullet;
+
+ insertParagraph.paragraphStyle = nextParagraphStyle;
+ insertParagraph.bullet = nextBullet;
+ }
+
+ if (deleteReptIndex !== -1) {
+ paragraphs.splice(deleteReptIndex, 1);
}
paragraphs.push(...insertParagraphs);
@@ -218,7 +251,7 @@ export function deleteTextRuns(body: IDocumentBody, textLength: number, currentI
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
- const removeTextRuns = [];
+ const removeTextRuns: ITextRun[] = [];
if (textRuns) {
const newTextRuns = [];
for (let i = 0, len = textRuns.length; i < len; i++) {
@@ -235,15 +268,8 @@ export function deleteTextRuns(body: IDocumentBody, textLength: number, currentI
} else if (st <= startIndex && ed >= endIndex) {
const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);
- if (segments.length > 2) {
- const seg1 = segments[0];
- const seg2 = segments[1];
- textRun.st = seg1[0];
- textRun.ed = seg1[1] + seg2[1] - seg2[0] + 1;
- } else {
- textRun.st = segments[0][0];
- textRun.ed = segments[0][1];
- }
+ textRun.st = segments[0];
+ textRun.ed = segments[1];
} else if (startIndex >= st && startIndex <= ed) {
removeTextRuns.push({
...textRun,
@@ -257,7 +283,8 @@ export function deleteTextRuns(body: IDocumentBody, textLength: number, currentI
st: st - currentIndex,
ed: endIndex - currentIndex,
});
- textRun.st = endIndex + 1;
+ textRun.st = endIndex - textLength + 1;
+ textRun.ed -= textLength;
} else if (st > endIndex) {
textRun.st -= textLength;
textRun.ed -= textLength;
@@ -276,23 +303,53 @@ export function deleteParagraphs(body: IDocumentBody, textLength: number, curren
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
- const removeParagraphs = [];
+ const removeParagraphs: IParagraph[] = [];
+ let removeAfterFirstNew: Nullable<IParagraph> = null;
+ let isRemove = false;
if (paragraphs) {
const newParagraphs = [];
for (let i = 0, len = paragraphs.length; i < len; i++) {
const paragraph = paragraphs[i];
const { startIndex: index } = paragraph;
- if (index >= startIndex && index <= endIndex) {
+ if (startIndex === endIndex && endIndex === index) {
+ const nextParagraph = paragraphs[i + 1];
+ const isBullet = checkParagraphHasBullet(nextParagraph);
+ if (isBullet && nextParagraph != null) {
+ delete nextParagraph.bullet;
+ delete nextParagraph.paragraphStyle?.hanging;
+ delete nextParagraph.paragraphStyle?.indentStart;
+ }
+ } else if (index >= startIndex && index <= endIndex) {
removeParagraphs.push({
...paragraph,
startIndex: index - currentIndex,
});
+ isRemove = true;
continue;
} else if (index > endIndex) {
paragraph.startIndex -= textLength;
}
newParagraphs.push(paragraph);
+
+ if (removeAfterFirstNew == null && isRemove) {
+ removeAfterFirstNew = paragraph;
+ }
+ }
+ if (removeAfterFirstNew != null) {
+ // When deleting a paragraph, the configuration of the paragraph
+ // in the beginning range should be retained. Due to the label design,
+ // the paragraph mark is located after the content, so when deleting,
+ // it will surround the configuration of the end range. A position update is required,
+ // and the undo time should also be considered Restoration of position
+ const removeFirst = removeParagraphs[0];
+ if (removeFirst) {
+ const newInsert = { ...removeFirst };
+ removeParagraphs.push(removeAfterFirstNew);
+ newParagraphs.splice(newParagraphs.indexOf(removeAfterFirstNew), 1, newInsert);
+ newInsert.startIndex = removeAfterFirstNew.startIndex;
+ removeAfterFirstNew.startIndex += textLength - currentIndex;
+ }
}
body.paragraphs = newParagraphs;
}
@@ -305,7 +362,7 @@ export function deleteSectionBreaks(body: IDocumentBody, textLength: number, cur
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
- const removeSectionBreaks = [];
+ const removeSectionBreaks: ISectionBreak[] = [];
if (sectionBreaks) {
const newSectionBreaks = [];
for (let i = 0, len = sectionBreaks.length; i < len; i++) {
@@ -334,7 +391,7 @@ export function deleteCustomBlocks(body: IDocumentBody, textLength: number, curr
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
- const removeCustomBlocks = [];
+ const removeCustomBlocks: ICustomBlock[] = [];
if (customBlocks) {
const newCustomBlocks = [];
for (let i = 0, len = customBlocks.length; i < len; i++) {
@@ -363,7 +420,7 @@ export function deleteTables(body: IDocumentBody, textLength: number, currentInd
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
- const removeTables = [];
+ const removeTables: ITable[] = [];
if (tables) {
const newTables = [];
for (let i = 0, len = tables.length; i < len; i++) {
@@ -372,22 +429,15 @@ export function deleteTables(body: IDocumentBody, textLength: number, currentInd
if (startIndex <= st && endIndex >= ed) {
removeTables.push({
...table,
- st: st - currentIndex,
- ed: ed - currentIndex,
+ startIndex: st - currentIndex,
+ endIndex: ed - currentIndex,
});
continue;
} else if (st <= startIndex && ed >= endIndex) {
const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);
- if (segments.length > 2) {
- const seg1 = segments[0];
- const seg2 = segments[1];
- table.startIndex = seg1[0];
- table.endIndex = seg1[1] + seg2[1] - seg2[0] + 1;
- } else {
- table.startIndex = segments[0][0];
- table.endIndex = segments[0][1];
- }
+ table.startIndex = segments[0];
+ table.endIndex = segments[1];
} else if (endIndex < st) {
table.startIndex -= textLength;
table.endIndex -= textLength;
@@ -405,7 +455,7 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
- const removeCustomRanges = [];
+ const removeCustomRanges: ICustomRange[] = [];
if (customRanges) {
const newCustomRanges = [];
for (let i = 0, len = customRanges.length; i < len; i++) {
@@ -414,22 +464,15 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
if (startIndex <= st && endIndex >= ed) {
removeCustomRanges.push({
...customRange,
- st: st - currentIndex,
- ed: ed - currentIndex,
+ startIndex: st - currentIndex,
+ endIndex: ed - currentIndex,
});
continue;
} else if (st <= startIndex && ed >= endIndex) {
const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);
- if (segments.length > 2) {
- const seg1 = segments[0];
- const seg2 = segments[1];
- customRange.startIndex = seg1[0];
- customRange.endIndex = seg1[1] + seg2[1] - seg2[0] + 1;
- } else {
- customRange.startIndex = segments[0][0];
- customRange.endIndex = segments[0][1];
- }
+ customRange.startIndex = segments[0];
+ customRange.endIndex = segments[1];
} else if (endIndex < st) {
customRange.startIndex -= textLength;
customRange.endIndex -= textLength;
diff --git a/packages/core/src/Docs/Apply/DeleteApply.ts b/packages/core/src/Docs/Apply/DeleteApply.ts
index 1a4e6ad78f..500e620eff 100644
--- a/packages/core/src/Docs/Apply/DeleteApply.ts
+++ b/packages/core/src/Docs/Apply/DeleteApply.ts
@@ -1,6 +1,8 @@
import { DocumentModel } from '../Domain/DocumentModel';
-import { deleteContent, getDocsUpdateBody } from '../../Shared/Common';
+import { getDocsUpdateBody } from '../../Shared/Common';
+import { deleteContent } from '../../Shared/DocTool';
import { IDocumentBody } from '../../Types/Interfaces/IDocumentData';
+import { deleteCustomBlocks, deleteCustomRanges, deleteParagraphs, deleteSectionBreaks, deleteTables, deleteTextRuns } from './Common';
export function DeleteApply(document: DocumentModel, textLength: number, currentIndex: number, segmentId?: string) {
const doc = document.snapshot;
@@ -15,7 +17,11 @@ export function DeleteApply(document: DocumentModel, textLength: number, current
bodyModel.delete(currentIndex, textLength);
- return updateAttributeByDelete(body, textLength, currentIndex);
+ const deleBody = updateAttributeByDelete(body, textLength, currentIndex);
+
+ console.log('删除的model打印', bodyModel, body, deleBody);
+
+ return deleBody;
}
function updateAttributeByDelete(body: IDocumentBody, textLength: number, currentIndex: number): IDocumentBody {
diff --git a/packages/core/src/Docs/Apply/InsertApply.ts b/packages/core/src/Docs/Apply/InsertApply.ts
index 3066732aa2..025c54b999 100644
--- a/packages/core/src/Docs/Apply/InsertApply.ts
+++ b/packages/core/src/Docs/Apply/InsertApply.ts
@@ -1,6 +1,7 @@
import { IDocumentBody } from '../../Types/Interfaces/IDocumentData';
import { DocumentModel } from '../Domain/DocumentModel';
import { getDocsUpdateBody } from '../../Shared/Common';
+import { insertTextToContent } from '../../Shared/DocTool';
import { insertCustomBlocks, insertCustomRanges, insertParagraphs, insertSectionBreaks, insertTables, insertTextRuns } from './Common';
export function InsertApply(document: DocumentModel, insertBody: IDocumentBody, textLength: number, currentIndex: number, segmentId?: string) {
@@ -21,9 +22,13 @@ export function InsertApply(document: DocumentModel, insertBody: IDocumentBody,
bodyModel.insert(insertBody, currentIndex);
updateAttributeByInsert(body, insertBody, textLength, currentIndex);
+
+ console.log('插入的model打印', bodyModel, body);
}
function updateAttributeByInsert(body: IDocumentBody, insertBody: IDocumentBody, textLength: number, currentIndex: number) {
+ body.dataStream = insertTextToContent(body.dataStream, currentIndex, insertBody.dataStream);
+
insertTextRuns(body, insertBody, textLength, currentIndex);
insertParagraphs(body, insertBody, textLength, currentIndex);
diff --git a/packages/core/src/Docs/Apply/UpdateAttributeApply.ts b/packages/core/src/Docs/Apply/UpdateAttributeApply.ts
index aa71ef84cc..860c4b2b22 100644
--- a/packages/core/src/Docs/Apply/UpdateAttributeApply.ts
+++ b/packages/core/src/Docs/Apply/UpdateAttributeApply.ts
@@ -1,15 +1,27 @@
-import { IDocumentBody } from '../../Interfaces/IDocumentData';
import { DocumentModel } from '../Domain/DocumentModel';
-import { getDocsUpdateBody, horizontalLineSegmentsSubtraction } from '../../Shared/Common';
+import { getDocsUpdateBody } from '../../Shared/Common';
import { UpdateDocsAttributeType } from '../../Shared/CommandEnum';
import { Nullable } from '../../Shared/Types';
+import {
+ deleteCustomBlocks,
+ deleteCustomRanges,
+ deleteParagraphs,
+ deleteSectionBreaks,
+ deleteTables,
+ deleteTextRuns,
+ insertCustomBlocks,
+ insertParagraphs,
+ insertTables,
+ insertTextRuns,
+} from './Common';
+import { ICustomBlock, ICustomRange, IDocumentBody, IParagraph, ISectionBreak, ITable, ITextRun } from '../../Interfaces/IDocumentData';
export function UpdateAttributeApply(
document: DocumentModel,
updateBody: Nullable<IDocumentBody>,
textLength: number,
currentIndex: number,
- coverType: UpdateDocsAttributeType,
+ coverType = UpdateDocsAttributeType.COVER,
segmentId?: string
) {
if (updateBody == null) {
@@ -30,78 +42,330 @@ export function UpdateAttributeApply(
function updateAttribute(body: IDocumentBody, updateBody: IDocumentBody, textLength: number, currentIndex: number, coverType: UpdateDocsAttributeType): IDocumentBody {
const removeTextRuns = updateTextRuns(body, updateBody, textLength, currentIndex, coverType);
+ const removeParagraphs = updateParagraphs(body, updateBody, textLength, currentIndex, coverType);
+
+ const removeSectionBreaks = updateSectionBreaks(body, updateBody, textLength, currentIndex, coverType);
+
+ const removeCustomBlocks = updateCustomBlocks(body, updateBody, textLength, currentIndex, coverType);
+
+ const removeTables = updateTables(body, updateBody, textLength, currentIndex, coverType);
+
+ const removeCustomRanges = updateCustomRanges(body, updateBody, textLength, currentIndex, coverType);
+
return {
dataStream: '',
textRuns: removeTextRuns,
- // paragraphs: removeParagraphs,
- // sectionBreaks: removeSectionBreaks,
- // customBlocks: removeCustomBlocks,
- // tables: removeTables,
- // customRanges: removeCustomRanges,
+ paragraphs: removeParagraphs,
+ sectionBreaks: removeSectionBreaks,
+ customBlocks: removeCustomBlocks,
+ tables: removeTables,
+ customRanges: removeCustomRanges,
};
}
function updateTextRuns(body: IDocumentBody, updateBody: IDocumentBody, textLength: number, currentIndex: number, coverType: UpdateDocsAttributeType) {
const { textRuns } = body;
- const { textRuns: updateTextRuns } = updateBody;
+ let { textRuns: updateDataTextRuns } = updateBody;
- if (textRuns == null || updateTextRuns == null) {
+ if (textRuns == null || updateDataTextRuns == null) {
return;
}
- const startIndex = currentIndex;
+ const removeTextRuns = deleteTextRuns(body, textLength, currentIndex);
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateTextRun = coverTextRun(updateDataTextRuns, removeTextRuns, coverType);
+ updateBody.textRuns = newUpdateTextRun;
+ }
+ insertTextRuns(body, updateBody, textLength, currentIndex);
+
+ return removeTextRuns;
+}
+
+function coverTextRun(updateDataTextRuns: ITextRun[], removeTextRuns: ITextRun[], coverType: UpdateDocsAttributeType) {
+ const newUpdateTextRun: ITextRun[] = [];
+ for (let updateTextRun of updateDataTextRuns) {
+ let { st: updateSt, ed: updateEd, ts: updateStyle } = updateTextRun;
+ let splitUpdateTextRuns: ITextRun[] = [];
+ for (let removeTextRun of removeTextRuns) {
+ const { st: removeSt, ed: removeEd, ts: removeStyle, sId } = removeTextRun;
+ let newTs;
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ newTs = { ...removeStyle, ...updateStyle };
+ } else {
+ newTs = { ...updateStyle, ...removeStyle };
+ }
+ if (updateSt >= removeSt && updateEd <= removeEd) {
+ splitUpdateTextRuns.push({
+ st: updateSt,
+ ed: updateEd,
+ ts: newTs,
+ sId,
+ });
+ continue;
+ } else if (updateSt <= removeSt && updateEd >= removeEd) {
+ if (updateSt <= removeSt - 1) {
+ splitUpdateTextRuns.push({
+ st: updateSt,
+ ed: removeSt - 1,
+ ts: newTs,
+ sId,
+ });
+ }
+ splitUpdateTextRuns.push({
+ st: removeSt,
+ ed: removeEd,
+ ts: newTs,
+ sId,
+ });
+ splitUpdateTextRuns.push({
+ st: removeEd + 1,
+ ed: updateEd,
+ ts: newTs,
+ sId,
+ });
+
+ updateSt = removeEd + 1;
+ } else if (updateSt >= removeSt && updateSt <= removeEd) {
+ splitUpdateTextRuns.push({
+ st: updateSt,
+ ed: removeEd,
+ ts: newTs,
+ sId,
+ });
+ splitUpdateTextRuns.push({
+ st: removeEd + 1,
+ ed: updateEd,
+ ts: newTs,
+ sId,
+ });
+ updateSt = removeEd + 1;
+ } else if (updateEd >= removeSt && updateEd <= removeEd) {
+ splitUpdateTextRuns.push({
+ st: removeSt,
+ ed: updateEd,
+ ts: newTs,
+ sId,
+ });
+ }
+ }
+ newUpdateTextRun.push(...splitUpdateTextRuns);
+ splitUpdateTextRuns = [];
+ }
+ return newUpdateTextRun;
+}
+
+function updateParagraphs(body: IDocumentBody, updateBody: IDocumentBody, textLength: number, currentIndex: number, coverType: UpdateDocsAttributeType) {
+ const { paragraphs } = body;
- const endIndex = currentIndex + textLength - 1;
+ let { paragraphs: updateDataParagraphs } = updateBody;
- const removeTextRuns = [];
- for (let i = 0, len = textRuns.length; i < len; i++) {
- const textRun = textRuns[i];
- const { st, ed } = textRun;
+ if (paragraphs == null || updateDataParagraphs == null) {
+ return;
+ }
- if (startIndex <= st && endIndex >= ed) {
- removeTextRuns.push({
- ...textRun,
- st: st - currentIndex,
- ed: ed - currentIndex,
- });
+ const removeParagraphs = deleteParagraphs(body, textLength, currentIndex);
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateParagraphs: IParagraph[] = [];
+ for (let updateParagraph of updateDataParagraphs) {
+ let { startIndex: updateStartIndex, paragraphStyle: updateParagraphStyle, bullet: updateBullet } = updateParagraph;
+ let splitUpdateParagraphs: IParagraph[] = [];
+ for (let removeParagraph of removeParagraphs) {
+ const { startIndex: removeStartIndex, paragraphStyle: removeParagraphStyle, bullet: removeBullet } = removeParagraph;
+ let newParagraphStyle;
+ let newBullet;
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ newParagraphStyle = { ...removeParagraphStyle, ...updateParagraphStyle };
+ newBullet = { listId: '', nestingLevel: 0, textStyle: {}, ...removeBullet, ...updateBullet };
+ } else {
+ newParagraphStyle = { ...updateParagraphStyle, ...removeParagraphStyle };
+ newBullet = { listId: '', nestingLevel: 0, textStyle: {}, ...updateBullet, ...removeBullet };
+ }
- for (let updateTextRun of updateTextRuns) {
- const { st: updateSt, ed: updateEd } = updateTextRun;
+ if (updateStartIndex === removeStartIndex) {
+ splitUpdateParagraphs.push({
+ startIndex: updateStartIndex,
+ paragraphStyle: newParagraphStyle,
+ bullet: newBullet,
+ });
+ break;
+ }
}
+ newUpdateParagraphs.push(...splitUpdateParagraphs);
+ splitUpdateParagraphs = [];
+ }
- continue;
- } else if (st <= startIndex && ed >= endIndex) {
- const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);
+ updateBody.paragraphs = newUpdateParagraphs;
+ }
+ insertParagraphs(body, updateBody, textLength, currentIndex);
- if (segments.length > 2) {
- const seg1 = segments[0];
- const seg2 = segments[1];
- textRun.st = seg1[0];
- textRun.ed = seg1[1] + seg2[1] - seg2[0] + 1;
- } else {
- textRun.st = segments[0][0];
- textRun.ed = segments[0][1];
+ return removeParagraphs;
+}
+
+function updateSectionBreaks(body: IDocumentBody, updateBody: IDocumentBody, textLength: number, currentIndex: number, coverType: UpdateDocsAttributeType) {
+ const { sectionBreaks } = body;
+
+ let { sectionBreaks: updateDataSectionBreaks } = updateBody;
+
+ if (sectionBreaks == null || updateDataSectionBreaks == null) {
+ return;
+ }
+
+ const removeSectionBreaks = deleteSectionBreaks(body, textLength, currentIndex);
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateSectionBreaks: ISectionBreak[] = [];
+ for (let updateSectionBreak of updateDataSectionBreaks) {
+ let { startIndex: updateStartIndex } = updateSectionBreak;
+ let splitUpdateSectionBreaks: ISectionBreak[] = [];
+ for (let removeSectionBreak of removeSectionBreaks) {
+ const { startIndex: removeStartIndex } = removeSectionBreak;
+ if (updateStartIndex === removeStartIndex) {
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ splitUpdateSectionBreaks.push({
+ ...removeSectionBreak,
+ ...updateSectionBreak,
+ });
+ } else {
+ splitUpdateSectionBreaks.push({
+ ...updateSectionBreak,
+ ...removeSectionBreak,
+ });
+ }
+ break;
+ }
}
- } else if (startIndex >= st && startIndex <= ed) {
- removeTextRuns.push({
- ...textRun,
- st: startIndex - currentIndex,
- ed: ed - currentIndex,
- });
- textRun.ed = startIndex - 1;
- } else if (endIndex >= st && endIndex <= ed) {
- removeTextRuns.push({
- ...textRun,
- st: st - currentIndex,
- ed: endIndex - currentIndex,
- });
- textRun.st = endIndex + 1;
- } else if (st > endIndex) {
- textRun.st -= textLength;
- textRun.ed -= textLength;
+ newUpdateSectionBreaks.push(...splitUpdateSectionBreaks);
+ splitUpdateSectionBreaks = [];
}
+ updateBody.sectionBreaks = newUpdateSectionBreaks;
}
+ insertParagraphs(body, updateBody, textLength, currentIndex);
- return removeTextRuns;
+ return removeSectionBreaks;
+}
+
+function updateCustomBlocks(body: IDocumentBody, updateBody: IDocumentBody, textLength: number, currentIndex: number, coverType: UpdateDocsAttributeType) {
+ const { customBlocks } = body;
+
+ let { customBlocks: updateDataCustomBlocks } = updateBody;
+
+ if (customBlocks == null || updateDataCustomBlocks == null) {
+ return;
+ }
+
+ const removeCustomBlocks = deleteCustomBlocks(body, textLength, currentIndex);
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateCustomBlocks: ICustomBlock[] = [];
+ for (let updateCustomBlock of updateDataCustomBlocks) {
+ let { startIndex: updateStartIndex } = updateCustomBlock;
+ let splitUpdateCustomBlocks: ICustomBlock[] = [];
+ for (let removeCustomBlock of removeCustomBlocks) {
+ const { startIndex: removeStartIndex } = removeCustomBlock;
+ if (updateStartIndex === removeStartIndex) {
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ splitUpdateCustomBlocks.push({
+ ...removeCustomBlock,
+ ...updateCustomBlock,
+ });
+ } else {
+ splitUpdateCustomBlocks.push({
+ ...updateCustomBlock,
+ ...removeCustomBlock,
+ });
+ }
+ break;
+ }
+ }
+ newUpdateCustomBlocks.push(...splitUpdateCustomBlocks);
+ splitUpdateCustomBlocks = [];
+ }
+ updateBody.customBlocks = newUpdateCustomBlocks;
+ }
+ insertCustomBlocks(body, updateBody, textLength, currentIndex);
+
+ return removeCustomBlocks;
+}
+
+function updateTables(body: IDocumentBody, updateBody: IDocumentBody, textLength: number, currentIndex: number, coverType: UpdateDocsAttributeType) {
+ const { tables } = body;
+
+ let { tables: updateDataTables } = updateBody;
+
+ if (tables == null || updateDataTables == null) {
+ return;
+ }
+
+ const removeTables = deleteTables(body, textLength, currentIndex);
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateTables: ITable[] = [];
+ for (let updateTable of updateDataTables) {
+ let { startIndex: updateStartIndex, endIndex: updateEndIndex } = updateTable;
+ let splitUpdateTables: ITable[] = [];
+ for (let removeTable of removeTables) {
+ const { startIndex: removeStartIndex, endIndex: removeEndIndex } = removeTable;
+ if (removeStartIndex >= updateStartIndex && removeEndIndex <= updateEndIndex) {
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ splitUpdateTables.push({
+ ...removeTable,
+ ...updateTable,
+ });
+ } else {
+ splitUpdateTables.push({
+ ...updateTable,
+ ...removeTable,
+ });
+ }
+ break;
+ }
+ }
+ newUpdateTables.push(...splitUpdateTables);
+ splitUpdateTables = [];
+ }
+ updateBody.tables = newUpdateTables;
+ }
+ insertTables(body, updateBody, textLength, currentIndex);
+
+ return removeTables;
+}
+
+function updateCustomRanges(body: IDocumentBody, updateBody: IDocumentBody, textLength: number, currentIndex: number, coverType: UpdateDocsAttributeType) {
+ const { customRanges } = body;
+
+ let { tables: updateDataCustomRanges } = updateBody;
+
+ if (customRanges == null || updateDataCustomRanges == null) {
+ return;
+ }
+
+ const removeCustomRanges = deleteCustomRanges(body, textLength, currentIndex);
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateCustomRanges: ICustomRange[] = [];
+ for (let updateCustomRange of updateDataCustomRanges) {
+ let { startIndex: updateStartIndex, endIndex: updateEndIndex } = updateCustomRange;
+ let splitUpdateCustomRanges: ICustomRange[] = [];
+ for (let removeCustomRange of removeCustomRanges) {
+ const { startIndex: removeStartIndex, endIndex: removeEndIndex } = removeCustomRange;
+ if (removeStartIndex >= updateStartIndex && removeEndIndex <= updateEndIndex) {
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ splitUpdateCustomRanges.push({
+ ...removeCustomRange,
+ ...updateCustomRange,
+ });
+ } else {
+ splitUpdateCustomRanges.push({
+ ...updateCustomRange,
+ ...removeCustomRange,
+ });
+ }
+ break;
+ }
+ }
+ newUpdateCustomRanges.push(...splitUpdateCustomRanges);
+ splitUpdateCustomRanges = [];
+ }
+ updateBody.customRanges = newUpdateCustomRanges;
+ }
+ insertTables(body, updateBody, textLength, currentIndex);
+
+ return removeCustomRanges;
}
diff --git a/packages/core/src/Docs/Domain/DataStreamTreeNode.ts b/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
index 21d8fd0295..1763e67d7d 100644
--- a/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
+++ b/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
@@ -1,10 +1,6 @@
-import {
- deleteContent,
- horizontalLineSegmentsSubtraction,
- insertTextToContent,
-} from '../../Shared/Common';
+import { horizontalLineSegmentsSubtraction, deleteContent, insertTextToContent } from '../../Shared/DocTool';
import { Nullable } from '../../Shared/Types';
-import { DataStreamTreeNodeType } from './Types';
+import { DataStreamTreeNodeType, DataStreamTreeTokenType } from './Types';
export class DataStreamTreeNode {
children: DataStreamTreeNode[] = [];
@@ -15,6 +11,8 @@ export class DataStreamTreeNode {
endIndex: number;
+ isBullet: boolean = false;
+
blocks: number[] = [];
constructor(public nodeType: DataStreamTreeNodeType, public content?: string) {}
@@ -45,11 +43,7 @@ export class DataStreamTreeNode {
}
insertText(text: string, insertIndex: number) {
- this.content = insertTextToContent(
- this.content || '',
- insertIndex - this.startIndex + 1,
- text
- );
+ this.content = insertTextToContent(this.content || '', insertIndex - this.startIndex, text);
}
exclude(index: number) {
@@ -59,17 +53,19 @@ export class DataStreamTreeNode {
plus(len: number) {
this.startIndex += len;
this.endIndex += len;
+ this.addIndexForBlock(len);
+ }
+
+ selfPlus(len: number, index?: number) {
+ this.endIndex += len;
+ if (index == null) {
+ index = this.startIndex;
+ }
+ this.addIndexForBlock(len, index);
}
split(index: number) {
- const {
- children,
- parent,
- startIndex,
- endIndex,
- nodeType,
- content = '',
- } = this.getProps();
+ const { children, parent, startIndex, endIndex, nodeType, content = '' } = this.getProps();
if (this.exclude(index)) {
return;
@@ -78,31 +74,24 @@ export class DataStreamTreeNode {
const firstStartIndex = 0;
const firstEndIndex = index - startIndex;
- const lastStartIndex = index - startIndex + 1;
+ const lastStartIndex = firstEndIndex;
const lastEndIndex = endIndex;
- const firstNode = DataStreamTreeNode.create(
- nodeType,
-
- content.slice(firstStartIndex, firstEndIndex)
- );
+ const firstNode = DataStreamTreeNode.create(nodeType, content.slice(firstStartIndex, firstEndIndex));
firstNode.parent = parent;
- firstNode.setIndexRange(firstStartIndex, firstEndIndex);
+ firstNode.setIndexRange(firstStartIndex, firstEndIndex - 1);
- const lastNode = DataStreamTreeNode.create(
- nodeType,
-
- content.slice(lastStartIndex, lastEndIndex)
- );
+ const lastNodeContent = content.slice(lastStartIndex, lastEndIndex);
+ const lastNode = DataStreamTreeNode.create(nodeType, lastNodeContent);
lastNode.parent = parent;
- lastNode.setIndexRange(lastStartIndex, lastEndIndex);
+ lastNode.setIndexRange(lastStartIndex, lastStartIndex + lastNodeContent.length - 1);
const firstChildNodes: DataStreamTreeNode[] = [];
const lastChildNodes: DataStreamTreeNode[] = [];
- for (let node of children) {
+ for (const node of children) {
const { startIndex: childStartIndex } = node;
if (node.exclude(index)) {
if (index < childStartIndex) {
@@ -126,6 +115,10 @@ export class DataStreamTreeNode {
lastNode.children = lastChildNodes;
+ firstNode.resetBlocks();
+
+ lastNode.resetBlocks();
+
return {
firstNode,
lastNode,
@@ -133,7 +126,11 @@ export class DataStreamTreeNode {
}
getPositionInParent() {
- return this.parent?.children.indexOf(this) || -1;
+ const index = this.parent?.children.indexOf(this) as number;
+ if (index == null) {
+ return -1;
+ }
+ return index;
}
remove() {
@@ -146,30 +143,55 @@ export class DataStreamTreeNode {
}
minus(startIndex: number, endIndex: number) {
- const segments = horizontalLineSegmentsSubtraction(
- this.startIndex,
- this.endIndex,
- startIndex,
- endIndex
- );
-
- if (segments.length > 2) {
- const seg1 = segments[0];
- const seg2 = segments[1];
- this.startIndex = seg1[0];
- this.endIndex = seg1[1] + seg2[1] - seg2[0] + 1;
- } else {
- this.startIndex = segments[0][0];
- this.endIndex = segments[0][1];
+ const segments = horizontalLineSegmentsSubtraction(this.startIndex, this.endIndex, startIndex, endIndex);
+
+ if (segments.length === 0) {
+ return;
}
- this.content = deleteContent(this.content || '', startIndex, endIndex);
+ const originStartIndex = this.startIndex;
+
+ this.startIndex = segments[0];
+ this.endIndex = segments[1];
+
+ if (this.content != null) {
+ this.content = deleteContent(this.content || '', startIndex - originStartIndex, endIndex - originStartIndex + 1);
+ }
}
merge(node: DataStreamTreeNode) {
- const { endIndex, children } = node;
- this.endIndex = endIndex;
+ const { startIndex, endIndex, children } = node;
+ this.endIndex += endIndex - startIndex + 1;
this.children.push(...children);
+ this.content += node.content || '';
node.remove();
}
+
+ private addIndexForBlock(addLen: number, index: number = -Infinity) {
+ for (let i = 0, len = this.blocks.length; i < len; i++) {
+ const block = this.blocks[i];
+ if (block >= index) {
+ this.blocks[i] = block + addLen;
+ }
+ }
+ }
+
+ private resetBlocks() {
+ if (this.nodeType !== DataStreamTreeNodeType.PARAGRAPH) {
+ return;
+ }
+ if (this.content == null) {
+ return;
+ }
+ if (this.content.length === 0) {
+ return;
+ }
+ this.blocks = [];
+ for (let i = 0, len = this.content.length; i < len; i++) {
+ const char = this.content[i];
+ if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
+ this.blocks.push(this.startIndex + i);
+ }
+ }
+ }
}
diff --git a/packages/core/src/Docs/Domain/DocumentBodyModel.ts b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
index 6488042b29..b6586bf432 100644
--- a/packages/core/src/Docs/Domain/DocumentBodyModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
@@ -1,5 +1,7 @@
import { IDocumentBody, ITextRun } from '../../Types/Interfaces/IDocumentData';
+import { checkParagraphHasBullet } from '../../Shared/DocTool';
+
import { Nullable } from '../../Shared/Types';
import { DataStreamTreeNode } from './DataStreamTreeNode';
import { DataStreamTreeNodeType, DataStreamTreeTokenType } from './Types';
@@ -13,7 +15,7 @@ export class DocumentBodyModelSimple {
if (this.body == null) {
return;
}
- this.children = this.transformToTree(this.body.dataStream);
+ this.children = this._transformToTree(this.body.dataStream);
}
resetCache() {}
@@ -41,14 +43,20 @@ export class DocumentBodyModelSimple {
getCustomRange(index: number) {}
- private transformToTree(dataStream: string) {
+ selfPlus(len: number, index: number) {}
+
+ getPositionInParent() {
+ return 0;
+ }
+
+ private _transformToTree(dataStream: string) {
const dataStreamLen = dataStream.length;
let content = '';
- let sectionList: DataStreamTreeNode[] = [];
+ const sectionList: DataStreamTreeNode[] = [];
let nodeList: DataStreamTreeNode[] = [];
let currentBlocks: number[] = [];
-
+ let paragraphIndex = 0;
for (let i = 0; i < dataStreamLen; i++) {
const char = dataStream[i];
if (char === DataStreamTreeTokenType.PARAGRAPH) {
@@ -58,49 +66,34 @@ export class DocumentBodyModelSimple {
content
);
+ const isBullet = this._checkParagraphBullet(paragraphIndex++);
node.setIndexRange(i - content.length + 1, i);
node.addBlocks(currentBlocks);
+ node.isBullet = isBullet;
nodeList.push(node);
content = '';
currentBlocks = [];
} else if (char === DataStreamTreeTokenType.SECTION_BREAK) {
- const sectionTree = DataStreamTreeNode.create(
- DataStreamTreeNodeType.SECTION_BREAK
- );
- this.batchParent(sectionTree, nodeList);
- let lastNode = nodeList[nodeList.length - 1];
+ const sectionTree = DataStreamTreeNode.create(DataStreamTreeNodeType.SECTION_BREAK);
+ this._batchParent(sectionTree, nodeList);
+ const lastNode = nodeList[nodeList.length - 1];
if (lastNode && lastNode.content) {
lastNode.content += DataStreamTreeTokenType.SECTION_BREAK;
}
sectionList.push(sectionTree);
nodeList = [];
} else if (char === DataStreamTreeTokenType.TABLE_START) {
- nodeList.push(
- DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE)
- );
+ nodeList.push(DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE));
} else if (char === DataStreamTreeTokenType.TABLE_ROW_START) {
- nodeList.push(
- DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_ROW)
- );
+ nodeList.push(DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_ROW));
} else if (char === DataStreamTreeTokenType.TABLE_CELL_START) {
- nodeList.push(
- DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL)
- );
+ nodeList.push(DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL));
} else if (char === DataStreamTreeTokenType.TABLE_END) {
- this.processPreviousNodesUntil(
- nodeList,
- DataStreamTreeNodeType.TABLE
- );
+ this._processPreviousNodesUntil(nodeList, DataStreamTreeNodeType.TABLE);
} else if (char === DataStreamTreeTokenType.TABLE_ROW_END) {
- this.processPreviousNodesUntil(
- nodeList,
- DataStreamTreeNodeType.TABLE_ROW
- );
+ this._processPreviousNodesUntil(nodeList, DataStreamTreeNodeType.TABLE_ROW);
} else if (char === DataStreamTreeTokenType.TABLE_CELL_END) {
- this.processPreviousNodesUntil(
- nodeList,
- DataStreamTreeNodeType.TABLE_CELL
- );
+ this._processPreviousNodesUntil(nodeList, DataStreamTreeNodeType.TABLE_CELL);
} else if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
currentBlocks.push(i);
content += char;
@@ -112,10 +105,7 @@ export class DocumentBodyModelSimple {
return sectionList;
}
- private processPreviousNodesUntil(
- nodeList: DataStreamTreeNode[],
- untilNodeType: DataStreamTreeNodeType
- ) {
+ private _processPreviousNodesUntil(nodeList: DataStreamTreeNode[], untilNodeType: DataStreamTreeNodeType) {
const nodeCollection: DataStreamTreeNode[] = [];
let node = nodeList.pop();
while (node) {
@@ -129,13 +119,12 @@ export class DocumentBodyModelSimple {
}
const recentTree = nodeList[nodeList.length - 1];
- this.batchParent(recentTree, nodeCollection, DataStreamTreeNodeType.TABLE);
+ this._batchParent(recentTree, nodeCollection, DataStreamTreeNodeType.TABLE);
if (untilNodeType === DataStreamTreeNodeType.TABLE_CELL) {
const firstNode = nodeCollection[0];
const lastNode = nodeCollection[nodeCollection.length];
- firstNode.content =
- DataStreamTreeTokenType.TABLE_CELL_START + firstNode.content || '';
+ firstNode.content = DataStreamTreeTokenType.TABLE_CELL_START + firstNode.content || '';
firstNode.startIndex -= 1;
lastNode.content += DataStreamTreeTokenType.TABLE_CELL_END;
lastNode.endIndex += 1;
@@ -143,8 +132,7 @@ export class DocumentBodyModelSimple {
const firstNode = nodeCollection[0].children[0];
let lastNode = nodeCollection[nodeCollection.length];
lastNode = lastNode.children[lastNode.children.length - 1];
- firstNode.content =
- DataStreamTreeTokenType.TABLE_ROW_START + firstNode.content || '';
+ firstNode.content = DataStreamTreeTokenType.TABLE_ROW_START + firstNode.content || '';
firstNode.startIndex -= 1;
lastNode.content += DataStreamTreeTokenType.TABLE_ROW_END;
lastNode.endIndex += 1;
@@ -153,31 +141,31 @@ export class DocumentBodyModelSimple {
let lastNode = nodeCollection[nodeCollection.length];
lastNode = lastNode.children[lastNode.children.length - 1];
lastNode = lastNode.children[lastNode.children.length - 1];
- firstNode.content =
- DataStreamTreeTokenType.TABLE_START + firstNode.content || '';
+ firstNode.content = DataStreamTreeTokenType.TABLE_START + firstNode.content || '';
firstNode.startIndex -= 1;
lastNode.content += DataStreamTreeTokenType.TABLE_END;
lastNode.endIndex += 1;
}
}
- private batchParent(
- parent: DataStreamTreeNode,
- children: DataStreamTreeNode[],
- nodeType = DataStreamTreeNodeType.SECTION_BREAK
- ) {
- for (let child of children) {
+ private _batchParent(parent: DataStreamTreeNode, children: DataStreamTreeNode[], nodeType = DataStreamTreeNodeType.SECTION_BREAK) {
+ for (const child of children) {
child.parent = parent;
parent.children.push(child);
}
- const startOffset =
- nodeType === DataStreamTreeNodeType.SECTION_BREAK ? 0 : 1;
+ const startOffset = nodeType === DataStreamTreeNodeType.SECTION_BREAK ? 0 : 1;
- parent.setIndexRange(
- children[0].startIndex - startOffset,
- children[children.length - 1].endIndex + 1
- );
+ parent.setIndexRange(children[0].startIndex - startOffset, children[children.length - 1].endIndex + 1);
+ }
+
+ private _checkParagraphBullet(index: number) {
+ const { paragraphs } = this.body;
+ if (paragraphs == null) {
+ return false;
+ }
+
+ return checkParagraphHasBullet(paragraphs[index]);
}
}
@@ -206,13 +194,13 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return;
}
- if (dataStream[dataStream.length - 1] === '\n') {
+ if (dataStream[dataStreamLen - 1] === DataStreamTreeTokenType.SECTION_BREAK) {
const insertBodyModel = new DocumentBodyModelSimple(insertBody);
dataStreamLen -= 1; // sectionBreak can not be inserted
const insertNodes = insertBodyModel.children;
- for (let node of insertNodes) {
+ for (const node of insertNodes) {
this.foreachDown(node, (newNode) => {
newNode.plus(insertIndex);
});
@@ -224,22 +212,16 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return;
}
- const { firstNode: insertedFirstNode, lastNode: insertedLastNode } =
- insertedNodeSplit;
+ const { firstNode: insertedFirstNode, lastNode: insertedLastNode } = insertedNodeSplit;
- insertedNode.parent?.children.splice(
- insertedNode.getPositionInParent(),
- 1,
- insertedFirstNode,
- ...insertNodes,
- insertedLastNode
- );
+ insertedNode.parent?.children.splice(insertedNode.getPositionInParent(), 1, insertedFirstNode, ...insertNodes, insertedLastNode);
this.foreachTop(insertedNode.parent, (currentNode) => {
- currentNode.endIndex += dataStreamLen;
+ // currentNode.endIndex += dataStreamLen;
+ currentNode.selfPlus(dataStreamLen, currentNode.getPositionInParent());
const children = currentNode.children;
let isStartFix = false;
- for (let node of children) {
+ for (const node of children) {
if (node === insertedLastNode) {
isStartFix = true;
}
@@ -253,17 +235,21 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
});
}
});
+ } else if (dataStreamLen === 1 && dataStream[dataStreamLen - 1] === DataStreamTreeTokenType.PARAGRAPH) {
+ this._insertParagraph(insertedNode, insertIndex);
} else {
insertedNode.insertText(dataStream, insertIndex);
- insertedNode.endIndex += dataStreamLen;
+ // insertedNode.endIndex += dataStreamLen;
+ insertedNode.selfPlus(dataStreamLen, insertIndex);
this.foreachTop(insertedNode.parent, (currentNode) => {
- currentNode.endIndex += dataStreamLen;
+ // currentNode.endIndex += dataStreamLen;
+ currentNode.selfPlus(dataStreamLen, currentNode.getPositionInParent());
const children = currentNode.children;
let isStartFix = false;
- for (let node of children) {
- if (node === currentNode) {
+ for (const node of children) {
+ if (node.startIndex > insertIndex) {
isStartFix = true;
}
@@ -284,42 +270,79 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
this.deleteTree(nodes, currentIndex, textLength);
}
- deleteTree(
- nodes: DataStreamTreeNode[],
- currentIndex: number,
- textLength: number
- ) {
+ deleteTree(nodes: DataStreamTreeNode[], currentIndex: number, textLength: number) {
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
let mergeNode: Nullable<DataStreamTreeNode> = null;
- for (let node of nodes) {
+ let nodeCount = nodes.length;
+ let i = 0;
+ while (i < nodeCount) {
+ const node = nodes[i];
const { startIndex: st, endIndex: ed, children } = node;
this.deleteTree(children, currentIndex, textLength);
- if (startIndex <= st && endIndex >= ed) {
+ if (startIndex === endIndex && endIndex === ed) {
+ // The cursor is at the dividing point between two paragraphs,
+ // and it is necessary to determine whether to delete elements
+ // such as paragraphs, chapters, and tables
+ if (node.nodeType === DataStreamTreeNodeType.PARAGRAPH) {
+ const nextNode = this._getNextNode(node);
+ if (nextNode == null) {
+ i++;
+ continue;
+ }
+
+ if (nextNode.isBullet) {
+ i++;
+ continue;
+ } else {
+ node.minus(startIndex, endIndex);
+ node.merge(nextNode);
+ nodeCount--;
+ }
+ }
+ // else if (node.nodeType === DataStreamTreeNodeType.SECTION_BREAK) {
+ // } else if (node.nodeType === DataStreamTreeNodeType.TABLE) {
+ // } else if (node.nodeType === DataStreamTreeNodeType.TABLE_ROW) {
+ // } else if (node.nodeType === DataStreamTreeNodeType.TABLE_CELL) {
+ // }
+ } else if (startIndex <= st && endIndex >= ed) {
+ // The first case. The selection range of the text box
+ // is larger than the current node
node.remove();
+ nodeCount--;
+ continue;
} else if (st <= startIndex && ed >= endIndex) {
- node.minus(startIndex, ed);
- } else if (startIndex >= st && startIndex <= ed) {
- node.minus(startIndex, ed);
- mergeNode = node;
- } else if (endIndex >= st && endIndex <= ed) {
+ // The second case. The selection range of
+ // the text box is smaller than the current node
+ node.minus(startIndex, endIndex);
+ } else if (endIndex > st && endIndex < ed) {
+ // The third case.
+ // The text selection left contains the current node
node.minus(st, endIndex);
if (mergeNode) {
mergeNode.merge(node);
+ mergeNode = null;
}
+ nodeCount--;
+ continue;
+ } else if (startIndex > st && startIndex < ed) {
+ // The fourth case.
+ // The text selection right contains the current node
+ node.minus(startIndex, ed);
+ mergeNode = node;
} else if (st > endIndex) {
+ // The current node is not on the right side of
+ // the selection area and needs to be moved as a whole
node.plus(-textLength);
}
+ i++;
}
}
- getParagraphByTree(
- nodes: DataStreamTreeNode[],
- insertIndex: number
- ): Nullable<DataStreamTreeNode> {
- for (let node of nodes) {
+ getParagraphByTree(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {
+ for (const node of nodes) {
const { startIndex, endIndex, children } = node;
if (node.exclude(insertIndex)) {
continue;
@@ -332,15 +355,14 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return null;
}
- foreachTop(
- node: Nullable<DataStreamTreeNode>,
- func: (node: DataStreamTreeNode) => void
- ) {
+ foreachTop(node: Nullable<DataStreamTreeNode>, func: (node: DataStreamTreeNode | DocumentBodyModelOrSimple) => void) {
let parent: Nullable<DataStreamTreeNode> = node;
while (parent) {
func(parent);
parent = parent.parent;
}
+
+ func(this);
}
foreachDown(node: DataStreamTreeNode, func: (node: DataStreamTreeNode) => void) {
@@ -406,11 +428,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
const trRange: ITextRun[] = [];
- for (
- let i = this.textRunCurrentIndex, textRunsLen = textRuns.length;
- i < textRunsLen;
- i++
- ) {
+ for (let i = this.textRunCurrentIndex, textRunsLen = textRuns.length; i < textRunsLen; i++) {
const textRun = textRuns[i];
if (textRun.st > endIndex) {
this.textRunCurrentIndex = i;
@@ -465,11 +483,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
}
}
- for (
- let i = this.textRunCurrentIndex, textRunsLen = textRuns.length;
- i < textRunsLen;
- i++
- ) {
+ for (let i = this.textRunCurrentIndex, textRunsLen = textRuns.length; i < textRunsLen; i++) {
const textRun = textRuns[i];
if (index >= textRun.st && index <= textRun.ed) {
this.textRunCurrentIndex = i;
@@ -513,11 +527,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
if (customRanges == null) {
return;
}
- for (
- let i = 0, customRangesLen = customRanges.length;
- i < customRangesLen;
- i++
- ) {
+ for (let i = 0, customRangesLen = customRanges.length; i < customRangesLen; i++) {
const customRange = customRanges[i];
if (index >= customRange.startIndex && index <= customRange.endIndex) {
return customRange;
@@ -525,6 +535,58 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
}
}
+ private _getNextNode(node: DataStreamTreeNode): DataStreamTreeNode {
+ const currentIndex = node.getPositionInParent();
+ const children = node.parent?.children;
+ return children?.[currentIndex + 1] as DataStreamTreeNode;
+ }
+
+ private _insertParagraph(insertedNode: DataStreamTreeNode, insertIndex = 0) {
+ const insertStartIndex = insertedNode.startIndex;
+
+ const insertEndIndex = insertedNode.endIndex;
+
+ const insertedNodeSplit = insertedNode.split(insertIndex);
+
+ if (insertedNodeSplit == null) {
+ return;
+ }
+
+ const { firstNode: insertedFirstNode, lastNode: insertedLastNode } = insertedNodeSplit;
+
+ insertedFirstNode.content += DataStreamTreeTokenType.PARAGRAPH;
+
+ insertedFirstNode.selfPlus(1);
+
+ insertedFirstNode.plus(insertStartIndex);
+
+ this.foreachDown(insertedLastNode, (newNode) => {
+ newNode.plus(insertStartIndex + 1);
+ });
+
+ insertedNode.parent?.children.splice(insertedNode.getPositionInParent(), 1, insertedFirstNode, insertedLastNode);
+
+ this.foreachTop(insertedNode.parent, (currentNode) => {
+ // currentNode.endIndex += dataStreamLen;
+ currentNode.selfPlus(1, currentNode.getPositionInParent());
+ const children = currentNode.children;
+ let isStartFix = false;
+ for (const node of children) {
+ if (node.startIndex >= insertEndIndex + 1) {
+ isStartFix = true;
+ }
+
+ if (!isStartFix) {
+ continue;
+ }
+
+ this.foreachDown(node, (newNode) => {
+ newNode.plus(1);
+ });
+ }
+ });
+ }
+
private move() {}
private split() {}
diff --git a/packages/core/src/Docs/Domain/DocumentModel.ts b/packages/core/src/Docs/Domain/DocumentModel.ts
index 1eaf610385..49f0d3d552 100644
--- a/packages/core/src/Docs/Domain/DocumentModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentModel.ts
@@ -1,11 +1,13 @@
import { Inject } from '@wendellhu/redi';
import { Command, CommandManager } from '../../Command';
-import { CommonParameterAttribute, IDocumentBody, IDocumentData } from '../../Types/Interfaces/IDocumentData';
+import { IDocumentBody, IDocumentData } from '../../Types/Interfaces/IDocumentData';
import { ITextSelectionRange } from '../../Types/Interfaces/ISelectionData';
import { DOC_ACTION_NAMES } from '../../Types/Const/DOC_ACTION_NAMES';
import { Tools, getTextIndexByCursor } from '../../Shared';
import { DocumentBodyModel } from './DocumentBodyModel';
import { DEFAULT_DOC } from '../../Types/Const';
+import { UpdateDocsAttributeType } from '../../Shared/CommandEnum';
+import { DocActionType } from '../Action/ActionDataInterface';
interface IDrawingUpdateConfig {
left: number;
@@ -132,7 +134,7 @@ export class DocumentModel extends DocumentModelSimple {
if (isCollapse) {
actionList.push({
actionName: DOC_ACTION_NAMES.RETAIN_ACTION_NAME,
- len: textStart,
+ len: textStart + 1,
segmentId,
});
} else {
@@ -170,7 +172,7 @@ export class DocumentModel extends DocumentModelSimple {
return this;
}
- update(attribute: CommonParameterAttribute, range: ITextSelectionRange, segmentId?: string) {
+ update(body: IDocumentBody, range: ITextSelectionRange, coverType = UpdateDocsAttributeType.COVER, segmentId?: string) {
const { cursorStart, cursorEnd, isEndBack, isStartBack } = range;
const actionList = [];
@@ -187,7 +189,8 @@ export class DocumentModel extends DocumentModelSimple {
actionList.push({
actionName: DOC_ACTION_NAMES.RETAIN_ACTION_NAME,
len: textEnd - textStart + 1,
- attribute,
+ coverType,
+ body,
segmentId,
});
@@ -206,16 +209,18 @@ export class DocumentModel extends DocumentModelSimple {
actionList.push({
actionName: DOC_ACTION_NAMES.RETAIN_ACTION_NAME,
- len: start,
+ len: start + 1,
segmentId,
});
- actionList.push({
- actionName: DOC_ACTION_NAMES.DELETE_ACTION_NAME,
- len: oldTextLen,
- line: 0,
- segmentId,
- });
+ if (oldTextLen > 0) {
+ actionList.push({
+ actionName: DOC_ACTION_NAMES.DELETE_ACTION_NAME,
+ len: oldTextLen,
+ line: 0,
+ segmentId,
+ });
+ }
actionList.push({
actionName: DOC_ACTION_NAMES.INSERT_ACTION_NAME,
@@ -259,10 +264,10 @@ export class DocumentModel extends DocumentModelSimple {
}
private _getDeleteAction(range: ITextSelectionRange, segmentId?: string) {
- const { cursorStart, cursorEnd, isEndBack, isStartBack } = range;
- const actionList = [];
+ const { cursorStart, cursorEnd, isEndBack, isStartBack, isCollapse } = range;
+ const actionList: DocActionType[] = [];
- const textStart = getTextIndexByCursor(cursorStart, isStartBack);
+ const textStart = getTextIndexByCursor(cursorStart, isStartBack) + (isCollapse ? 0 : 1);
const textEnd = getTextIndexByCursor(cursorEnd, isEndBack);
diff --git a/packages/core/src/Shared/Common.ts b/packages/core/src/Shared/Common.ts
index 6804f6c081..d2dcaef380 100644
--- a/packages/core/src/Shared/Common.ts
+++ b/packages/core/src/Shared/Common.ts
@@ -1,30 +1,18 @@
import { Tools } from './Tools';
-import { Nullable } from '.';
-import {
- ICellInfo,
- ISelection,
- ICellData,
- IColorStyle,
- IDocumentData,
- IStyleData,
-} from '../Types/Interfaces';
+import { Nullable } from './Types';
+import { IDocumentData } from '../Types/Interfaces/IDocumentData';
+import { ICellData } from '../Types/Interfaces/ICellData';
+import { IColorStyle, IStyleData } from '../Types/Interfaces/IStyleData';
+import { ICellInfo, ISelection } from '../Types/Interfaces/ISelectionData';
import { ColorBuilder } from '../Sheets/Domain';
-import {
- BaselineOffset,
- TextDirection,
- HorizontalAlign,
- VerticalAlign,
- WrapStrategy,
- BorderStyleTypes,
-} from '../Types/Enum';
+import { BaselineOffset, TextDirection, HorizontalAlign, VerticalAlign, WrapStrategy, BorderStyleTypes } from '../Types/Enum';
-export function makeCellToSelection(
- cellInfo: Nullable<ICellInfo>
-): Nullable<ISelection> {
+export function makeCellToSelection(cellInfo: Nullable<ICellInfo>): Nullable<ISelection> {
if (!cellInfo) {
return;
}
- let { row, column, startY, endY, startX, endX, isMerged, mergeInfo } = cellInfo;
+ const { row, column, isMerged, mergeInfo } = cellInfo;
+ let { startY, endY, startX, endX } = cellInfo;
let startRow = row;
let startColumn = column;
let endRow = row;
@@ -80,11 +68,7 @@ export function getColorStyle(color: Nullable<IColorStyle>): Nullable<string> {
return color.rgb;
}
if (color.th) {
- return new ColorBuilder()
- .setThemeColor(color.th)
- .asThemeColor()
- .asRgbColor()
- .getCssString();
+ return new ColorBuilder().setThemeColor(color.th).asThemeColor().asRgbColor().getCssString();
}
}
return null;
@@ -159,6 +143,7 @@ export function handleJsonToDom(p: IDocumentData): string {
* @param style
* @returns
*/
+// eslint-disable-next-line max-lines-per-function
export function handleStyleToString(style: IStyleData, isCell: boolean = false) {
let str = '';
const styleMap = new Map([
@@ -213,17 +198,12 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
if (style.ul?.s) {
// If there are existing lines, add new lines
if (str.indexOf('text-decoration-line') > -1) {
- str = str.replace(
- /(?<=text-decoration-line:.*)\b(?=;)/g,
- ' underline'
- );
+ str = str.replace(/(?<=text-decoration-line:.*)\b(?=;)/g, ' underline');
} else {
str += `text-decoration-line: underline; `;
}
if (style.ul.cl && str.indexOf('text-decoration-color') === -1) {
- str += `text-decoration-color: ${getColorStyle(
- style.ul.cl
- )}; `;
+ str += `text-decoration-color: ${getColorStyle(style.ul.cl)}; `;
}
if (style.ul.t && str.indexOf('text-decoration-style') === -1) {
str += `text-decoration-style: ${style.ul.t} `;
@@ -236,17 +216,12 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
() => {
if (style.st?.s) {
if (str.indexOf('text-decoration-line') > -1) {
- str = str.replace(
- /(?<=text-decoration-line:.*)\b(?=;)/g,
- ' line-through'
- );
+ str = str.replace(/(?<=text-decoration-line:.*)\b(?=;)/g, ' line-through');
} else {
str += `text-decoration-line: line-through; `;
}
if (style.st.cl && str.indexOf('text-decoration-color') === -1) {
- str += `text-decoration-color: ${getColorStyle(
- style.st.cl
- )}; `;
+ str += `text-decoration-color: ${getColorStyle(style.st.cl)}; `;
}
if (style.st.t && str.indexOf('text-decoration-style') === -1) {
str += `text-decoration-style: ${style.st.t} `;
@@ -259,17 +234,12 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
() => {
if (style.ol?.s) {
if (str.indexOf('text-decoration-line') > -1) {
- str = str.replace(
- /(?<=text-decoration-line:.*)\b(?=;)/g,
- ' overline'
- );
+ str = str.replace(/(?<=text-decoration-line:.*)\b(?=;)/g, ' overline');
} else {
str += `text-decoration-line: overline; `;
}
if (style.ol.cl && str.indexOf('text-decoration-color') === -1) {
- str += `text-decoration-color: ${getColorStyle(
- style.ol.cl
- )}; `;
+ str += `text-decoration-color: ${getColorStyle(style.ol.cl)}; `;
}
if (style.ol.t && str.indexOf('text-decoration-style') === -1) {
str += `text-decoration-style: ${style.ol.t} `;
@@ -287,24 +257,16 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
'bd',
() => {
if (style.bd?.b) {
- str += `border-bottom: ${getBorderStyle(style.bd?.b.s)} ${
- getColorStyle(style.bd.b.cl) ?? ''
- }; `;
+ str += `border-bottom: ${getBorderStyle(style.bd?.b.s)} ${getColorStyle(style.bd.b.cl) ?? ''}; `;
}
if (style.bd?.t) {
- str += `border-top: ${getBorderStyle(style.bd?.t.s)} ${
- getColorStyle(style.bd.t.cl) ?? ''
- }; `;
+ str += `border-top: ${getBorderStyle(style.bd?.t.s)} ${getColorStyle(style.bd.t.cl) ?? ''}; `;
}
if (style.bd?.r) {
- str += `border-right: ${getBorderStyle(style.bd?.r.s)} ${
- getColorStyle(style.bd.r.cl) ?? ''
- }; `;
+ str += `border-right: ${getBorderStyle(style.bd?.r.s)} ${getColorStyle(style.bd.r.cl) ?? ''}; `;
}
if (style.bd?.l) {
- str += `border-left: ${getBorderStyle(style.bd?.l.s)} ${
- getColorStyle(style.bd.l.cl) ?? ''
- }; `;
+ str += `border-left: ${getBorderStyle(style.bd?.l.s)} ${getColorStyle(style.bd.l.cl) ?? ''}; `;
}
},
],
@@ -341,9 +303,7 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
[
'tr',
() => {
- str += `data-rotate: (${style.tr?.a}deg${
- style.tr?.v ? ` ,${style.tr?.v}` : ''
- });`;
+ str += `data-rotate: (${style.tr?.a}deg${style.tr?.v ? ` ,${style.tr?.v}` : ''});`;
},
],
[
@@ -402,10 +362,10 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
// l = `${pxToPt(style.pd?.l || 0)}pt`;
// r = `${pxToPt(style.pd?.r || 0)}pt`;
// } else {
- let b = `${style.pd?.b}pt`;
- let t = `${style.pd?.t}pt`;
- let l = `${style.pd?.l}pt`;
- let r = `${style.pd?.r}pt`;
+ const b = `${style.pd?.b}pt`;
+ const t = `${style.pd?.t}pt`;
+ const l = `${style.pd?.l}pt`;
+ const r = `${style.pd?.r}pt`;
// }
if (style.pd?.b) {
str += `padding-bottom: ${b}; `;
@@ -423,7 +383,7 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
],
]);
const cellSkip = ['bd', 'tr', 'tb'];
- for (let k in style) {
+ for (const k in style) {
if (isCell && cellSkip.includes(k)) continue; // Cell styles to skip when entering edit mode
styleMap.get(k)?.();
}
@@ -495,22 +455,6 @@ export function getTextIndexByCursor(index: number, isBack: boolean = false) {
return isBack ? index - 1 : index;
}
-export function insertTextToContent(content: string, start: number, text: string) {
- return content.slice(0, start) + text + content.slice(start);
-}
-
-export function deleteContent(content: string, start: number, end: number) {
- if (start > end) {
- return content;
- }
-
- if (start === end) {
- start -= 1;
- }
-
- return content.slice(0, start) + content.slice(end);
-}
-
export function getDocsUpdateBody(model: IDocumentData, segmentId?: string) {
let body = model.body;
@@ -525,40 +469,3 @@ export function getDocsUpdateBody(model: IDocumentData, segmentId?: string) {
return body;
}
-
-export function horizontalLineSegmentsSubtraction(
- A1: number,
- A2: number,
- B1: number,
- B2: number
-) {
- // 确保A1 < A2, B1 < B2
- if (A1 > A2) {
- [A1, A2] = [A2, A1];
- }
- if (B1 > B2) {
- [B1, B2] = [B2, B1];
- }
-
- // 检查线段是否重叠
- if (A2 < B1 || B2 < A1) {
- return [[A1, A2]]; // 无重叠,返回原线段A
- }
-
- const overlapStart = Math.max(A1, B1);
- const overlapEnd = Math.min(A2, B2);
-
- const result = [];
-
- // 添加重叠之前的线段
- if (overlapStart > A1) {
- result.push([A1, overlapStart]);
- }
-
- // 添加重叠之后的线段
- if (overlapEnd < A2) {
- result.push([overlapEnd, A2]);
- }
-
- return result;
-}
diff --git a/packages/core/src/Shared/DocTool.ts b/packages/core/src/Shared/DocTool.ts
new file mode 100644
index 0000000000..819fcebc57
--- /dev/null
+++ b/packages/core/src/Shared/DocTool.ts
@@ -0,0 +1,76 @@
+import { IParagraph } from '../Types/Interfaces/IDocumentData';
+
+export function horizontalLineSegmentsSubtraction(A1: number, A2: number, B1: number, B2: number) {
+ // 确保A1 < A2, B1 < B2
+ if (A1 > A2) {
+ [A1, A2] = [A2, A1];
+ }
+ if (B1 > B2) {
+ [B1, B2] = [B2, B1];
+ }
+
+ if (A2 < B1 || B2 < A1) {
+ return [A1, A2]; // 无重叠,返回原线段A
+ }
+
+ if (B1 < A1) {
+ B1 = A1;
+ }
+
+ if (B2 > A2) {
+ B2 = A2;
+ }
+
+ const subLength = B2 - B1 + 1;
+ let result: number[] = [];
+ if (A1 === B1) {
+ // Subtract the start segment
+ result = [B2 + 1 - subLength, A2 - subLength];
+ } else if (A2 === B2) {
+ // Subtract the end segment
+ result = [A1, B1 - 1];
+ } else {
+ // Subtract the middle segment
+ result = [A1, A2 - subLength];
+ }
+
+ return result;
+}
+
+export function checkParagraphHasBullet(paragraph: IParagraph) {
+ if (paragraph == null) {
+ return false;
+ }
+ const bullet = paragraph.bullet;
+
+ return bullet?.listId != null;
+}
+
+export function checkParagraphHasIndent(paragraph: IParagraph) {
+ if (paragraph == null) {
+ return false;
+ }
+ const paragraphStyle = paragraph.paragraphStyle;
+
+ if (paragraphStyle?.indentStart == null || paragraphStyle?.indentStart === 0) {
+ return false;
+ }
+
+ return true;
+}
+
+export function insertTextToContent(content: string, start: number, text: string) {
+ return content.slice(0, start) + text + content.slice(start);
+}
+
+export function deleteContent(content: string, start: number, end: number) {
+ if (start > end) {
+ return content;
+ }
+
+ // if (start === end) {
+ // start -= 1;
+ // }
+
+ return content.slice(0, start) + content.slice(end);
+}
diff --git a/packages/core/src/Shared/index.ts b/packages/core/src/Shared/index.ts
index 95b6dfa5f3..17b46b707a 100644
--- a/packages/core/src/Shared/index.ts
+++ b/packages/core/src/Shared/index.ts
@@ -27,4 +27,5 @@ export * from './Types';
export * from './TypeStore';
export * from './HashAlgorithm';
export * from './Compare';
+export * from './CommandEnum';
// @endindex
diff --git a/packages/sheets-plugin-formula/src/Controller/keyCode.ts b/packages/sheets-plugin-formula/src/Controller/keyCode.ts
index cd3831b9e5..3ac8fe797d 100644
--- a/packages/sheets-plugin-formula/src/Controller/keyCode.ts
+++ b/packages/sheets-plugin-formula/src/Controller/keyCode.ts
@@ -47,6 +47,13 @@ export enum KeyCode {
* https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/
*/
export enum KeyboardKeyType {
- backspace = 'Backspace',
- delete = 'Delete',
+ 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/Controller/RightMenuUIController.ts b/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
index 399210f8be..3f608922c3 100644
--- a/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
@@ -1,5 +1,6 @@
import { IMouseEvent, IPointerEvent } from '@univerjs/base-render';
-import { BaseMenuItem, BaseSelectChildrenProps, ComponentChildren, ComponentManager, CustomLabel, ICustomLabelType, IMenuService, MenuPosition } from '@univerjs/base-ui';
+import { BaseMenuItem, ComponentManager, ICustomLabelType, IMenuService, MenuPosition } from '@univerjs/base-ui';
+import { ComponentChildren } from 'preact';
import { Disposable, ICurrentUniverService, ObserverManager, Tools, UIObserver } from '@univerjs/core';
import { Inject, Injector, SkipSelf } from '@wendellhu/redi';
import { CanvasView } from '@univerjs/base-sheets';
@@ -318,4 +319,4 @@ export class RightMenuUIController extends Disposable {
this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
});
}
-}
\ No newline at end of file
+}
diff --git a/packages/ui-plugin-sheets/src/Controller/menu.ts b/packages/ui-plugin-sheets/src/Controller/menu.ts
index 2fb3fea045..c6f4f70c92 100644
--- a/packages/ui-plugin-sheets/src/Controller/menu.ts
+++ b/packages/ui-plugin-sheets/src/Controller/menu.ts
@@ -345,4 +345,4 @@ export function DeleteRangeMoveUpMenuItemFactory(accessor: IAccessor): IMenuItem
title: 'rightClick.moveUp',
parentId: `${DeleteRangeCommand.id}.parent`,
};
-}
\ No newline at end of file
+}
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
index 52b754e31a..6f9e9a90ae 100644
--- a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
+++ b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
@@ -38,9 +38,9 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
});
}
- setMenuListNeo = (menuItems: IDisplayMenuItem[]) => {
+ setMenuListNeo = (menuItems: IMenuItem[]) => {
this.setState({
- menuItems:this.buildMenuTree(menuItems),
+ menuItems: this.buildMenuTree(menuItems),
});
};
diff --git a/packages/ui-plugin-slides/src/SlideUIPlugin.ts b/packages/ui-plugin-slides/src/SlideUIPlugin.ts
index dc9e505618..e22de9c1b9 100644
--- a/packages/ui-plugin-slides/src/SlideUIPlugin.ts
+++ b/packages/ui-plugin-slides/src/SlideUIPlugin.ts
@@ -2,6 +2,7 @@ import { Plugin, Tools, LocaleService, PluginType } from '@univerjs/core';
import { RegisterManager, ComponentManager, getRefElement, DragManager } from '@univerjs/base-ui';
import { IRenderingEngine } from '@univerjs/base-render';
import { Inject, Injector } from '@wendellhu/redi';
+import { CanvasView } from '@univerjs/base-slides';
import { zh, en } from './Locale';
import { SLIDE_UI_PLUGIN_NAME } from './Basics/Const/PLUGIN_NAME';
import { AppUIController } from './Controller/AppUIController';
@@ -18,13 +19,14 @@ export class SlideUIPlugin extends Plugin<SlideUIPluginObserve> {
private _config: ISlideUIPluginConfig;
private _dragManager: DragManager;
-
+
private _componentManager: ComponentManager;
constructor(
config: Partial<ISlideUIPluginConfig> = {},
@Inject(Injector) override readonly _injector: Injector,
- @Inject(LocaleService) private readonly _localeService: LocaleService
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @Inject(CanvasView) private readonly _canvasView: CanvasView
) {
super(SLIDE_UI_PLUGIN_NAME);
this._config = Tools.deepMerge({}, DefaultSlideUIConfig, config);
@@ -66,16 +68,17 @@ export class SlideUIPlugin extends Plugin<SlideUIPluginObserve> {
// should be clear
setTimeout(() => {
engine.resize();
+ this._canvasView.scrollToCenter();
}, 0);
}
- initUI() { }
+ initUI() {}
override onMounted(): void {
this.initialize();
}
- override onDestroy(): void { }
+ override onDestroy(): void {}
getAppUIController() {
return this._appUIController;