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.

refactor(doc): refactor doc input (#267)

Univer94020e13a451
diff --git a/packages/base-docs/src/Basics/component-tools.ts b/packages/base-docs/src/Basics/component-tools.ts
new file mode 100644
index 0000000000..65b7503788
--- /dev/null
+++ b/packages/base-docs/src/Basics/component-tools.ts
@@ -0,0 +1,33 @@
+import { Documents, Engine, IRenderManagerService, Scene } from '@univerjs/base-render';
+import { ICurrentUniverService, Nullable } from '@univerjs/core';
+
+export interface IDocObjectParam {
+ document: Documents;
+ scene: Scene;
+ engine: Engine;
+}
+
+export function getDocObject(
+ currentUniverService: ICurrentUniverService,
+ renderManagerService: IRenderManagerService
+): Nullable<IDocObjectParam> {
+ const documentModel = currentUniverService.getCurrentUniverDocInstance();
+
+ const unitId = documentModel.getUnitId();
+
+ const currentRender = renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { components, mainComponent, scene, engine } = currentRender;
+
+ const document = mainComponent as Documents;
+
+ return {
+ document,
+ scene,
+ engine,
+ };
+}
diff --git a/packages/base-docs/src/Controller/DocumentController.ts b/packages/base-docs/src/Controller/DocumentController.ts
deleted file mode 100644
index 40b5bc08ac..0000000000
--- a/packages/base-docs/src/Controller/DocumentController.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { LifecycleStages, OnLifecycle } from '@univerjs/core';
-import { Inject, Injector } from '@wendellhu/redi';
-
-import { InputController } from './InputController';
-
-@OnLifecycle(LifecycleStages.Rendered, DocumentController)
-export class DocumentController {
- private readonly _inputController: InputController;
-
- constructor(@Inject(Injector) private readonly _injector: Injector) {
- this._inputController = this._injector.createInstance(InputController);
- this._injector.add([InputController, this._inputController]);
- }
-}
diff --git a/packages/base-docs/src/Controller/InputController.ts b/packages/base-docs/src/Controller/InputController.ts
deleted file mode 100644
index ef585098ba..0000000000
--- a/packages/base-docs/src/Controller/InputController.ts
+++ /dev/null
@@ -1,780 +0,0 @@
-import {
- Documents,
- getParagraphBySpan,
- hasListSpan,
- IDocumentSkeletonLine,
- IDocumentSkeletonSpan,
- IEditorInputConfig,
- INodePosition,
- INodeSearch,
- isFirstSpan,
- isIndentBySpan,
- isPlaceholderOrSpace,
- isSameLine,
- TextSelection,
-} from '@univerjs/base-render';
-import {
- DataStreamTreeTokenType,
- Direction,
- Disposable,
- DisposableCollection,
- DocumentModel,
- ICommandService,
- ICurrentUniverService,
- IParagraph,
- Nullable,
- Observable,
- toDisposable,
-} from '@univerjs/core';
-import { IDisposable, Inject } from '@wendellhu/redi';
-
-import {
- DeleteCommand,
- IMEInputCommand,
- InsertCommand,
- UpdateCommand,
-} from '../commands/commands/core-editing.command';
-import { DocsViewManagerService } from '../services/docs-view-manager/docs-view-manager.service';
-import { DocsView } from '../View/Render/Views';
-
-/**
- * InputController handles inputting events on the currently focused DocsView and apply edits to corresponding UniverDoc.
- */
-export class InputController extends Disposable {
- private _previousIMEContent: string = '';
-
- private _previousIMEStart: number = -1;
-
- private _currentNodePosition: Nullable<INodePosition>;
-
- private _editorDisposables: DisposableCollection | null = null;
-
- private _currentDocsView: DocsView | null = null;
-
- constructor(
- @Inject(DocsViewManagerService) private readonly _docsViewManager: DocsViewManagerService,
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
- @ICommandService private readonly _commandService: ICommandService
- ) {
- super();
-
- this.disposeWithMe(
- toDisposable(
- this._docsViewManager.current$.subscribe((docsView) => {
- this._currentDocsView?.getDocs().disableEditor();
- this._editorDisposables?.dispose();
- this._editorDisposables = null;
-
- if (docsView) {
- this._currentDocsView = docsView;
- this._editorDisposables = this._initialize(docsView);
- }
- })
- )
- );
- }
-
- override dispose(): void {
- super.dispose();
-
- this._currentDocsView = null;
- this._editorDisposables?.dispose();
- }
-
- moveCursor(_docModel: DocumentModel, direction: Direction) {
- if (!this._currentDocsView) {
- return;
- }
-
- const documents = this._currentDocsView.getDocs();
- const activeSelection = documents.getActiveSelection();
- if (!activeSelection) {
- return false;
- }
-
- const startNodePosition = activeSelection.getStart();
- const preSpan = documents.findSpanByPosition(startNodePosition);
-
- // TODO@DR-Univer: 这里的代码重复的部分比较多
- if (direction === Direction.DOWN || direction === Direction.UP) {
- const newPos = this._getTopOrBottomPosition(documents as Documents, preSpan, direction === Direction.DOWN);
- if (newPos == null) {
- return;
- }
-
- const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
- if (selectionRemain == null) {
- return;
- }
-
- this._syncSelection(documents as Documents, selectionRemain, newPos, true);
- } else if (direction === Direction.LEFT) {
- const activeRange = activeSelection.getRange();
- const cursorStart = activeRange.cursorStart;
- let cursor = cursorStart;
- let span: Nullable<IDocumentSkeletonSpan>;
- let isBack = false;
- if (isFirstSpan(preSpan)) {
- span = documents.findNodeByCharIndex(cursor);
-
- if (preSpan === span) {
- isBack = true;
- }
-
- while (isPlaceholderOrSpace(span)) {
- span = documents.findNodeByCharIndex(--cursor);
- }
- } else {
- span = documents.findNodeByCharIndex(--cursor);
- }
-
- const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
- this._adjustSelection(documents, selectionRemain, span, isBack, true);
- } else {
- const activeRange = activeSelection.getRange();
- const cursorStart = activeRange.cursorStart;
- const isStartBack = activeRange.isStartBack;
- let cursor = cursorStart;
- if (isStartBack === true) {
- cursor -= 1;
- }
-
- let span = documents.findNodeByCharIndex(++cursor);
-
- const originCursor = cursor;
-
- while (isPlaceholderOrSpace(span)) {
- span = documents.findNodeByCharIndex(++cursor);
- }
-
- let isBack = false;
- if (isFirstSpan(span) && preSpan !== span) {
- isBack = true;
- } else {
- span = documents.findNodeByCharIndex(originCursor);
- }
-
- if (span == null) {
- return;
- }
- const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
- this._adjustSelection(documents, selectionRemain, span, isBack, true);
- }
- }
-
- // eslint-disable-next-line max-lines-per-function
- deleteLeft() {
- if (!this._currentDocsView) {
- return;
- }
-
- const document = this._currentDocsView.getDocs();
- const activeSelection = document.getActiveSelection();
- if (!activeSelection) {
- return;
- }
-
- const skeleton = document.getSkeleton();
- const docsModel = this._currentUniverService.getCurrentUniverDocInstance();
- const startNodePosition = activeSelection.getStart();
- const preSpan = document.findSpanByPosition(startNodePosition);
-
- const preIsBullet = hasListSpan(preSpan);
-
- const preIsIndent = isIndentBySpan(preSpan, docsModel.body);
-
- const activeRange = activeSelection.getRange();
- const cursorStart = activeRange.cursorStart;
- const isStartBack = activeRange.isStartBack;
- const isCollapse = activeRange.isCollapse;
- const segmentId = activeSelection.segmentId;
- let cursor = cursorStart;
-
- if (isStartBack === true) {
- cursor -= 1;
- }
-
- if (isCollapse === false) {
- cursor += 1;
- }
-
- let span = document.findNodeByCharIndex(cursor);
-
- const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
-
- // const content = document.findNodeByCharIndex(cursor - 1)?.content || '';
- const isUpdateParagraph =
- isFirstSpan(preSpan) && span !== preSpan && (preIsBullet === true || preIsIndent === true);
- if (isUpdateParagraph) {
- const paragraph = getParagraphBySpan(preSpan, docsModel.body);
-
- if (paragraph == null) {
- return;
- }
-
- const paragraphIndex = paragraph?.startIndex;
-
- const updateParagraph: IParagraph = { startIndex: 0 };
-
- const paragraphStyle = paragraph.paragraphStyle;
- if (preIsBullet === true) {
- const paragraphStyle = paragraph.paragraphStyle;
- if (paragraphStyle) {
- updateParagraph.paragraphStyle = paragraphStyle;
- }
- } else if (preIsIndent === true) {
- const bullet = paragraph.bullet;
- if (bullet) {
- updateParagraph.bullet = bullet;
- }
- if (paragraphStyle != null) {
- updateParagraph.paragraphStyle = { ...paragraphStyle };
- delete updateParagraph.paragraphStyle.hanging;
- delete updateParagraph.paragraphStyle.indentStart;
- }
- }
-
- this._commandService.executeCommand(UpdateCommand.id, {
- unitId: docsModel.getUnitId(),
- body: {
- dataStream: '',
- paragraphs: [{ ...updateParagraph }],
- },
- range: {
- cursorStart: paragraphIndex,
- cursorEnd: paragraphIndex,
- isEndBack: false,
- isStartBack: false,
- isCollapse: true,
- },
- segmentId,
- });
- } else {
- const endNodePosition = activeSelection?.getEnd();
- if (endNodePosition != null) {
- const endSpan = document.findSpanByPosition(endNodePosition);
- if (hasListSpan(endSpan) && !isSameLine(preSpan, endSpan)) {
- activeRange.cursorEnd -= 1;
- }
- }
-
- this._commandService.executeCommand(DeleteCommand.id, {
- unitId: docsModel.getUnitId(),
- range: activeRange,
- segmentId,
- });
- }
-
- skeleton?.calculate();
-
- let isBack = false;
-
- if (isUpdateParagraph) {
- isBack = true;
- cursor++;
- } else if (isFirstSpan(span)) {
- isBack = true;
- } else {
- cursor--;
- }
- span = document.findNodeByCharIndex(cursor);
-
- this._adjustSelection(document as Documents, selectionRemain, span, isBack);
-
- //
- this._resetIME();
- }
-
- breakLine() {
- if (!this._currentDocsView) {
- return;
- }
-
- const document = this._currentDocsView.getDocs();
- const activeSelection = document.getActiveSelection();
- if (!activeSelection) {
- return;
- }
-
- const skeleton = document.getSkeleton();
- const docsModel = this._currentUniverService.getCurrentUniverDocInstance();
- const startNodePosition = activeSelection.getStart();
-
- const activeRange = activeSelection.getRange();
- const cursorStart = activeRange.cursorStart;
- const isStartBack = activeRange.isStartBack;
- const segmentId = activeSelection.segmentId;
- // split paragraph
- let cursor = cursorStart;
-
- if (isStartBack === false) {
- cursor += 1;
- }
-
- const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
-
- this._commandService.executeCommand(InsertCommand.id, {
- unitId: docsModel.getUnitId(),
- body: {
- dataStream: DataStreamTreeTokenType.PARAGRAPH,
- paragraphs: this._generateParagraph(DataStreamTreeTokenType.PARAGRAPH),
- },
- range: activeRange,
- segmentId,
- });
-
- skeleton?.calculate();
-
- const span = document.findNodeByCharIndex(++cursor);
-
- this._adjustSelection(document as Documents, selectionRemain, span, true);
- }
-
- private _initialInput(onInputObservable: Observable<IEditorInputConfig>, docsModel: DocumentModel): IDisposable {
- const observer = 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;
-
- let cursor = cursorStart;
-
- if (isStartBack === false) {
- cursor += 1;
- }
-
- const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
-
- this._commandService.executeCommand(InsertCommand.id, {
- unitId: docsModel.getUnitId(),
- body: {
- dataStream: content,
- },
- range: activeRange,
- segmentId,
- });
-
- skeleton.calculate();
-
- cursor += content.length - 1;
-
- const span = document.findNodeByCharIndex(cursor);
-
- this._adjustSelection(document as Documents, selectionRemain, span);
- });
-
- return toDisposable(() => onInputObservable.remove(observer));
- }
-
- private _initialComposition(
- onCompositionstartObservable: Observable<IEditorInputConfig>,
- onCompositionupdateObservable: Observable<IEditorInputConfig>,
- onCompositionendObservable: Observable<IEditorInputConfig>,
- docsModel: DocumentModel
- ): IDisposable {
- const startObserver = onCompositionstartObservable.add((config) => {
- const { activeSelection, selectionList } = config;
-
- const activeRange = activeSelection?.getRange();
-
- if (!activeRange) {
- return;
- }
-
- const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack } = activeRange;
-
- let cursor = cursorStart;
-
- if (isStartBack === true) {
- cursor -= 1;
- }
- this._previousIMEStart = cursor;
- });
-
- const updateObserver = onCompositionupdateObservable.add(async (config) => {
- const { event, document, activeSelection } = config;
-
- let cursor = this._previousIMEStart;
-
- const skeleton = document.getSkeleton();
-
- const segmentId = activeSelection?.segmentId;
-
- if (!skeleton) {
- return;
- }
-
- const e = event as CompositionEvent;
-
- const content = e.data;
-
- if (content === this._previousIMEContent) {
- return;
- }
-
- const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
-
- await this._commandService.executeCommand(IMEInputCommand.id, {
- unitId: docsModel.getUnitId(),
- newText: content,
- oldTextLen: this._previousIMEContent.length,
- start: cursor,
- segmentId,
- });
-
- skeleton.calculate();
-
- cursor += content.length;
-
- const span = document.findNodeByCharIndex(cursor);
-
- this._adjustSelection(document as Documents, selectionRemain, span);
-
- this._previousIMEContent = content;
- });
-
- const endObserver = onCompositionendObservable.add((config) => {
- this._resetIME();
- });
-
- return toDisposable(() => {
- onCompositionstartObservable.remove(startObserver);
- onCompositionupdateObservable.remove(updateObserver);
- onCompositionendObservable.remove(endObserver);
- });
- }
-
- private _getTopOrBottomPosition(
- document: Documents,
- span: Nullable<IDocumentSkeletonSpan>,
- direction: boolean
- ): Nullable<INodePosition> {
- const referenceSpan = document.findSpanByPosition(this._currentNodePosition);
- if (referenceSpan == null || span == null) {
- return;
- }
-
- const offsetLeft = this._getSpanLeftOffsetInLine(referenceSpan);
-
- const line = this._getNextOrPrevLine(span, direction);
-
- if (line == null) {
- return;
- }
-
- const position: Nullable<INodeSearch> = this._matchPositionByLeftOffset(document, line, offsetLeft);
-
- let isBack = this._currentNodePosition?.isBack;
-
- isBack = isBack == null ? false : isBack;
-
- if (position == null) {
- return;
- }
-
- return { ...position, isBack };
- }
-
- private _getSpanLeftOffsetInLine(span: IDocumentSkeletonSpan) {
- const divide = span.parent;
-
- if (divide == null) {
- return -Infinity;
- }
-
- const divideLeft = divide.left;
-
- const { left, width } = span;
-
- const start = divideLeft + left;
-
- if (this._currentNodePosition?.isBack === true) {
- return start;
- }
-
- return start + width;
- }
-
- private _matchPositionByLeftOffset(document: Documents, 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 document.findPositionBySpan(span);
- }
-
- const distance = Math.abs(offsetLeft - (leftSide + rightSide) / 2);
- if (distance < nearestNode.distance) {
- nearestNode.span = span;
- nearestNode.distance = distance;
- }
- }
- }
-
- if (nearestNode.span == null) {
- return;
- }
-
- return document.findPositionBySpan(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 = '';
-
- this._previousIMEStart = -1;
- }
-
- private _getIncreaseText(current: string, old: string) {
- const oldLen = old.length;
- return current.slice(oldLen);
- }
-
- private _adjustSelection(
- document: Documents,
- selectionRemain?: TextSelection,
- span?: Nullable<IDocumentSkeletonSpan>,
- isBack = false,
- isSyncScroll = false
- ) {
- if (span == null) {
- return;
- }
-
- const position = document.findPositionBySpan(span);
-
- if (position == null || selectionRemain == null) {
- return;
- }
-
- const newPos: INodePosition = { ...position, isBack };
-
- this._syncSelection(document, selectionRemain, newPos, isSyncScroll);
-
- this._currentNodePosition = selectionRemain.getStart();
-
- // document.addSelection(selectionRemain);
-
- // selectionRemain.startNodePosition = newPos;
-
- // selectionRemain.endNodePosition = undefined;
-
- // selectionRemain.refresh(document);
-
- // this._currentNodePosition = selectionRemain.getStart();
-
- // if (isSyncScroll) {
- // document.scrollBySelection();
- // }
-
- // document.syncSelection();
- }
-
- private _syncSelection(
- document: Documents,
- selectionRemain: TextSelection,
- newPos: INodePosition,
- isSyncScroll = false
- ) {
- document.addSelection(selectionRemain);
-
- selectionRemain.startNodePosition = newPos;
-
- selectionRemain.endNodePosition = undefined;
-
- selectionRemain.refresh(document);
-
- if (isSyncScroll) {
- document.scrollBySelection();
- }
-
- document.syncSelection();
- }
-
- private _initialize(docsView: DocsView): DisposableCollection {
- docsView.getDocs().enableEditor();
- const events = docsView.getDocs().getEditorInputEvent();
- const docsModel = this._currentUniverService.getCurrentUniverDocInstance();
- const disposableCollection = new DisposableCollection();
-
- if (!events) {
- return disposableCollection;
- }
-
- const {
- onInputObservable,
- onCompositionstartObservable,
- onCompositionupdateObservable,
- onCompositionendObservable,
- onSelectionStartObservable,
- } = events;
-
- disposableCollection.add(this._initialInput(onInputObservable, docsModel));
- disposableCollection.add(
- this._initialComposition(
- onCompositionstartObservable,
- onCompositionupdateObservable,
- onCompositionendObservable,
- docsModel
- )
- );
-
- const observer = onSelectionStartObservable.add((nodePosition) => {
- this._currentNodePosition = nodePosition;
- });
- disposableCollection.add(toDisposable(() => onSelectionStartObservable.remove(observer)));
-
- return disposableCollection;
- }
-}
diff --git a/packages/base-docs/src/Controller/delete-left-input.controller.ts b/packages/base-docs/src/Controller/delete-left-input.controller.ts
new file mode 100644
index 0000000000..1e1fb40b60
--- /dev/null
+++ b/packages/base-docs/src/Controller/delete-left-input.controller.ts
@@ -0,0 +1,191 @@
+import {
+ getParagraphBySpan,
+ hasListSpan,
+ IRenderManagerService,
+ isFirstSpan,
+ isIndentBySpan,
+ isSameLine,
+ ITextSelectionRenderManager,
+} from '@univerjs/base-render';
+import {
+ Disposable,
+ ICommandInfo,
+ ICommandService,
+ ICurrentUniverService,
+ IParagraph,
+ LifecycleStages,
+ Nullable,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Subscription } from 'rxjs';
+
+import { getDocObject } from '../Basics/component-tools';
+import { DeleteCommand, DeleteLeftCommand, UpdateCommand } from '../commands/commands/core-editing.command';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
+
+@OnLifecycle(LifecycleStages.Rendered, DeleteLeftInputController)
+export class DeleteLeftInputController extends Disposable {
+ private _onInputSubscription: Nullable<Subscription>;
+
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ override dispose(): void {
+ this._onInputSubscription?.unsubscribe();
+ }
+
+ private _initialize() {}
+
+ private _commandExecutedListener() {
+ const updateCommandList = [DeleteLeftCommand.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ this._deleteFunction();
+ })
+ );
+ }
+
+ private _deleteFunction() {
+ const activeRange = this._textSelectionRenderManager.getActiveRange();
+
+ const activeSelection = this._textSelectionRenderManager.getActiveTextSelection();
+
+ const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+
+ if (activeRange == null || skeleton == null || activeSelection == null) {
+ return;
+ }
+
+ const docsModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const startNodePosition = activeSelection.getStart();
+ const preSpan = skeleton.findSpanByPosition(startNodePosition);
+
+ const preIsBullet = hasListSpan(preSpan);
+
+ const preIsIndent = isIndentBySpan(preSpan, docsModel.body);
+
+ const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } = activeRange;
+
+ let cursor = cursorStart;
+
+ if (isStartBack === true) {
+ cursor -= 1;
+ }
+
+ if (isCollapse === false) {
+ cursor += 1;
+ }
+
+ const span = skeleton.findNodeByCharIndex(cursor);
+
+ const isUpdateParagraph =
+ isFirstSpan(preSpan) && span !== preSpan && (preIsBullet === true || preIsIndent === true);
+ if (isUpdateParagraph) {
+ const paragraph = getParagraphBySpan(preSpan, docsModel.body);
+
+ if (paragraph == null) {
+ return;
+ }
+
+ const paragraphIndex = paragraph?.startIndex;
+
+ const updateParagraph: IParagraph = { startIndex: 0 };
+
+ const paragraphStyle = paragraph.paragraphStyle;
+ if (preIsBullet === true) {
+ const paragraphStyle = paragraph.paragraphStyle;
+ if (paragraphStyle) {
+ updateParagraph.paragraphStyle = paragraphStyle;
+ }
+ } else if (preIsIndent === true) {
+ const bullet = paragraph.bullet;
+ if (bullet) {
+ updateParagraph.bullet = bullet;
+ }
+ if (paragraphStyle != null) {
+ updateParagraph.paragraphStyle = { ...paragraphStyle };
+ delete updateParagraph.paragraphStyle.hanging;
+ delete updateParagraph.paragraphStyle.indentStart;
+ }
+ }
+
+ this._commandService.executeCommand(UpdateCommand.id, {
+ unitId: docsModel.getUnitId(),
+ body: {
+ dataStream: '',
+ paragraphs: [{ ...updateParagraph }],
+ },
+ range: {
+ cursorStart: paragraphIndex,
+ cursorEnd: paragraphIndex,
+ isEndBack: false,
+ isStartBack: false,
+ isCollapse: true,
+ },
+ segmentId,
+ });
+ } else {
+ const endNodePosition = activeSelection?.getEnd();
+ if (endNodePosition != null) {
+ const endSpan = skeleton.findSpanByPosition(endNodePosition);
+ if (hasListSpan(endSpan) && !isSameLine(preSpan, endSpan)) {
+ activeRange.cursorEnd -= 1;
+ }
+ }
+
+ this._commandService.executeCommand(DeleteCommand.id, {
+ unitId: docsModel.getUnitId(),
+ range: activeRange,
+ segmentId,
+ });
+ }
+
+ skeleton?.calculate();
+
+ let isBack = false;
+
+ if (isUpdateParagraph) {
+ isBack = true;
+ cursor++;
+ } else if (isFirstSpan(span)) {
+ isBack = true;
+ } else {
+ cursor--;
+ }
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: cursor,
+ cursorEnd: cursor,
+ isCollapse: true,
+ isEndBack: isBack,
+ isStartBack: isBack,
+ style,
+ },
+ ]);
+ }
+
+ private _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
+}
diff --git a/packages/base-docs/src/Controller/doc-render.controller.ts b/packages/base-docs/src/Controller/doc-render.controller.ts
new file mode 100644
index 0000000000..33623eb10c
--- /dev/null
+++ b/packages/base-docs/src/Controller/doc-render.controller.ts
@@ -0,0 +1,57 @@
+import { Documents, IRenderManagerService } from '@univerjs/base-render';
+import { Disposable, ICommandService, ICurrentUniverService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+
+@OnLifecycle(LifecycleStages.Rendered, DocRenderController)
+export class DocRenderController extends Disposable {
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ private _initialize() {
+ this._initialRenderRefresh();
+ }
+
+ private _initialRenderRefresh() {
+ this._docSkeletonManagerService.currentSkeletonBefore$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+
+ const { skeleton: documentSkeleton, unitId } = param;
+
+ const documentModel = this._currentUniverService.getUniverDocInstance(unitId);
+
+ if (documentModel == null) {
+ return;
+ }
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { mainComponent, components, scene } = currentRender;
+
+ const docsComponent = mainComponent as Documents;
+
+ docsComponent.changeSkeleton(documentSkeleton);
+
+ documentSkeleton.calculate();
+ });
+ }
+
+ private _commandExecutedListener() {}
+}
diff --git a/packages/base-docs/src/Controller/ime-input.controller.ts b/packages/base-docs/src/Controller/ime-input.controller.ts
new file mode 100644
index 0000000000..65ed80bdd8
--- /dev/null
+++ b/packages/base-docs/src/Controller/ime-input.controller.ts
@@ -0,0 +1,150 @@
+import {
+ IRenderManagerService,
+ ITextSelectionRangeWithStyle,
+ ITextSelectionRenderManager,
+} from '@univerjs/base-render';
+import {
+ Disposable,
+ ICommandService,
+ ICurrentUniverService,
+ LifecycleStages,
+ Nullable,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Subscription } from 'rxjs';
+
+import { getDocObject } from '../Basics/component-tools';
+import { IMEInputCommand } from '../commands/commands/core-editing.command';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
+
+@OnLifecycle(LifecycleStages.Rendered, IMEInputController)
+export class IMEInputController extends Disposable {
+ private _previousIMEContent: string = '';
+
+ private _previousIMERange: Nullable<ITextSelectionRangeWithStyle>;
+
+ private _onStartSubscription: Nullable<Subscription>;
+
+ private _onUpdateSubscription: Nullable<Subscription>;
+
+ private _onEndSubscription: Nullable<Subscription>;
+
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ override dispose(): void {
+ this._onStartSubscription?.unsubscribe();
+ this._onUpdateSubscription?.unsubscribe();
+ this._onEndSubscription?.unsubscribe();
+ }
+
+ private _initialize() {
+ this._initialOnCompositionstart();
+
+ this._initialOnCompositionUpdate();
+
+ this._onEndSubscription = this._textSelectionRenderManager.onCompositionend$.subscribe((config) => {
+ this._resetIME();
+ });
+ }
+
+ private _initialOnCompositionstart() {
+ this._onStartSubscription = this._textSelectionRenderManager.onCompositionstart$.subscribe((config) => {
+ if (config == null) {
+ return;
+ }
+ const { activeRange } = config;
+
+ if (activeRange == null) {
+ return;
+ }
+
+ this._previousIMERange = activeRange;
+ });
+ }
+
+ private _initialOnCompositionUpdate() {
+ this._onUpdateSubscription = this._textSelectionRenderManager.onCompositionupdate$.subscribe(async (config) => {
+ const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+
+ if (this._previousIMERange == null || config == null || skeleton == null) {
+ return;
+ }
+
+ const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
+
+ const { event, activeRange } = config;
+
+ const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } =
+ this._previousIMERange;
+
+ if (skeleton == null || activeRange == null) {
+ return;
+ }
+
+ const e = event as CompositionEvent;
+
+ const content = e.data;
+
+ if (content === this._previousIMEContent) {
+ return;
+ }
+
+ await this._commandService.executeCommand(IMEInputCommand.id, {
+ unitId: documentModel.getUnitId(),
+ newText: content,
+ oldTextLen: this._previousIMEContent.length,
+ range: this._previousIMERange,
+ segmentId,
+ });
+
+ skeleton.calculate();
+
+ const len = content.length;
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: cursorStart + len,
+ cursorEnd: cursorEnd + len,
+ isCollapse: true,
+ isEndBack,
+ isStartBack,
+ style,
+ },
+ ]);
+
+ if (!this._previousIMERange.isCollapse) {
+ this._previousIMERange.isCollapse = true;
+ }
+
+ this._previousIMEContent = content;
+ });
+ }
+
+ private _resetIME() {
+ this._previousIMEContent = '';
+
+ this._previousIMERange = null;
+ }
+
+ private _commandExecutedListener() {}
+
+ private _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
+}
diff --git a/packages/base-docs/src/Controller/line-break-input.controller.ts b/packages/base-docs/src/Controller/line-break-input.controller.ts
new file mode 100644
index 0000000000..324167af63
--- /dev/null
+++ b/packages/base-docs/src/Controller/line-break-input.controller.ts
@@ -0,0 +1,129 @@
+import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import {
+ DataStreamTreeTokenType,
+ Disposable,
+ ICommandInfo,
+ ICommandService,
+ ICurrentUniverService,
+ IParagraph,
+ LifecycleStages,
+ Nullable,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Subscription } from 'rxjs';
+
+import { getDocObject } from '../Basics/component-tools';
+import { BreakLineCommand, InsertCommand } from '../commands/commands/core-editing.command';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
+
+@OnLifecycle(LifecycleStages.Rendered, LineBreakInputController)
+export class LineBreakInputController extends Disposable {
+ private _onInputSubscription: Nullable<Subscription>;
+
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ override dispose(): void {
+ this._onInputSubscription?.unsubscribe();
+ }
+
+ private _initialize() {}
+
+ private _commandExecutedListener() {
+ const updateCommandList = [BreakLineCommand.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ this._breakLineFunction();
+ })
+ );
+ }
+
+ private _breakLineFunction() {
+ const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+
+ const activeRange = this._textSelectionRenderManager.getActiveRange();
+
+ if (activeRange == null || skeleton == null) {
+ return;
+ }
+
+ const docsModel = this._currentUniverService.getCurrentUniverDocInstance();
+
+ const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } = activeRange;
+
+ // split paragraph
+ let cursor = cursorStart;
+
+ if (isStartBack === false) {
+ cursor += 1;
+ }
+
+ // const selectionRemain = document.remainActiveSelection() as TextSelection | undefined;
+
+ this._commandService.executeCommand(InsertCommand.id, {
+ unitId: docsModel.getUnitId(),
+ body: {
+ dataStream: DataStreamTreeTokenType.PARAGRAPH,
+ paragraphs: this._generateParagraph(DataStreamTreeTokenType.PARAGRAPH),
+ },
+ range: activeRange,
+ segmentId,
+ });
+
+ skeleton?.calculate();
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: cursor + 1,
+ cursorEnd: cursor + 1,
+ isCollapse: true,
+ isEndBack,
+ isStartBack,
+ style,
+ },
+ ]);
+
+ // const span = document.findNodeByCharIndex(++cursor);
+
+ // this._adjustSelection(document as Documents, selectionRemain, span, true);
+ }
+
+ 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 _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
+}
diff --git a/packages/base-docs/src/Controller/move-cursor.controller.ts b/packages/base-docs/src/Controller/move-cursor.controller.ts
new file mode 100644
index 0000000000..35e8dc7809
--- /dev/null
+++ b/packages/base-docs/src/Controller/move-cursor.controller.ts
@@ -0,0 +1,389 @@
+import {
+ DocumentSkeleton,
+ IDocumentSkeletonLine,
+ IDocumentSkeletonSpan,
+ INodePosition,
+ INodeSearch,
+ IRenderManagerService,
+ isFirstSpan,
+ isPlaceholderOrSpace,
+ ITextSelectionRenderManager,
+ NodePositionConvertToCursor,
+} from '@univerjs/base-render';
+import {
+ Direction,
+ Disposable,
+ ICommandInfo,
+ ICommandService,
+ ICurrentUniverService,
+ LifecycleStages,
+ Nullable,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Subscription } from 'rxjs';
+
+import { getDocObject } from '../Basics/component-tools';
+import { IMoveCursorOperationParams, MoveCursorOperation } from '../commands/operations/cursor.operation';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
+
+@OnLifecycle(LifecycleStages.Rendered, MoveCursorController)
+export class MoveCursorController extends Disposable {
+ private _onInputSubscription: Nullable<Subscription>;
+
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ override dispose(): void {
+ this._onInputSubscription?.unsubscribe();
+ }
+
+ private _initialize() {}
+
+ private _commandExecutedListener() {
+ const updateCommandList = [MoveCursorOperation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ const param = command.params as IMoveCursorOperationParams;
+
+ this._moveCursorFunction(param.direction);
+ })
+ );
+ }
+
+ private _moveCursorFunction(direction: Direction) {
+ const activeRange = this._textSelectionRenderManager.getActiveRange();
+
+ const activeSelection = this._textSelectionRenderManager.getActiveTextSelection();
+
+ const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+
+ const docObject = this._getDocObject();
+
+ if (activeRange == null || skeleton == null || activeSelection == null || docObject == null) {
+ return;
+ }
+
+ const startNodePosition = activeSelection.getStart();
+ const preSpan = skeleton.findSpanByPosition(startNodePosition);
+
+ const documentOffsetConfig = docObject.document.getOffsetConfig();
+
+ const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } = activeRange;
+
+ let cursor = cursorStart;
+
+ if (direction === Direction.DOWN || direction === Direction.UP) {
+ const newPos = this._getTopOrBottomPosition(skeleton, preSpan, direction === Direction.DOWN);
+ if (newPos == null) {
+ return;
+ }
+
+ const newActiveRange = new NodePositionConvertToCursor(documentOffsetConfig, skeleton).getRangePointData(
+ newPos,
+ newPos
+ ).cursorList[0];
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ ...newActiveRange,
+ style,
+ },
+ ]);
+
+ // const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
+ // if (selectionRemain == null) {
+ // return;
+ // }
+
+ // this._syncSelection(documents as Documents, selectionRemain, newPos, true);
+ } else if (direction === Direction.LEFT) {
+ let span: Nullable<IDocumentSkeletonSpan>;
+ let isBack = false;
+ if (isFirstSpan(preSpan)) {
+ span = skeleton.findNodeByCharIndex(cursor);
+
+ if (preSpan === span) {
+ isBack = true;
+ }
+
+ while (isPlaceholderOrSpace(span)) {
+ span = skeleton.findNodeByCharIndex(--cursor);
+ }
+ } else {
+ span = skeleton.findNodeByCharIndex(--cursor);
+ }
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: cursor,
+ cursorEnd: cursor,
+ isCollapse: true,
+ isEndBack: isBack,
+ isStartBack: isBack,
+ style,
+ },
+ ]);
+
+ // const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
+ // this._adjustSelection(documents, selectionRemain, span, isBack, true);
+ } else {
+ if (isStartBack === true) {
+ cursor -= 1;
+ }
+
+ let span = skeleton.findNodeByCharIndex(++cursor);
+
+ const originCursor = cursor;
+
+ while (isPlaceholderOrSpace(span)) {
+ span = skeleton.findNodeByCharIndex(++cursor);
+ }
+
+ let isBack = false;
+ if (isFirstSpan(span) && preSpan !== span) {
+ isBack = true;
+ } else {
+ cursor = originCursor;
+ }
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: cursor,
+ cursorEnd: cursor,
+ isCollapse: true,
+ isEndBack: isBack,
+ isStartBack: isBack,
+ style,
+ },
+ ]);
+ // const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
+ // this._adjustSelection(documents, selectionRemain, span, isBack, true);
+ }
+ }
+
+ private _getTopOrBottomPosition(
+ docSkeleton: DocumentSkeleton,
+ span: Nullable<IDocumentSkeletonSpan>,
+ direction: boolean
+ ): Nullable<INodePosition> {
+ // const referenceSpan = docSkeleton.findSpanByPosition(this._currentNodePosition);
+ const selectionRange = this._textSelectionManagerService.getFirst();
+ if (selectionRange == null) {
+ return;
+ }
+ const referenceSpan = docSkeleton.findNodeByCharIndex(selectionRange.cursorStart);
+ if (referenceSpan == null || span == null) {
+ return;
+ }
+
+ let isBack = selectionRange.isStartBack;
+
+ const offsetLeft = this._getSpanLeftOffsetInLine(referenceSpan, isBack);
+
+ const line = this._getNextOrPrevLine(span, direction);
+
+ if (line == null) {
+ return;
+ }
+
+ const position: Nullable<INodeSearch> = this._matchPositionByLeftOffset(docSkeleton, line, offsetLeft);
+
+ isBack = isBack == null ? false : isBack;
+
+ if (position == null) {
+ return;
+ }
+
+ return { ...position, isBack };
+ }
+
+ private _getSpanLeftOffsetInLine(span: IDocumentSkeletonSpan, isBack: boolean) {
+ const divide = span.parent;
+
+ if (divide == null) {
+ return -Infinity;
+ }
+
+ const divideLeft = divide.left;
+
+ const { left, width } = span;
+
+ const start = divideLeft + left;
+
+ if (isBack === true) {
+ return start;
+ }
+
+ return start + width;
+ }
+
+ private _matchPositionByLeftOffset(docSkeleton: DocumentSkeleton, 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 docSkeleton.findPositionBySpan(span);
+ }
+
+ const distance = Math.abs(offsetLeft - (leftSide + rightSide) / 2);
+ if (distance < nearestNode.distance) {
+ nearestNode.span = span;
+ nearestNode.distance = distance;
+ }
+ }
+ }
+
+ if (nearestNode.span == null) {
+ return;
+ }
+
+ return docSkeleton.findPositionBySpan(nearestNode.span);
+ }
+
+ 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 _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
+}
diff --git a/packages/base-docs/src/Controller/normal-input.controller.ts b/packages/base-docs/src/Controller/normal-input.controller.ts
new file mode 100644
index 0000000000..3a0725d6fc
--- /dev/null
+++ b/packages/base-docs/src/Controller/normal-input.controller.ts
@@ -0,0 +1,101 @@
+import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import {
+ Disposable,
+ ICommandService,
+ ICurrentUniverService,
+ LifecycleStages,
+ Nullable,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Subscription } from 'rxjs';
+
+import { getDocObject } from '../Basics/component-tools';
+import { InsertCommand } from '../commands/commands/core-editing.command';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
+
+@OnLifecycle(LifecycleStages.Rendered, NormalInputController)
+export class NormalInputController extends Disposable {
+ private _onInputSubscription: Nullable<Subscription>;
+
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ override dispose(): void {
+ this._onInputSubscription?.unsubscribe();
+ }
+
+ private _initialize() {
+ this._initialNormalInput();
+ }
+
+ private _initialNormalInput() {
+ this._onInputSubscription = this._textSelectionRenderManager.onInput$.subscribe((config) => {
+ if (config == null) {
+ return;
+ }
+
+ const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
+
+ const { event, content = '', activeRange } = config;
+
+ const e = event as InputEvent;
+
+ const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+
+ if (e.data == null || skeleton == null) {
+ return;
+ }
+
+ if (!skeleton || !activeRange) {
+ return;
+ }
+
+ const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } = activeRange;
+
+ this._commandService.executeCommand(InsertCommand.id, {
+ unitId: documentModel.getUnitId(),
+ body: {
+ dataStream: content,
+ },
+ range: activeRange,
+ segmentId,
+ });
+
+ skeleton.calculate();
+
+ const len = content.length;
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ cursorStart: cursorStart + len,
+ cursorEnd: cursorStart + len,
+ isCollapse: true,
+ isEndBack,
+ isStartBack,
+ style,
+ },
+ ]);
+ });
+ }
+
+ private _commandExecutedListener() {}
+
+ private _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
+}
diff --git a/packages/base-docs/src/Controller/page-render.controller.ts b/packages/base-docs/src/Controller/page-render.controller.ts
new file mode 100644
index 0000000000..ee52fc18cf
--- /dev/null
+++ b/packages/base-docs/src/Controller/page-render.controller.ts
@@ -0,0 +1,69 @@
+import { Documents, IPageRenderConfig, IRenderManagerService, Rect } from '@univerjs/base-render';
+import { Disposable, ICommandService, ICurrentUniverService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+
+const PAGE_STROKE_COLOR = 'rgba(198,198,198, 1)';
+
+const PAGE_FILL_COLOR = 'rgba(255,255,255, 1)';
+
+@OnLifecycle(LifecycleStages.Rendered, PageRenderController)
+export class PageRenderController extends Disposable {
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ private _initialize() {
+ this._initialRenderRefresh();
+ }
+
+ private _initialRenderRefresh() {
+ this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+
+ const { unitId } = param;
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { mainComponent, components, scene } = currentRender;
+
+ const docsComponent = mainComponent as Documents;
+
+ const pageSize = docsComponent.getSkeleton()?.getPageSize();
+
+ docsComponent.onPageRenderObservable.add((config: IPageRenderConfig) => {
+ const { page, pageLeft, pageTop, ctx } = config;
+ const { width, height, marginBottom, marginLeft, marginRight, marginTop } = page;
+ ctx.save();
+ ctx.translate(pageLeft - 0.5, pageTop - 0.5);
+ Rect.drawWith(ctx, {
+ width: pageSize?.width || width,
+ height: pageSize?.height || height,
+ strokeWidth: 1,
+ stroke: PAGE_STROKE_COLOR,
+ fill: PAGE_FILL_COLOR,
+ zIndex: 3,
+ });
+ ctx.restore();
+ });
+ });
+ }
+
+ private _commandExecutedListener() {}
+}
diff --git a/packages/base-docs/src/Controller/text-selection.controller.ts b/packages/base-docs/src/Controller/text-selection.controller.ts
new file mode 100644
index 0000000000..81338af48c
--- /dev/null
+++ b/packages/base-docs/src/Controller/text-selection.controller.ts
@@ -0,0 +1,225 @@
+import {
+ CURSOR_TYPE,
+ cursorConvertToTextSelection,
+ getOneTextSelectionRange,
+ IMouseEvent,
+ IPointerEvent,
+ IRenderManagerService,
+ ITextSelectionRangeWithStyle,
+ ITextSelectionRenderManager,
+ NodePositionConvertToCursor,
+} from '@univerjs/base-render';
+import {
+ Disposable,
+ ICommandInfo,
+ ICommandService,
+ ICurrentUniverService,
+ LifecycleStages,
+ Nullable,
+ Observer,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import { getDocObject, IDocObjectParam } from '../Basics/component-tools';
+import { VIEWPORT_KEY } from '../Basics/docs-view-key';
+import { ISetZoomRatioMutationParams, SetZoomRatioMutation } from '../commands/mutations/set-zoom-ratio.mutation';
+import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import {
+ NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ TextSelectionManagerService,
+} from '../services/text-selection-manager.service';
+
+@OnLifecycle(LifecycleStages.Rendered, TextSelectionController)
+export class TextSelectionController extends Disposable {
+ private _moveInObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _moveOutObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _downObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ITextSelectionRenderManager
+ private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ override dispose(): void {
+ const docObject = this._getDocObject();
+ if (docObject == null) {
+ return;
+ }
+ const { document, scene } = docObject;
+ document.onPointerEnterObserver.remove(this._moveInObserver);
+ document.onPointerLeaveObserver.remove(this._moveOutObserver);
+ document.onPointerLeaveObserver.remove(this._downObserver);
+ }
+
+ private _initialize() {
+ const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
+
+ const docObject = this._getDocObject();
+ if (docObject == null) {
+ return;
+ }
+
+ this._onChangeListener();
+
+ this._initialMain(docObject);
+
+ this._skeletonListener();
+
+ this._commandExecutedListener();
+
+ this._userActionSyncListener();
+
+ const unitId = documentModel.getUnitId();
+
+ this._textSelectionManagerService.setCurrentSelection({
+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ unitId,
+ });
+ }
+
+ private _initialMain(docObject: IDocObjectParam) {
+ const { document, scene } = docObject;
+ const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+
+ this._moveInObserver = document.onPointerEnterObserver.add(() => {
+ document.cursor = CURSOR_TYPE.TEXT;
+ });
+
+ this._moveOutObserver = document.onPointerLeaveObserver.add(() => {
+ document.cursor = CURSOR_TYPE.DEFAULT;
+ scene.resetCursor();
+ });
+
+ this._downObserver = document?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+ this._textSelectionRenderManager.eventTrigger(evt, document.getOffsetConfig());
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ });
+ }
+
+ private _onChangeListener() {
+ this._textSelectionManagerService.textSelectionInfo$.subscribe((param) => {
+ this._textSelectionRenderManager.reset();
+ if (param == null) {
+ return;
+ }
+
+ const docSkeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+
+ const currentRender = this._getDocObject();
+
+ if (currentRender == null || docSkeleton == null) {
+ return;
+ }
+
+ const { scene, document } = currentRender;
+
+ for (const selectionWithStyle of param) {
+ const textSelection = cursorConvertToTextSelection(
+ scene,
+ selectionWithStyle,
+ docSkeleton,
+ document.getOffsetConfig()
+ );
+ this._textSelectionRenderManager.add(textSelection);
+ }
+
+ this._textSelectionRenderManager.sync();
+ });
+ }
+
+ private _userActionSyncListener() {
+ this._textSelectionRenderManager.textSelection$.subscribe((textSelections) => {
+ const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const unitId = documentModel.getUnitId();
+
+ const docSkeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+
+ const document = this._getDocObject()?.document;
+
+ if (docSkeleton == null || document == null) {
+ return;
+ }
+
+ const convert = new NodePositionConvertToCursor(document.getOffsetConfig(), docSkeleton);
+
+ this._commandService.executeCommand(SetTextSelectionsOperation.id, {
+ unitId,
+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ ranges: textSelections
+ .map((textSelection) => {
+ let { endNodePosition } = textSelection;
+ const { startNodePosition } = textSelection;
+ if (endNodePosition == null) {
+ endNodePosition = startNodePosition;
+ }
+ const rangeList = convert.getRangePointData(startNodePosition, endNodePosition).cursorList;
+ return getOneTextSelectionRange(rangeList);
+ })
+ .filter((x) => x !== null) as ITextSelectionRangeWithStyle[],
+ });
+ });
+ }
+
+ private _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [SetZoomRatioMutation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
+
+ const params = command.params as ISetZoomRatioMutationParams;
+ const { documentId } = params;
+ if (documentId !== documentModel.getUnitId()) {
+ return;
+ }
+
+ this._textSelectionManagerService.refreshSelection();
+ }
+ })
+ );
+ }
+
+ private _skeletonListener() {
+ this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+ const { unitId, skeleton } = param;
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { scene } = currentRender;
+
+ this._textSelectionRenderManager.changeRuntime(skeleton, scene);
+
+ this._textSelectionManagerService.setCurrentSelection({
+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ unitId,
+ });
+ });
+ }
+}
diff --git a/packages/base-docs/src/DocPlugin.ts b/packages/base-docs/src/DocPlugin.ts
index a7e031b681..08fcaef8e0 100644
--- a/packages/base-docs/src/DocPlugin.ts
+++ b/packages/base-docs/src/DocPlugin.ts
@@ -1,3 +1,4 @@
+import { ITextSelectionRenderManager, TextSelectionRenderManager } from '@univerjs/base-render';
import { DesktopPlatformService, IPlatformService, IShortcutService } from '@univerjs/base-ui';
import {
ICommand,
@@ -5,7 +6,6 @@ import {
IConfigService,
ICurrentUniverService,
LocaleService,
- Nullable,
Plugin,
PLUGIN_NAMES,
PluginType,
@@ -22,11 +22,23 @@ import {
InsertCommand,
UpdateCommand,
} from './commands/commands/core-editing.command';
+import { SetZoomRatioCommand } from './commands/commands/set-zoom-ratio.command';
import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
+import { SetZoomRatioMutation } from './commands/mutations/set-zoom-ratio.mutation';
import { MoveCursorOperation } from './commands/operations/cursor.operation';
-import { DocumentController } from './Controller/DocumentController';
+import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
+import { DeleteLeftInputController } from './Controller/delete-left-input.controller';
+import { DocRenderController } from './Controller/doc-render.controller';
+import { IMEInputController } from './Controller/ime-input.controller';
+import { LineBreakInputController } from './Controller/line-break-input.controller';
+import { MoveCursorController } from './Controller/move-cursor.controller';
+import { NormalInputController } from './Controller/normal-input.controller';
+import { PageRenderController } from './Controller/page-render.controller';
+import { TextSelectionController } from './Controller/text-selection.controller';
import { en } from './Locale';
+import { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
import { DocsViewManagerService } from './services/docs-view-manager/docs-view-manager.service';
+import { TextSelectionManagerService } from './services/text-selection-manager.service';
import { BreakLineShortcut, DeleteLeftShortcut } from './shortcuts/core-editing.shortcut';
import {
MoveCursorDownShortcut,
@@ -34,8 +46,7 @@ import {
MoveCursorRightShortcut,
MoveCursorUpShortcut,
} from './shortcuts/cursor.shortcut';
-import { CanvasView } from './View/CanvasView';
-import { DocsView } from './View/Render/Views';
+import { DocCanvasView } from './View/doc-canvas-view';
export interface IDocPluginConfig {
[DOCS_CONFIG_STANDALONE_KEY]?: boolean;
@@ -49,8 +60,6 @@ export class DocPlugin extends Plugin {
private _config: IDocPluginConfig;
- private _canvasView!: CanvasView;
-
constructor(
config: Partial<IDocPluginConfig> = {},
@SkipSelf() @Inject(Injector) _univerInjector: Injector,
@@ -75,11 +84,11 @@ export class DocPlugin extends Plugin {
en,
});
- if (this._config.standalone) {
- this.initCanvasView();
- }
+ // if (this._config.standalone) {
+ // this.initCanvasView();
+ // }
- this._markDocAsFocused();
+ // this._markDocAsFocused();
}
initializeCommands(): void {
@@ -94,6 +103,9 @@ export class DocPlugin extends Plugin {
IMEInputCommand,
RichTextEditingMutation,
CoverCommand,
+ SetZoomRatioCommand,
+ SetZoomRatioMutation,
+ SetTextSelectionsOperation,
] as ICommand[]
).forEach((command) => {
this._injector.get(ICommandService).registerCommand(command);
@@ -116,45 +128,9 @@ export class DocPlugin extends Plugin {
this._configService.batchSettings(unitId, config);
}
- initCanvasView() {
- this._canvasView = this._injector.get(CanvasView);
- }
-
- getConfig() {
- return this._config;
- }
-
- /**
- * @deprecated use DI to get underlying dependencies
- * @returns
- */
- getCanvasView() {
- return this._canvasView;
- }
-
- /**
- * @deprecated use DI to get underlying dependencies
- * @returns
- */
- getDocsView() {
- return this.getCanvasView().getDocsView();
- }
-
- /**
- * @deprecated use DI to get underlying dependencies
- * @returns
- */
- getMainComponent() {
- return (this.getDocsView() as Nullable<DocsView>)?.getDocs();
- }
-
- /**
- * @deprecated use DI to get underlying dependencies
- * @returns
- */
- getInputEvent() {
- return this.getMainComponent()?.getEditorInputEvent();
- }
+ // initCanvasView() {
+ // this._canvasView = this._injector.get(CanvasView);
+ // }
override onReady(): void {
this.initialize();
@@ -169,12 +145,33 @@ export class DocPlugin extends Plugin {
private _initializeDependencies(docInjector: Injector, univerInjector: Injector) {
(
[
- [
- CanvasView,
- { useFactory: () => docInjector.createInstance(CanvasView, this._config.standalone ?? true) },
- ], // FIXME: CanvasView shouldn't be a dependency of DocPlugin. Because it maybe created dynamically.
+ // [
+ // CanvasView,
+ // { useFactory: () => docInjector.createInstance(CanvasView, this._config.standalone ?? true) },
+ // ], // FIXME: CanvasView shouldn't be a dependency of DocPlugin. Because it maybe created dynamically.
+ //views
+ [DocCanvasView],
+
+ // services
[IPlatformService, { useClass: DesktopPlatformService }],
- [DocumentController],
+ [DocSkeletonManagerService],
+ [
+ ITextSelectionRenderManager,
+ {
+ useClass: TextSelectionRenderManager,
+ },
+ ],
+ [TextSelectionManagerService],
+
+ // controllers
+ [DocRenderController],
+ [PageRenderController],
+ [TextSelectionController],
+ [NormalInputController],
+ [IMEInputController],
+ [DeleteLeftInputController],
+ [LineBreakInputController],
+ [MoveCursorController],
] as Dependency[]
).forEach((d) => docInjector.add(d));
diff --git a/packages/base-docs/src/View/CanvasView.ts b/packages/base-docs/src/View/CanvasView.ts
deleted file mode 100644
index 60032ead65..0000000000
--- a/packages/base-docs/src/View/CanvasView.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import {
- Documents,
- EVENT_TYPE,
- IRenderManagerService,
- IWheelEvent,
- Layer,
- RenderManagerService,
- ScrollBar,
- Viewport,
-} from '@univerjs/base-render';
-import { EventState, IConfigService, ICurrentUniverService } from '@univerjs/core';
-import { Inject, Injector } from '@wendellhu/redi';
-
-import {
- DOCS_COMPONENT_DEFAULT_Z_INDEX,
- DOCS_COMPONENT_HEADER_LAYER_INDEX,
- DOCS_COMPONENT_MAIN_LAYER_INDEX,
- DOCS_CONFIG_STANDALONE_KEY,
- DOCS_VIEW_KEY,
- VIEWPORT_KEY,
-} from '../Basics/docs-view-key';
-
-export class CanvasView {
- constructor(
- /** @deprecated This a temporary solution. CanvasView should not be a singleton. */
- private standalone = true,
- @IRenderManagerService private readonly _renderManagerService: RenderManagerService,
- @IConfigService private readonly _configService: IConfigService,
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
- // @IRenderingEngine private readonly _engine: Engine,
- @Inject(Injector) private readonly _injector: Injector
- ) {
- this._initialize();
- }
-
- getDocsView() {}
-
- private _initialize() {
- const { engine, scene } = this._getDocsObject()!;
-
- const viewMain = new Viewport(VIEWPORT_KEY.VIEW_MAIN, scene, {
- left: 0,
- top: 0,
- bottom: 0,
- right: 0,
- isWheelPreventDefaultX: true,
- });
-
- scene.addViewport(viewMain).attachControl();
-
- scene.on(EVENT_TYPE.wheel, (evt: unknown, state: EventState) => {
- const e = evt as IWheelEvent;
- if (e.ctrlKey) {
- const deltaFactor = Math.abs(e.deltaX);
- let scrollNum = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;
- scrollNum *= e.deltaY > 0 ? -1 : 1;
- if (scene.scaleX < 1) {
- scrollNum /= 2;
- }
-
- if (scene.scaleX + scrollNum > 4) {
- scene.scale(4, 4);
- } else if (scene.scaleX + scrollNum < 0.1) {
- scene.scale(0.1, 0.1);
- } else {
- const value = e.deltaY > 0 ? 0.1 : -0.1;
- // scene.scaleBy(scrollNum, scrollNum);
- e.preventDefault();
- }
- } else {
- viewMain.onMouseWheel(e, state);
- }
- });
-
- new ScrollBar(viewMain);
-
- scene.addLayer(
- Layer.create(scene, [], DOCS_COMPONENT_MAIN_LAYER_INDEX),
- Layer.create(scene, [], DOCS_COMPONENT_HEADER_LAYER_INDEX)
- );
-
- // this._viewLoader(scene);
- const documents = new Documents(DOCS_VIEW_KEY.MAIN);
- documents.zIndex = DOCS_COMPONENT_DEFAULT_Z_INDEX;
-
- scene.addObjects([documents], DOCS_COMPONENT_MAIN_LAYER_INDEX);
-
- if (this._getStandalone()) {
- engine.runRenderLoop(() => {
- scene.render();
- const app = document.getElementById('app');
- if (app) {
- app.innerText = `fps:${Math.round(engine.getFps()).toString()}`;
- }
- });
- }
- }
-
- private _getStandalone() {
- const unitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();
- return this._configService.getConfig(unitId, DOCS_CONFIG_STANDALONE_KEY) as boolean;
- }
-
- private _getDocsObject() {
- const unitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();
- const standalone = this._configService.getConfig(unitId, DOCS_CONFIG_STANDALONE_KEY) as boolean;
- if (standalone === true) {
- this._renderManagerService.createRenderWithNewEngine(unitId);
- } else {
- this._renderManagerService.createRenderWithDefaultEngine(unitId);
- }
-
- return this._renderManagerService.getRenderById(unitId);
- }
-}
diff --git a/packages/base-docs/src/View/Render/Views/DocsView.ts b/packages/base-docs/src/View/Render/Views/DocsView.ts
index 380c8a56f3..fbb6c7de0a 100644
--- a/packages/base-docs/src/View/Render/Views/DocsView.ts
+++ b/packages/base-docs/src/View/Render/Views/DocsView.ts
@@ -93,8 +93,8 @@ export class DocsView extends BaseView {
const documentSkeleton = this._buildSkeleton(docsModel);
const documents = new Documents(DOCS_VIEW_KEY.MAIN, documentSkeleton, {
- pageMarginLeft: docsModel.documentStyle.marginLeft,
- pageMarginTop: docsModel.documentStyle.marginTop,
+ pageMarginLeft: docsModel.documentStyle.marginLeft || 0,
+ pageMarginTop: docsModel.documentStyle.marginTop || 0,
});
documents.zIndex = 1000;
this._documentSkeleton = documentSkeleton;
diff --git a/packages/base-docs/src/View/doc-canvas-view.ts b/packages/base-docs/src/View/doc-canvas-view.ts
new file mode 100644
index 0000000000..39832a215f
--- /dev/null
+++ b/packages/base-docs/src/View/doc-canvas-view.ts
@@ -0,0 +1,162 @@
+import {
+ Documents,
+ EVENT_TYPE,
+ IRender,
+ IRenderManagerService,
+ IWheelEvent,
+ Layer,
+ RenderManagerService,
+ Scene,
+ ScrollBar,
+ Viewport,
+} from '@univerjs/base-render';
+import {
+ DocumentModel,
+ EventState,
+ IConfigService,
+ ICurrentUniverService,
+ LifecycleStages,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import {
+ DOCS_COMPONENT_DEFAULT_Z_INDEX,
+ DOCS_COMPONENT_HEADER_LAYER_INDEX,
+ DOCS_COMPONENT_MAIN_LAYER_INDEX,
+ DOCS_VIEW_KEY,
+ VIEWPORT_KEY,
+} from '../Basics/docs-view-key';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+
+@OnLifecycle(LifecycleStages.Ready, DocCanvasView)
+export class DocCanvasView {
+ private _scene!: Scene;
+
+ private _currentDocumentModel!: DocumentModel;
+ constructor(
+ @IRenderManagerService private readonly _renderManagerService: RenderManagerService,
+ @IConfigService private readonly _configService: IConfigService,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ // @IRenderingEngine private readonly _engine: Engine,
+ @Inject(Injector) private readonly _injector: Injector
+ ) {
+ this._currentUniverService.currentDoc$.subscribe((documentModel) => {
+ if (documentModel == null) {
+ throw new Error('documentModel is null');
+ }
+ this._currentDocumentModel = documentModel;
+ this._addNewRender();
+ });
+ }
+
+ private _addNewRender() {
+ const documentModel = this._currentDocumentModel;
+
+ const unitId = documentModel.getUnitId();
+
+ const container = documentModel.getContainer();
+
+ const parentRenderUnitId = documentModel.getParentRenderUnitId();
+
+ if (container != null && parentRenderUnitId != null) {
+ throw new Error('container or parentRenderUnitId can only exist one');
+ }
+
+ if (container == null && parentRenderUnitId != null) {
+ this._renderManagerService.createRenderWithParent(unitId, parentRenderUnitId);
+ } else {
+ this._renderManagerService.createRender(unitId);
+ }
+
+ this._renderManagerService.setCurrent(unitId);
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { scene, engine } = currentRender;
+
+ scene.openTransformer();
+
+ this._scene = scene;
+
+ const viewMain = new Viewport(VIEWPORT_KEY.VIEW_MAIN, scene, {
+ left: 0,
+ top: 0,
+ bottom: 0,
+ right: 0,
+ isWheelPreventDefaultX: true,
+ });
+
+ scene.addViewport(viewMain).attachControl();
+
+ scene.on(EVENT_TYPE.wheel, (evt: unknown, state: EventState) => {
+ const e = evt as IWheelEvent;
+ if (e.ctrlKey) {
+ const deltaFactor = Math.abs(e.deltaX);
+ let scrollNum = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;
+ scrollNum *= e.deltaY > 0 ? -1 : 1;
+ if (scene.scaleX < 1) {
+ scrollNum /= 2;
+ }
+
+ if (scene.scaleX + scrollNum > 4) {
+ scene.scale(4, 4);
+ } else if (scene.scaleX + scrollNum < 0.1) {
+ scene.scale(0.1, 0.1);
+ } else {
+ const value = e.deltaY > 0 ? 0.1 : -0.1;
+ // scene.scaleBy(scrollNum, scrollNum);
+ e.preventDefault();
+ }
+ } else {
+ viewMain.onMouseWheel(e, state);
+ }
+ });
+
+ new ScrollBar(viewMain);
+
+ scene.addLayer(
+ Layer.create(scene, [], DOCS_COMPONENT_MAIN_LAYER_INDEX),
+ Layer.create(scene, [], DOCS_COMPONENT_HEADER_LAYER_INDEX)
+ );
+
+ // this._viewLoader(scene);
+
+ this._addComponent(currentRender);
+
+ const should = this._currentDocumentModel.getShouldRenderLoopImmediately();
+ if (should) {
+ engine.runRenderLoop(() => {
+ scene.render();
+ // const app = document.getElementById('app');
+ // if (app) {
+ // app.innerText = `fps:${Math.round(engine.getFps()).toString()}`;
+ // }
+ });
+ }
+ }
+
+ private _addComponent(currentRender: IRender) {
+ const scene = this._scene;
+ const documentModel = this._currentDocumentModel;
+
+ const unitId = documentModel.getUnitId();
+ const documents = new Documents(DOCS_VIEW_KEY.MAIN, undefined, {
+ pageMarginLeft: documentModel.documentStyle.marginLeft || 0,
+ pageMarginTop: documentModel.documentStyle.marginTop || 0,
+ });
+ documents.zIndex = DOCS_COMPONENT_DEFAULT_Z_INDEX;
+
+ currentRender.mainComponent = documents;
+ currentRender.components.set(DOCS_VIEW_KEY.MAIN, documents);
+
+ scene.addObjects([documents], DOCS_COMPONENT_MAIN_LAYER_INDEX);
+
+ this._docSkeletonManagerService.setCurrent({ unitId });
+ }
+}
diff --git a/packages/base-docs/src/commands/commands/core-editing.command.ts b/packages/base-docs/src/commands/commands/core-editing.command.ts
index dc712369f9..1793fa554e 100644
--- a/packages/base-docs/src/commands/commands/core-editing.command.ts
+++ b/packages/base-docs/src/commands/commands/core-editing.command.ts
@@ -13,7 +13,6 @@ import {
UpdateDocsAttributeType,
} from '@univerjs/core';
-import { InputController } from '../../Controller/InputController';
import {
IDeleteMutationParams,
IRetainMutationParams,
@@ -24,21 +23,19 @@ import {
export const DeleteLeftCommand: ICommand = {
id: 'doc.command.delete-left',
type: CommandType.COMMAND,
- handler: async (accessor) => {
- const inputController = accessor.get(InputController);
- inputController.deleteLeft();
- return true;
- },
+ handler: async (accessor) =>
+ // const inputController = accessor.get(InputController);
+ // inputController.deleteLeft();
+ true,
};
export const BreakLineCommand: ICommand = {
id: 'doc.command.break-line',
type: CommandType.COMMAND,
- handler: async (accessor) => {
- const inputController = accessor.get(InputController);
- inputController.breakLine();
- return true;
- },
+ handler: async (accessor) =>
+ // const inputController = accessor.get(InputController);
+ // inputController.breakLine();
+ true,
};
export interface IInsertCommandParams {
@@ -250,7 +247,7 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
export interface IIMEInputCommandParams {
newText: string;
oldTextLen: number;
- start: number;
+ range: ITextSelectionRange;
segmentId?: string;
unitId: string;
}
@@ -261,7 +258,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
handler: async (accessor, params: IIMEInputCommandParams) => {
const commandService = accessor.get(ICommandService);
- const { unitId, newText, oldTextLen, start, segmentId } = params;
+ const { unitId, newText, oldTextLen, range, segmentId } = params;
const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
params: {
@@ -270,11 +267,17 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
},
};
- doMutation.params!.mutations.push({
- t: 'r',
- len: start + 1,
- segmentId,
- });
+ if (range.isCollapse) {
+ const start = getTextIndexByCursor(range.cursorStart, range.isStartBack);
+
+ doMutation.params!.mutations.push({
+ t: 'r',
+ len: start + 1,
+ segmentId,
+ });
+ } else {
+ doMutation.params!.mutations.push(...getRetainAndDeleteFromReplace(range, segmentId));
+ }
if (oldTextLen > 0) {
doMutation.params!.mutations.push({
diff --git a/packages/base-docs/src/commands/commands/doc-object.command.ts b/packages/base-docs/src/commands/commands/doc-object.command.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/base-docs/src/commands/commands/set-zoom-ratio.command.ts b/packages/base-docs/src/commands/commands/set-zoom-ratio.command.ts
new file mode 100644
index 0000000000..2de3a44337
--- /dev/null
+++ b/packages/base-docs/src/commands/commands/set-zoom-ratio.command.ts
@@ -0,0 +1,58 @@
+import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import {
+ ISetZoomRatioMutationParams,
+ SetZoomRatioMutation,
+ SetZoomRatioUndoMutationFactory,
+} from '../mutations/set-zoom-ratio.mutation';
+
+export interface ISetZoomRatioCommandParams {
+ zoomRatio?: number;
+ documentId?: string;
+}
+
+export const SetZoomRatioCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'doc.command.set-zoom-ratio',
+
+ handler: async (accessor: IAccessor, params?: ISetZoomRatioCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+
+ let documentId = currentUniverService.getCurrentUniverDocInstance().getUnitId();
+ let zoomRatio = 1;
+
+ if (params) {
+ documentId = params.documentId ?? documentId;
+ zoomRatio = params.zoomRatio ?? zoomRatio;
+ }
+
+ const workbook = currentUniverService.getUniverDocInstance(documentId);
+ if (!workbook) return false;
+
+ const setZoomRatioMutationParams: ISetZoomRatioMutationParams = {
+ zoomRatio,
+ documentId,
+ };
+
+ const undoMutationParams = SetZoomRatioUndoMutationFactory(accessor, setZoomRatioMutationParams);
+ const result = commandService.executeCommand(SetZoomRatioMutation.id, setZoomRatioMutationParams);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: documentId,
+ undo() {
+ return commandService.executeCommand(SetZoomRatioMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetZoomRatioMutation.id, setZoomRatioMutationParams);
+ },
+ });
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
index 2d92b8938c..740a4b1d77 100644
--- a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
@@ -63,20 +63,27 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
mutations.forEach((mutation) => {
if (mutation.t === 'r') {
const { coverType, body, len, segmentId } = mutation;
- const documentBody = UpdateAttributeApply(
- document,
- body,
- len,
- commonParameter.cursor,
- coverType,
- segmentId
- );
+ if (body != null) {
+ const documentBody = UpdateAttributeApply(
+ document,
+ body,
+ len,
+ commonParameter.cursor,
+ coverType,
+ segmentId
+ );
+ undoMutations.push({
+ ...mutation,
+ t: 'r',
+ coverType: UpdateDocsAttributeType.REPLACE,
+ body: documentBody,
+ });
+ }
+
commonParameter.moveCursor(len);
undoMutations.push({
...mutation,
t: 'r',
- coverType: UpdateDocsAttributeType.REPLACE,
- body: documentBody,
});
} else if (mutation.t === 'i') {
const { body, len, segmentId, line } = mutation;
diff --git a/packages/base-docs/src/commands/mutations/doc-object.mutation.ts b/packages/base-docs/src/commands/mutations/doc-object.mutation.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/base-docs/src/commands/mutations/set-zoom-ratio.mutation.ts b/packages/base-docs/src/commands/mutations/set-zoom-ratio.mutation.ts
new file mode 100644
index 0000000000..534955c80f
--- /dev/null
+++ b/packages/base-docs/src/commands/mutations/set-zoom-ratio.mutation.ts
@@ -0,0 +1,38 @@
+import { CommandType, ICurrentUniverService, IMutation, Tools } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetZoomRatioMutationParams {
+ zoomRatio: number;
+ documentId: string;
+}
+
+export const SetZoomRatioUndoMutationFactory = (
+ accessor: IAccessor,
+ params: ISetZoomRatioMutationParams
+): ISetZoomRatioMutationParams => {
+ const documentModel = accessor.get(ICurrentUniverService).getUniverDocInstance(params.documentId);
+ const old = documentModel?.getSettings()?.zoomRatio || 1;
+ return {
+ ...Tools.deepClone(params),
+ zoomRatio: old,
+ };
+};
+
+export const SetZoomRatioMutation: IMutation<ISetZoomRatioMutationParams> = {
+ id: 'doc.mutation.set-zoom-ratio',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const documentModel = accessor.get(ICurrentUniverService).getUniverDocInstance(params.documentId);
+ if (!documentModel) return false;
+ const documentData = documentModel.getSnapshot();
+ if (documentData.settings == null) {
+ documentData.settings = {
+ zoomRatio: params.zoomRatio,
+ };
+ } else {
+ documentData.settings.zoomRatio = params.zoomRatio;
+ }
+
+ return true;
+ },
+};
diff --git a/packages/base-docs/src/commands/operations/cursor.operation.ts b/packages/base-docs/src/commands/operations/cursor.operation.ts
index 105d5ef0e2..d9e4928b26 100644
--- a/packages/base-docs/src/commands/operations/cursor.operation.ts
+++ b/packages/base-docs/src/commands/operations/cursor.operation.ts
@@ -1,6 +1,4 @@
-import { CommandType, Direction, ICurrentUniverService, IOperation } from '@univerjs/core';
-
-import { InputController } from '../../Controller/InputController';
+import { CommandType, Direction, IOperation } from '@univerjs/core';
export interface IMoveCursorOperationParams {
direction: Direction;
@@ -19,10 +17,10 @@ export const MoveCursorOperation: IOperation<IMoveCursorOperationParams> = {
return false;
}
- const currentUniverService = accessor.get(ICurrentUniverService);
- const inputController = accessor.get(InputController);
+ // const currentUniverService = accessor.get(ICurrentUniverService);
+ // const inputController = accessor.get(InputController);
- inputController.moveCursor(currentUniverService.getCurrentUniverDocInstance(), params.direction);
+ // inputController.moveCursor(currentUniverService.getCurrentUniverDocInstance(), params.direction);
return true;
},
diff --git a/packages/base-docs/src/commands/operations/text-selection.operation.ts b/packages/base-docs/src/commands/operations/text-selection.operation.ts
new file mode 100644
index 0000000000..b595b9aab6
--- /dev/null
+++ b/packages/base-docs/src/commands/operations/text-selection.operation.ts
@@ -0,0 +1,22 @@
+// This file provide operations to change selection of sheets.
+
+import { ITextSelectionRangeWithStyle } from '@univerjs/base-render';
+import { CommandType, IOperation } from '@univerjs/core';
+
+import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
+
+export interface ISetTextSelectionsOperationParams {
+ unitId: string;
+ pluginName: string;
+ ranges: ITextSelectionRangeWithStyle[];
+}
+
+export const SetTextSelectionsOperation: IOperation<ISetTextSelectionsOperationParams> = {
+ id: 'doc.operation.set-selections',
+ type: CommandType.OPERATION,
+ handler: async (accessor, params) => {
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
+ textSelectionManagerService.replace(params!.ranges);
+ return true;
+ },
+};
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index 3745319254..ade9a5e688 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -1,3 +1,4 @@
+export * from './Basics/component-tools';
export {
CoverCommand,
DeleteCommand,
@@ -12,5 +13,7 @@ export {
} from './commands/commands/core-editing.command';
export * from './DocPlugin';
export * from './Locale';
+export { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
export { DocsViewManagerService } from './services/docs-view-manager/docs-view-manager.service';
+export { TextSelectionManagerService } from './services/text-selection-manager.service';
export { DocsView, DocsViewFactory } from './View/Render/Views/DocsView';
diff --git a/packages/base-docs/src/services/doc-skeleton-manager.service.ts b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
new file mode 100644
index 0000000000..3e0e7be6f9
--- /dev/null
+++ b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
@@ -0,0 +1,108 @@
+import { DocumentSkeleton } from '@univerjs/base-render';
+import { DocumentModel, ICurrentUniverService, LocaleService, Nullable } from '@univerjs/core';
+import { IDisposable, Inject } from '@wendellhu/redi';
+import { BehaviorSubject } from 'rxjs';
+
+export interface IDocSkeletonManagerParam {
+ unitId: string;
+ skeleton: DocumentSkeleton;
+ dirty: boolean;
+}
+
+export interface IDocSkeletonManagerSearch {
+ unitId: string;
+}
+
+/**
+ * This service is for worksheet build sheet skeleton.
+ */
+export class DocSkeletonManagerService implements IDisposable {
+ private _currentSkeleton: IDocSkeletonManagerSearch = {
+ unitId: '',
+ };
+
+ private _docSkeletonParam: IDocSkeletonManagerParam[] = [];
+
+ private readonly _currentSkeleton$ = new BehaviorSubject<Nullable<IDocSkeletonManagerParam>>(null);
+
+ readonly currentSkeleton$ = this._currentSkeleton$.asObservable();
+
+ /**
+ * CurrentSkeletonBefore for pre-triggered logic during registration
+ */
+ private readonly _currentSkeletonBefore$ = new BehaviorSubject<Nullable<IDocSkeletonManagerParam>>(null);
+
+ readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();
+
+ constructor(
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {}
+
+ dispose(): void {
+ this._currentSkeletonBefore$.complete();
+ this._currentSkeleton$.complete();
+ this._docSkeletonParam = [];
+ }
+
+ getCurrent(): Nullable<IDocSkeletonManagerParam> {
+ return this._getCurrentBySearch(this._currentSkeleton);
+ }
+
+ setCurrent(searchParm: IDocSkeletonManagerSearch): Nullable<IDocSkeletonManagerParam> {
+ const param = this._getCurrentBySearch(searchParm);
+ if (param != null) {
+ if (param.dirty) {
+ param.skeleton.makeDirty(true);
+ param.dirty = false;
+ }
+ param.skeleton.calculate();
+ } else {
+ const { unitId } = searchParm;
+
+ const documentModel = this._currentUniverService.getUniverDocInstance(searchParm.unitId);
+
+ if (documentModel == null || documentModel.bodyModel == null) {
+ return;
+ }
+
+ const skeleton = this._buildSkeleton(documentModel);
+
+ skeleton.calculate();
+
+ this._docSkeletonParam.push({
+ unitId,
+ skeleton,
+ dirty: false,
+ });
+ }
+
+ this._currentSkeleton = searchParm;
+
+ this._currentSkeletonBefore$.next(this.getCurrent());
+
+ this._currentSkeleton$.next(this.getCurrent());
+
+ return this.getCurrent();
+ }
+
+ makeDirtyCurrent(state: boolean = true) {
+ this.makeDirty(this._currentSkeleton, state);
+ }
+
+ makeDirty(searchParm: IDocSkeletonManagerSearch, state: boolean = true) {
+ const param = this._getCurrentBySearch(searchParm);
+ if (param == null) {
+ return;
+ }
+ param.dirty = state;
+ }
+
+ private _getCurrentBySearch(searchParm: IDocSkeletonManagerSearch): Nullable<IDocSkeletonManagerParam> {
+ return this._docSkeletonParam.find((param) => param.unitId === searchParm.unitId);
+ }
+
+ private _buildSkeleton(documentModel: DocumentModel) {
+ return DocumentSkeleton.create(documentModel, this._localeService);
+ }
+}
diff --git a/packages/base-docs/src/services/docs-skeleton-manager.service.ts b/packages/base-docs/src/services/docs-skeleton-manager.service.ts
deleted file mode 100644
index cb357516d1..0000000000
--- a/packages/base-docs/src/services/docs-skeleton-manager.service.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { DocumentSkeleton } from '@univerjs/base-render';
-import { Nullable } from '@univerjs/core';
-import { IDisposable } from '@wendellhu/redi';
-import { BehaviorSubject } from 'rxjs';
-
-/**
- * This service is for worksheet build sheet skeleton.
- */
-export class DocsSkeletonManagerService implements IDisposable {
- private _currentSkeleton: Nullable<DocumentSkeleton> = null;
-
- private readonly _currentSkeleton$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(this._currentSkeleton);
-
- readonly currentSkeleton$ = this._currentSkeleton$.asObservable();
-
- /**
- * CurrentSkeletonBefore for pre-triggered logic during registration
- */
- private readonly _currentSkeletonBefore$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(this._currentSkeleton);
-
- readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();
-
- dispose(): void {
- this._currentSkeletonBefore$.complete();
- this._currentSkeleton$.complete();
- }
-
- getCurrent(): Nullable<DocumentSkeleton> {
- return this._currentSkeleton;
- }
-
- setCurrent(skeleton: DocumentSkeleton) {
- this._currentSkeleton = skeleton;
-
- this._currentSkeletonBefore$.next(this.getCurrent());
-
- this._currentSkeleton$.next(this.getCurrent());
- }
-}
diff --git a/packages/base-docs/src/services/text-selection-manager.service.ts b/packages/base-docs/src/services/text-selection-manager.service.ts
new file mode 100644
index 0000000000..295d8f7648
--- /dev/null
+++ b/packages/base-docs/src/services/text-selection-manager.service.ts
@@ -0,0 +1,257 @@
+import { ISelectionStyle, ITextSelectionRangeWithStyle } from '@univerjs/base-render';
+import { ISelectionCell, Nullable } from '@univerjs/core';
+import { IDisposable } from '@wendellhu/redi';
+import { BehaviorSubject } from 'rxjs';
+
+export const NORMAL_TEXT_SELECTION_PLUGIN_NAME = 'normalTextSelectionPluginName';
+
+export interface ITextSelectionManagerSearchParam {
+ pluginName: string;
+ unitId: string;
+}
+
+export interface ITextSelectionManagerInsertParam extends ITextSelectionManagerSearchParam {
+ textRanges: ITextSelectionRangeWithStyle[];
+}
+
+//{ [pluginName: string]: { [unitId: string]: ITextSelectionRangeWithStyle[] } }
+export type ITextSelectionInfo = Map<string, Map<string, ITextSelectionRangeWithStyle[]>>;
+
+/**
+ * This service is for selection.
+ */
+export class TextSelectionManagerService implements IDisposable {
+ private readonly _textSelectionInfo: ITextSelectionInfo = new Map();
+
+ private _currentSelection: Nullable<ITextSelectionManagerSearchParam> = null;
+
+ private readonly _textSelectionInfo$ = new BehaviorSubject<Nullable<ITextSelectionRangeWithStyle[]>>(null);
+
+ readonly textSelectionInfo$ = this._textSelectionInfo$.asObservable();
+
+ reset() {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._currentSelection = {
+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ unitId: this._currentSelection?.unitId,
+ };
+ this._textSelectionInfo.clear();
+
+ this.refresh(this._currentSelection);
+ }
+
+ resetPlugin() {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._currentSelection.pluginName = NORMAL_TEXT_SELECTION_PLUGIN_NAME;
+
+ this.refresh(this._currentSelection);
+ }
+
+ dispose(): void {
+ this._textSelectionInfo$.complete();
+ }
+
+ refreshSelection() {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this.refresh(this._currentSelection);
+ }
+
+ setCurrentSelection(param: ITextSelectionManagerSearchParam) {
+ this._currentSelection = param;
+
+ this.refresh(param);
+ }
+
+ setCurrentSelectionNotRefresh(param: ITextSelectionManagerSearchParam) {
+ this._currentSelection = param;
+ }
+
+ getTextSelectionInfo(): Readonly<ITextSelectionInfo> {
+ return this._textSelectionInfo;
+ }
+
+ getTextRangesByParam(
+ param: Nullable<ITextSelectionManagerSearchParam>
+ ): Readonly<Nullable<ITextSelectionRangeWithStyle[]>> {
+ return this._getTextRanges(param);
+ }
+
+ getSelections(): Readonly<Nullable<ITextSelectionRangeWithStyle[]>> {
+ return this._getTextRanges(this._currentSelection);
+ }
+
+ getFirst(): Readonly<Nullable<ITextSelectionRangeWithStyle>> {
+ return this._getFirstByParam(this._currentSelection);
+ }
+
+ getLast(): Readonly<Nullable<ITextSelectionRangeWithStyle & { primary: ISelectionCell }>> {
+ // The last selection position must have a primary.
+ return this._getLastByParam(this._currentSelection) as Readonly<
+ Nullable<ITextSelectionRangeWithStyle & { primary: ISelectionCell }>
+ >;
+ }
+
+ add(textRanges: ITextSelectionRangeWithStyle[]) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._addByParam({
+ ...this._currentSelection,
+ textRanges,
+ });
+ }
+
+ replace(textRanges: ITextSelectionRangeWithStyle[]) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._replaceByParam({
+ ...this._currentSelection,
+ textRanges,
+ });
+ this.refresh(this._currentSelection);
+ }
+
+ replaceWithNoRefresh(textRanges: ITextSelectionRangeWithStyle[]) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._replaceByParam({
+ ...this._currentSelection,
+ textRanges,
+ });
+ }
+
+ clear(): void {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._clearByParam(this._currentSelection);
+ }
+
+ remove(index: number): void {
+ if (this._currentSelection == null) {
+ return;
+ }
+
+ this._removeByParam(index, this._currentSelection);
+ }
+
+ createDefaultAutoFillSelection(): ISelectionStyle {
+ return {
+ strokeWidth: 2,
+ stroke: '#FFF000',
+ fill: 'rgba(0, 0, 0, 0.2)',
+ widgets: {},
+ hasAutoFill: true,
+ };
+ }
+
+ createCopyPasteSelection(): ISelectionStyle {
+ return {
+ strokeWidth: 2,
+ stroke: '#FFF000',
+ fill: 'rgba(0, 0, 0, 0.2)',
+ widgets: {},
+ hasAutoFill: false,
+ };
+ }
+
+ createDefaultSelection(): ISelectionStyle {
+ return {
+ strokeWidth: 2,
+ stroke: '#FFF000',
+ fill: 'rgba(0, 0, 0, 0.2)',
+ widgets: { tr: true, tl: true, br: true, bl: true },
+ hasAutoFill: false,
+ };
+ }
+
+ private _getTextRanges(param: Nullable<ITextSelectionManagerSearchParam>) {
+ if (param == null) {
+ return;
+ }
+ const { pluginName, unitId } = param;
+ return this._textSelectionInfo.get(pluginName)?.get(unitId);
+ }
+
+ private refresh(param: ITextSelectionManagerSearchParam): void {
+ this._textSelectionInfo$.next(this._getTextRanges(param));
+ }
+
+ private _getFirstByParam(
+ param: Nullable<ITextSelectionManagerSearchParam>
+ ): Readonly<Nullable<ITextSelectionRangeWithStyle>> {
+ const textRange = this._getTextRanges(param);
+
+ return textRange?.[0];
+ }
+
+ private _getLastByParam(
+ param: Nullable<ITextSelectionManagerSearchParam>
+ ): Readonly<Nullable<ITextSelectionRangeWithStyle>> {
+ const textRange = this._getTextRanges(param);
+
+ return textRange?.[textRange.length - 1];
+ }
+
+ private _addByParam(insertParam: ITextSelectionManagerInsertParam): void {
+ const { pluginName, unitId, textRanges } = insertParam;
+
+ if (!this._textSelectionInfo.has(pluginName)) {
+ this._textSelectionInfo.set(pluginName, new Map());
+ }
+
+ const unitTextRange = this._textSelectionInfo.get(pluginName)!;
+
+ if (!unitTextRange.has(unitId)) {
+ unitTextRange.set(unitId, [...textRanges]);
+ } else {
+ const OldTextRanges = unitTextRange.get(unitId)!;
+ OldTextRanges.push(...textRanges);
+ }
+
+ this.refresh({ pluginName, unitId });
+ }
+
+ private _replaceByParam(insertParam: ITextSelectionManagerInsertParam) {
+ const { pluginName, unitId, textRanges } = insertParam;
+
+ if (!this._textSelectionInfo.has(pluginName)) {
+ this._textSelectionInfo.set(pluginName, new Map());
+ }
+
+ const unitTextRange = this._textSelectionInfo.get(pluginName)!;
+
+ if (!unitTextRange.has(unitId)) {
+ unitTextRange.set(unitId, textRanges);
+ } else {
+ const OldTextRanges = unitTextRange.get(unitId)!;
+ OldTextRanges.splice(0, OldTextRanges.length, ...textRanges);
+ }
+
+ // this.refresh({ pluginName, unitId, sheetId });
+ }
+
+ private _clearByParam(param: ITextSelectionManagerSearchParam): void {
+ const textRange = this._getTextRanges(param);
+
+ textRange?.splice(0);
+
+ this.refresh(param);
+ }
+
+ private _removeByParam(index: number, param: ITextSelectionManagerSearchParam): void {
+ const textRange = this._getTextRanges(param);
+
+ textRange?.splice(index, 1);
+
+ this.refresh(param);
+ }
+}
diff --git a/packages/base-render/src/Basics/Draw.ts b/packages/base-render/src/Basics/Draw.ts
index b28f6a32cf..eeccfcc0b5 100644
--- a/packages/base-render/src/Basics/Draw.ts
+++ b/packages/base-render/src/Basics/Draw.ts
@@ -3,8 +3,40 @@ import { BorderStyleTypes, IPosition } from '@univerjs/core';
import { BORDER_TYPE, ORIENTATION_TYPE } from './Const';
import { IDocumentSkeletonLine } from './IDocumentSkeletonCached';
+import { createCanvasElement } from './Tools';
import { Vector2 } from './Vector2';
+export interface IContext2D extends CanvasRenderingContext2D {
+ webkitBackingStorePixelRatio: number;
+ mozBackingStorePixelRatio: number;
+ msBackingStorePixelRatio: number;
+ oBackingStorePixelRatio: number;
+ backingStorePixelRatio: number;
+}
+
+// calculate pixel ratio
+export function getDevicePixelRatio(): number {
+ let _pixelRatio: number = 1;
+ const canvas = createCanvasElement();
+ const context = canvas.getContext('2d') as IContext2D;
+ _pixelRatio = (() => {
+ const devicePixelRatio = window.devicePixelRatio || 1;
+ const backingStoreRatio =
+ context.webkitBackingStorePixelRatio ||
+ context.mozBackingStorePixelRatio ||
+ context.msBackingStorePixelRatio ||
+ context.oBackingStorePixelRatio ||
+ context.backingStorePixelRatio ||
+ 1;
+ return devicePixelRatio / backingStoreRatio;
+ })();
+
+ if (_pixelRatio < 1) {
+ return 1;
+ }
+ return Math.ceil(_pixelRatio * 10) / 10;
+}
+
export function drawLineByBorderType(ctx: CanvasRenderingContext2D, type: BORDER_TYPE, position: IPosition) {
let drawStartX = 0;
let drawStartY = 0;
@@ -32,12 +64,64 @@ export function drawLineByBorderType(ctx: CanvasRenderingContext2D, type: BORDER
drawEndX = endX;
drawEndY = endY;
}
+
+ // ctx.clearRect(drawStartX - 1, drawStartY - 1, drawEndX - drawStartX + 2, drawEndY - drawStartY + 2);
ctx.beginPath();
ctx.moveTo(drawStartX, drawStartY);
ctx.lineTo(drawEndX, drawEndY);
ctx.stroke();
}
+export function clearLineByBorderType(
+ ctx: CanvasRenderingContext2D,
+ type: BORDER_TYPE,
+ position: IPosition,
+ scaleX: number,
+ scaleY: number
+) {
+ let drawStartX = 0;
+ let drawStartY = 0;
+ let drawEndX = 0;
+ let drawEndY = 0;
+ const { startX, startY, endX, endY } = position;
+ if (type === BORDER_TYPE.TOP) {
+ drawStartX = startX;
+ drawStartY = startY;
+ drawEndX = endX;
+ drawEndY = startY;
+ } else if (type === BORDER_TYPE.BOTTOM) {
+ drawStartX = startX;
+ drawStartY = endY;
+ drawEndX = endX;
+ drawEndY = endY;
+ } else if (type === BORDER_TYPE.LEFT) {
+ drawStartX = startX;
+ drawStartY = startY;
+ drawEndX = startX;
+ drawEndY = endY;
+ } else if (type === BORDER_TYPE.RIGHT) {
+ drawStartX = endX;
+ drawStartY = startY;
+ drawEndX = endX;
+ drawEndY = endY;
+ }
+
+ ctx.beginPath();
+ ctx.strokeStyle = 'rgb(255,255,255)';
+ ctx.lineWidth = 1.5 / Math.max(scaleX, scaleY);
+ ctx.moveTo(drawStartX, drawStartY);
+ ctx.lineTo(drawEndX, drawEndY);
+ ctx.stroke();
+
+ // ctx.beginPath();
+ // ctx.clearRect(
+ // drawStartX - 1 / scaleX,
+ // drawStartY - 1 / scaleY,
+ // drawEndX - drawStartX + 2 / scaleX,
+ // drawEndY - drawStartY + 2 / scaleY
+ // );
+}
+
export function setLineType(ctx: CanvasRenderingContext2D, style: BorderStyleTypes) {
if (style === BorderStyleTypes.HAIR) {
ctx.setLineDash([1, 2]);
@@ -58,17 +142,26 @@ export function setLineType(ctx: CanvasRenderingContext2D, style: BorderStyleTyp
}
}
+export function getLineOffset() {
+ const ratio = getLineWith(1);
+ return ratio - Math.floor(ratio);
+}
+
+export function getLineWith(width: number) {
+ return Math.ceil((width / getDevicePixelRatio()) * 100) / 100;
+}
+
export function getLineWidth(style: BorderStyleTypes) {
- let lineWidth = 1;
+ let lineWidth = getLineWith(1);
if (
style === BorderStyleTypes.MEDIUM ||
style === BorderStyleTypes.MEDIUM_DASH_DOT ||
style === BorderStyleTypes.MEDIUM_DASHED ||
style === BorderStyleTypes.MEDIUM_DASH_DOT_DOT
) {
- lineWidth = 2;
+ lineWidth = getLineWith(2);
} else if (style === BorderStyleTypes.THICK) {
- lineWidth = 3;
+ lineWidth = getLineWith(3);
}
return lineWidth;
@@ -238,8 +331,10 @@ export function getRotateOffsetAndFarthestHypotenuse(
* @param pixelRatio devicePixelRatio
* @returns
*/
-export function getTranslateInSpreadContextWithPixelRatio(pixelRatio: number) {
- const pixelRatioPlusFix = pixelRatio + 0.5;
- const ceilPixelRatio = Math.ceil(pixelRatioPlusFix);
- return ceilPixelRatio - pixelRatioPlusFix;
+export function getTranslateInSpreadContextWithPixelRatio() {
+ const offset = 0.5 - getLineOffset();
+ return {
+ left: offset,
+ top: offset,
+ };
}
diff --git a/packages/base-render/src/Basics/Interfaces.ts b/packages/base-render/src/Basics/Interfaces.ts
index 748dc5f9c4..8f230ea120 100644
--- a/packages/base-render/src/Basics/Interfaces.ts
+++ b/packages/base-render/src/Basics/Interfaces.ts
@@ -30,6 +30,7 @@ export interface IObjectFullState extends ITransformState {
zIndex?: number;
isTransformer?: boolean;
forceRender?: boolean;
+ debounceParentDirty?: boolean;
}
export interface IRect extends ISize, IOffset {
diff --git a/packages/base-render/src/Basics/TextSelection.ts b/packages/base-render/src/Basics/TextSelection.ts
new file mode 100644
index 0000000000..f828131c11
--- /dev/null
+++ b/packages/base-render/src/Basics/TextSelection.ts
@@ -0,0 +1,19 @@
+import { ITextSelectionRangeParam } from '@univerjs/core';
+
+export interface ITextSelectionStyle {
+ strokeWidth: number;
+ stroke: string;
+ strokeActive: string;
+ fill: string;
+}
+
+export const NORMAL_TEXT_SELECTION_PLUGIN_STYLE: ITextSelectionStyle = {
+ strokeWidth: 1,
+ stroke: 'rgba(0,0,0, 0)',
+ strokeActive: 'rgba(0,0,0, 1)',
+ fill: 'rgba(0, 0, 0, 0.2)',
+};
+
+export interface ITextSelectionRangeWithStyle extends ITextSelectionRangeParam {
+ style: ITextSelectionStyle;
+}
diff --git a/packages/base-render/src/Basics/index.ts b/packages/base-render/src/Basics/index.ts
index 6ee48f80ba..e2f936406b 100644
--- a/packages/base-render/src/Basics/index.ts
+++ b/packages/base-render/src/Basics/index.ts
@@ -9,6 +9,7 @@ export * from './Path2';
export * from './PerformanceMonitor';
export * from './ScrollXY';
export * from './Selection';
+export * from './TextSelection';
export * from './Tools';
export * from './Transform';
export * from './Vector2';
diff --git a/packages/base-render/src/Canvas.ts b/packages/base-render/src/Canvas.ts
index 3e41c3592e..61e2497121 100644
--- a/packages/base-render/src/Canvas.ts
+++ b/packages/base-render/src/Canvas.ts
@@ -1,36 +1,6 @@
+import { getDevicePixelRatio } from './Basics/Draw';
import { createCanvasElement } from './Basics/Tools';
-export interface IContext2D extends CanvasRenderingContext2D {
- webkitBackingStorePixelRatio: number;
- mozBackingStorePixelRatio: number;
- msBackingStorePixelRatio: number;
- oBackingStorePixelRatio: number;
- backingStorePixelRatio: number;
-}
-
-// calculate pixel ratio
-export function getDevicePixelRatio(): number {
- let _pixelRatio: number = 1;
- const canvas = createCanvasElement();
- const context = canvas.getContext('2d') as IContext2D;
- _pixelRatio = (() => {
- const devicePixelRatio = window.devicePixelRatio || 1;
- const backingStoreRatio =
- context.webkitBackingStorePixelRatio ||
- context.mozBackingStorePixelRatio ||
- context.msBackingStorePixelRatio ||
- context.oBackingStorePixelRatio ||
- context.backingStorePixelRatio ||
- 1;
- return devicePixelRatio / backingStoreRatio;
- })();
-
- if (_pixelRatio < 1) {
- return 1;
- }
- return Math.ceil(_pixelRatio * 10) / 10;
-}
-
interface ICanvasProps {
width?: number;
height?: number;
@@ -111,7 +81,7 @@ export class Canvas {
setSize(width?: number, height?: number, pixelRatioParam?: number) {
// this.setWidth(width || 0);
// this.setHeight(height || 0);
- this._pixelRatio = Math.ceil(pixelRatioParam || getDevicePixelRatio());
+ this._pixelRatio = pixelRatioParam || getDevicePixelRatio();
if (width) {
this._width = width;
this._canvasEle.width = width * this._pixelRatio;
diff --git a/packages/base-render/src/Component/Docs/Common/TextSelection.ts b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
index 9f0a018782..90873ba244 100644
--- a/packages/base-render/src/Component/Docs/Common/TextSelection.ts
+++ b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
@@ -1,112 +1,70 @@
-import { IPosition, ITextSelectionRange, Nullable, Tools } from '@univerjs/core';
+import { ITextSelectionRange, Nullable, Tools } from '@univerjs/core';
import { COLORS } from '../../../Basics/Const';
-import {
- IDocumentSkeletonColumn,
- IDocumentSkeletonDivide,
- IDocumentSkeletonLine,
- IDocumentSkeletonPage,
- IDocumentSkeletonSection,
- SpanType,
-} from '../../../Basics/IDocumentSkeletonCached';
import { INodePosition } from '../../../Basics/Interfaces';
+import {
+ ITextSelectionRangeWithStyle,
+ ITextSelectionStyle,
+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+} from '../../../Basics/TextSelection';
import { getColor } from '../../../Basics/Tools';
import { IPoint } from '../../../Basics/Vector2';
+import { Scene } from '../../../Scene';
import { Rect } from '../../../Shape/Rect';
import { RegularPolygon } from '../../../Shape/RegularPolygon';
import { ThinScene } from '../../../ThinScene';
-import { DocComponent } from '../DocComponent';
-import { Liquid } from './Liquid';
+import { DocumentSkeleton } from '../DocSkeleton';
+import { IDocumentOffsetConfig } from '../Document';
+import {
+ compareNodePosition,
+ getOneTextSelectionRange,
+ NodePositionConvertToCursor,
+ NodePositionMap,
+} from './convert-cursor';
-enum NodePositionStateType {
- NORMAL,
- START,
- END,
-}
+const TEXT_RANGE_KEY_PREFIX = '__TestSelectionRange__';
-enum NodePositionType {
- page,
- section,
- column,
- line,
- divide,
- span,
-}
+const TEXT_ANCHOR_KEY_PREFIX = '__TestSelectionAnchor__';
-const NodePositionMap = {
- page: 0,
- section: 1,
- column: 2,
- line: 3,
- divide: 4,
- span: 5,
-};
-
-interface ICurrentNodePositionState {
- page: NodePositionStateType;
- section: NodePositionStateType;
- column: NodePositionStateType;
- line: NodePositionStateType;
- divide: NodePositionStateType;
- span: NodePositionStateType;
-}
+export function cursorConvertToTextSelection(
+ scene: Scene,
+ range: ITextSelectionRangeWithStyle,
+ docSkeleton: DocumentSkeleton,
+ documentOffsetConfig: IDocumentOffsetConfig
+): Nullable<TextSelection> {
+ const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, style } = range;
+
+ const startNode = docSkeleton.findNodePositionByCharIndex(cursorStart, isStartBack);
+ let endNode;
+ if (isCollapse !== true) {
+ endNode = docSkeleton.findNodePositionByCharIndex(cursorEnd, isEndBack);
+ }
-const TEXT_RANGE_KEY_PREFIX = '__TestSelectionRange__';
+ const textSelection = new TextSelection(scene, startNode, endNode, style);
-const TEXT_ANCHOR_KEY_PREFIX = '__TestSelectionAnchor__';
+ textSelection.refresh(documentOffsetConfig, docSkeleton);
+
+ return textSelection;
+}
export class TextSelection {
private _current = false;
- private _Liquid = new Liquid();
-
private _rangeShape: Nullable<RegularPolygon>;
private _anchorShape: Nullable<Rect>;
private _rangeList: ITextSelectionRange[] = [];
- private _currentStartState: ICurrentNodePositionState = {
- page: NodePositionStateType.NORMAL,
- section: NodePositionStateType.NORMAL,
- column: NodePositionStateType.NORMAL,
- line: NodePositionStateType.NORMAL,
- divide: NodePositionStateType.NORMAL,
- span: NodePositionStateType.NORMAL,
- };
-
- private _currentEndState: ICurrentNodePositionState = {
- page: NodePositionStateType.NORMAL,
- section: NodePositionStateType.NORMAL,
- column: NodePositionStateType.NORMAL,
- line: NodePositionStateType.NORMAL,
- divide: NodePositionStateType.NORMAL,
- span: NodePositionStateType.NORMAL,
- };
-
constructor(
private _scene: ThinScene,
public startNodePosition?: Nullable<INodePosition>,
public endNodePosition?: Nullable<INodePosition>,
- public segmentId?: string
+ private _style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE
) {}
- getRange() {
- const cursorList = this._rangeList;
-
- const firstCursor = cursorList[0];
-
- const lastCursor = cursorList[cursorList.length - 1];
-
- const isCollapse = cursorList.length === 1 && firstCursor.isCollapse;
-
- return {
- cursorStart: firstCursor.cursorStart,
- cursorEnd: lastCursor.cursorEnd,
- isStartBack: firstCursor.isStartBack,
- isEndBack: lastCursor.isEndBack,
- isCollapse,
- };
+ getRange(): Nullable<ITextSelectionRange> {
+ return getOneTextSelectionRange(this._rangeList);
}
getRangeList() {
@@ -119,13 +77,13 @@ export class TextSelection {
activeStatic() {
this._anchorShape?.setProps({
- stroke: getColor(COLORS.black, 1),
+ stroke: this._style?.strokeActive || getColor(COLORS.black, 1),
});
}
deactivateStatic() {
this._anchorShape?.setProps({
- stroke: getColor(COLORS.black, 0),
+ stroke: this._style?.stroke || getColor(COLORS.black, 0),
});
}
@@ -185,6 +143,10 @@ export class TextSelection {
const compareRange = textSelection.getRange();
+ if (compareRange == null || activeRange == null) {
+ return false;
+ }
+
const activeStart = this._getCursorPosition(activeRange.cursorStart, activeRange.isStartBack);
const activeEnd = this._getCursorPosition(activeRange.cursorEnd, activeRange.isEndBack);
@@ -200,7 +162,7 @@ export class TextSelection {
return true;
}
- refresh(documents: DocComponent) {
+ refresh(documentOffsetConfig: IDocumentOffsetConfig, docSkeleton: DocumentSkeleton) {
const start = this.startNodePosition;
const end = this.endNodePosition;
@@ -212,18 +174,22 @@ export class TextSelection {
return;
}
+ const { docsLeft, docsTop } = documentOffsetConfig;
+
+ const convert = new NodePositionConvertToCursor(documentOffsetConfig, docSkeleton);
+
if (this.isCollapsed()) {
- const data = this._getRangePointData(start!, start!, documents);
+ const data = convert.getRangePointData(start, start);
const { pointGroup, cursorList } = data;
this._setRangeList(cursorList);
- pointGroup.length > 0 && this._createAndUpdateAnchor(pointGroup, documents.left, documents.top);
+ pointGroup.length > 0 && this._createAndUpdateAnchor(pointGroup, docsLeft, docsTop);
return;
}
- const data = this._getRangePointData(start!, end!, documents);
+ const data = convert.getRangePointData(start, end);
const { pointGroup, cursorList } = data;
this._setRangeList(cursorList);
- pointGroup.length > 0 && this._createAndUpdateRange(pointGroup, documents.left, documents.top);
+ pointGroup.length > 0 && this._createAndUpdateRange(pointGroup, docsLeft, docsTop);
}
getStart() {
@@ -235,7 +201,7 @@ export class TextSelection {
return this.startNodePosition;
}
- const { start } = this._compareNodePosition(this.startNodePosition, this.endNodePosition);
+ const { start } = compareNodePosition(this.startNodePosition, this.endNodePosition);
return start;
}
@@ -249,213 +215,11 @@ export class TextSelection {
return null;
}
- const { end } = this._compareNodePosition(this.startNodePosition, this.endNodePosition);
+ const { end } = compareNodePosition(this.startNodePosition, this.endNodePosition);
return end;
}
- private _resetCurrentNodePositionState() {
- this._currentStartState = {
- page: NodePositionStateType.NORMAL,
- section: NodePositionStateType.NORMAL,
- column: NodePositionStateType.NORMAL,
- line: NodePositionStateType.NORMAL,
- divide: NodePositionStateType.NORMAL,
- span: NodePositionStateType.NORMAL,
- };
-
- this._currentEndState = {
- page: NodePositionStateType.NORMAL,
- section: NodePositionStateType.NORMAL,
- column: NodePositionStateType.NORMAL,
- line: NodePositionStateType.NORMAL,
- divide: NodePositionStateType.NORMAL,
- span: NodePositionStateType.NORMAL,
- };
- }
-
- private _compareNodePositionLogic(pos1: INodePosition, pos2: INodePosition) {
- if (pos1.page > pos2.page) {
- return false;
- }
-
- if (pos1.page < pos2.page) {
- return true;
- }
-
- if (pos1.section > pos2.section) {
- return false;
- }
-
- if (pos1.section < pos2.section) {
- return true;
- }
-
- if (pos1.column > pos2.column) {
- return false;
- }
-
- if (pos1.column < pos2.column) {
- return true;
- }
-
- if (pos1.line > pos2.line) {
- return false;
- }
-
- if (pos1.line < pos2.line) {
- return true;
- }
-
- if (pos1.divide > pos2.divide) {
- return false;
- }
-
- if (pos1.divide < pos2.divide) {
- return true;
- }
-
- if (pos1.span > pos2.span) {
- return false;
- }
-
- if (pos1.span < pos2.span) {
- return true;
- }
-
- return true;
- }
-
- private _compareNodePosition(pos1: INodePosition, pos2: INodePosition) {
- const compare = this._compareNodePositionLogic(pos1, pos2);
- if (compare) {
- return {
- start: pos1,
- end: pos2,
- };
- }
- return {
- start: pos2,
- end: pos1,
- };
- }
-
- private _setNodePositionState(type = NodePositionType.page, start: number, end: number, current: number) {
- if (current === start) {
- this._currentStartState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.START;
- } else {
- this._currentStartState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.NORMAL;
- }
-
- if (current === end) {
- this._currentEndState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.END;
- } else {
- this._currentEndState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.NORMAL;
- }
- }
-
- private _checkPreviousNodePositionState(typeIndex: number, isStart = true) {
- let index = typeIndex;
- let resultState: Nullable<NodePositionStateType>;
- while (index >= 0) {
- const type = NodePositionType[index] as keyof ICurrentNodePositionState;
- let state;
- if (isStart) {
- state = this._currentStartState[type];
- } else {
- state = this._currentEndState[type];
- }
-
- if (state === undefined) {
- return;
- }
- if (resultState === undefined) {
- resultState = state;
- }
- if (state !== resultState) {
- return NodePositionStateType.NORMAL;
- }
-
- index--;
- }
-
- return resultState;
- }
-
- private _getSelectionRuler(
- typeIndex: number,
- startPosition: INodePosition,
- endPosition: INodePosition,
- nextLength: number,
- current: number
- ) {
- let start_next = 0;
- let end_next = nextLength;
-
- const type = NodePositionType[typeIndex] as keyof INodePosition;
-
- const nextType = NodePositionType[typeIndex + 1] as keyof INodePosition;
-
- if (nextType === null || type === null) {
- return {
- start_next,
- end_next,
- };
- }
-
- const start = startPosition[type] as number;
-
- const end = endPosition[type] as number;
-
- this._setNodePositionState(type as unknown as NodePositionType, start, end, current);
-
- const preStartNestType = this._checkPreviousNodePositionState(typeIndex);
-
- const preEndNestType = this._checkPreviousNodePositionState(typeIndex, false);
-
- if (preStartNestType === NodePositionStateType.START) {
- start_next = startPosition[nextType] as number;
- }
-
- if (preEndNestType === NodePositionStateType.END) {
- end_next = endPosition[nextType] as number;
- }
-
- return {
- start_next,
- end_next,
- };
- }
-
- private _pushToPoints(position: IPosition) {
- const { startX, startY, endX, endY } = position;
- const points: Array<{ x: number; y: number }> = [];
- points.push({
- x: startX,
- y: startY,
- });
-
- points.push({
- x: endX,
- y: startY,
- });
-
- points.push({
- x: endX,
- y: endY,
- });
-
- points.push({
- x: startX,
- y: endY,
- });
- points.push({
- x: startX,
- y: startY,
- });
- return points;
- }
-
private isSamePosition() {
const start = this.startNodePosition;
@@ -493,10 +257,11 @@ export class TextSelection {
const polygon = new RegularPolygon(TEXT_RANGE_KEY_PREFIX + Tools.generateRandomId(6), {
pointsGroup,
- fill: getColor(COLORS.black, 0.2),
+ fill: this._style?.fill || getColor(COLORS.black, 0.2),
left,
top,
evented: false,
+ debounceParentDirty: false,
});
this._rangeShape = polygon;
@@ -534,8 +299,8 @@ export class TextSelection {
left: left + docsLeft,
top: top + docsTop,
height,
- strokeWidth: 1,
- stroke: getColor(COLORS.black),
+ strokeWidth: this._style?.strokeWidth || 1,
+ stroke: this._style?.stroke || getColor(COLORS.black, 0),
evented: false,
});
@@ -544,276 +309,6 @@ export class TextSelection {
this._scene.addObject(anchor, 2);
}
- // eslint-disable-next-line max-lines-per-function
- private _getRangePointData(startOrigin: INodePosition, endOrigin: INodePosition, documents: DocComponent) {
- const pointGroup: IPoint[][] = [];
-
- const cursorList: ITextSelectionRange[] = [];
-
- if (startOrigin == null || endOrigin == null) {
- return {
- pointGroup,
- cursorList,
- };
- }
-
- const { start, end } = this._compareNodePosition(startOrigin, endOrigin);
-
- // eslint-disable-next-line max-lines-per-function
- this._selectionIterator(start!, end!, documents, (start_sp, end_sp, isFirst, isLast, divide, line) => {
- const { lineHeight } = line;
-
- const { spanGroup, st } = divide;
-
- const { x: startX, y: startY } = this._Liquid;
-
- let position: IPosition;
-
- const firstSpan = spanGroup[start_sp];
- const lastSpan = spanGroup[end_sp];
-
- const firstSpanLeft = firstSpan?.left || 0;
- const firstSpanWidth = firstSpan?.width || 0;
-
- const lastSpanLeft = lastSpan?.left || 0;
- const lastSpanWidth = lastSpan?.width || 0;
-
- const isCurrentList = firstSpan?.spanType === SpanType.LIST;
-
- const hasList = spanGroup[0]?.spanType === SpanType.LIST;
-
- let cursorStart = start_sp + st;
-
- let cursorEnd = end_sp + st;
-
- const isStartBack = start.span === start_sp && isFirst ? start.isBack : true;
-
- const isEndBack = end.span === end_sp && isLast ? end.isBack : false;
-
- // let isStartBackFin = isStartBack;
-
- // let isEndBackFin = isEndBack;
-
- const isCollapse = start === end;
-
- if (start_sp === 0 && end_sp === spanGroup.length - 1) {
- cursorEnd -= hasList ? 1 : 0;
-
- position = {
- startX: startX + firstSpanLeft + (isCurrentList ? firstSpanWidth : 0),
- startY,
- endX: startX + lastSpanLeft + lastSpanWidth,
- endY: startY + lineHeight,
- };
- } else {
- const isStartBackFin = isStartBack && !isCurrentList;
-
- // isEndBackFin = isEndBack;
-
- // cursorStart += isStartBackFin ? 0 : 1;
-
- cursorStart -= hasList && !isCurrentList ? 1 : 0;
-
- // cursorEnd += isEndBackFin ? 0 : 1;
-
- cursorEnd -= hasList && !isCurrentList ? 1 : 0;
-
- // console.log('span', {
- // start,
- // end,
- // hasList,
- // isStartBackFin,
- // firstSpan,
- // lastSpan,
- // start_sp,
- // end_sp,
- // isStartBack,
- // isEndBack,
- // cursorStart,
- // cursorEnd,
- // isCurrentList,
- // });
-
- position = {
- startX: startX + firstSpanLeft + (isStartBackFin ? 0 : firstSpanWidth),
- startY,
- endX: startX + lastSpanLeft + (isEndBack ? 0 : lastSpanWidth),
- endY: startY + lineHeight,
- };
-
- // for (let sp = start_sp; sp <= end_sp; sp++) {
- // const span = spanGroup[sp];
- // const { width: spanWidth, left: spanLeft } = span;
- // }
- }
-
- pointGroup.push(this._pushToPoints(position));
- cursorList.push({
- isStartBack,
- isEndBack,
- cursorStart,
- cursorEnd,
- isCollapse,
- });
- });
-
- return {
- pointGroup,
- cursorList,
- };
- }
-
- // eslint-disable-next-line max-lines-per-function
- private _selectionIterator(
- startPosition: INodePosition,
- endPosition: INodePosition,
- documents: DocComponent,
- func: (
- startSpanIndex: number,
- endSpanIndex: number,
- isFirst: boolean,
- isLast: boolean,
- divide: IDocumentSkeletonDivide,
- line: IDocumentSkeletonLine,
- column: IDocumentSkeletonColumn,
- section: IDocumentSkeletonSection,
- page: IDocumentSkeletonPage
- ) => void
- ) {
- const skeleton = documents.getSkeleton();
- if (!skeleton) {
- return [];
- }
-
- this._Liquid.reset();
-
- const skeletonData = skeleton.getSkeletonData();
-
- if (skeletonData == null) {
- return [];
- }
-
- const pages = skeletonData.pages;
-
- const { page: pageIndex } = startPosition;
-
- const { page: endPageIndex } = endPosition;
-
- this._resetCurrentNodePositionState();
-
- for (let p = 0; p <= pageIndex - 1; p++) {
- const page = pages[p];
- this._Liquid.translatePage(
- page,
- documents.pageLayoutType,
- documents.pageMarginLeft,
- documents.pageMarginTop
- );
- }
-
- for (let p = pageIndex; p <= endPageIndex; p++) {
- const page = pages[p];
- const sections = page.sections;
-
- const { start_next: start_s, end_next: end_s } = this._getSelectionRuler(
- NodePositionMap.page,
- startPosition,
- endPosition,
- sections.length - 1,
- p
- );
- this._Liquid.translateSave();
- this._Liquid.translatePagePadding(page);
-
- for (let s = start_s; s <= end_s; s++) {
- const section = sections[s];
- const columns = section.columns;
- const { start_next: start_c, end_next: end_c } = this._getSelectionRuler(
- NodePositionMap.section,
- startPosition,
- endPosition,
- columns.length - 1,
- s
- );
-
- this._Liquid.translateSection(section);
-
- for (let c = start_c; c <= end_c; c++) {
- const column = columns[c];
- const lines = column.lines;
- const { start_next: start_l, end_next: end_l } = this._getSelectionRuler(
- NodePositionMap.column,
- startPosition,
- endPosition,
- lines.length - 1,
- c
- );
-
- this._Liquid.translateColumn(column);
-
- for (let l = start_l; l <= end_l; l++) {
- const line = lines[l];
- const { divides, type, lineHeight = 0 } = line;
- const { start_next: start_d, end_next: end_d } = this._getSelectionRuler(
- NodePositionMap.line,
- startPosition,
- endPosition,
- divides.length - 1,
- l
- );
- this._Liquid.translateSave();
- this._Liquid.translateLine(line);
-
- for (let d = start_d; d <= end_d; d++) {
- const divide = divides[d];
-
- // console.log('div', divides, divide, startPosition, endPosition, start_d, end_d, d);
-
- this._Liquid.translateSave();
- this._Liquid.translateDivide(divide);
-
- const spanGroup = divide.spanGroup;
-
- const { start_next: start_sp, end_next: end_sp } = this._getSelectionRuler(
- NodePositionMap.divide,
- startPosition,
- endPosition,
- spanGroup.length - 1,
- d
- );
-
- let isFirst = false;
-
- let isLast = false;
-
- if (p === pageIndex && s === start_s && c === start_c && l === start_l && d === start_d) {
- isFirst = true;
- }
-
- if (p === endPageIndex && s === end_s && c === end_c && l === end_l && d === end_d) {
- isLast = true;
- }
-
- func && func(start_sp, end_sp, isFirst, isLast, divide, line, column, section, page);
-
- this._Liquid.translateRestore();
- }
-
- this._Liquid.translateRestore();
- }
- }
- }
-
- this._Liquid.translateRestore();
- this._Liquid.translatePage(
- page,
- documents.pageLayoutType,
- documents.pageMarginLeft,
- documents.pageMarginTop
- );
- }
- }
-
private _setRangeList(rangeList: ITextSelectionRange[]) {
if (rangeList.length === 0) {
return;
diff --git a/packages/base-render/src/Component/Docs/Common/convert-cursor.ts b/packages/base-render/src/Component/Docs/Common/convert-cursor.ts
new file mode 100644
index 0000000000..fe730ec56a
--- /dev/null
+++ b/packages/base-render/src/Component/Docs/Common/convert-cursor.ts
@@ -0,0 +1,552 @@
+import { IPosition, ITextSelectionRange, Nullable } from '@univerjs/core';
+
+import {
+ IDocumentSkeletonColumn,
+ IDocumentSkeletonDivide,
+ IDocumentSkeletonLine,
+ IDocumentSkeletonPage,
+ IDocumentSkeletonSection,
+ SpanType,
+} from '../../../Basics/IDocumentSkeletonCached';
+import { INodePosition } from '../../../Basics/Interfaces';
+import { IPoint } from '../../../Basics/Vector2';
+import { DocumentSkeleton } from '../DocSkeleton';
+import { IDocumentOffsetConfig } from '../Document';
+import { Liquid } from './Liquid';
+
+export enum NodePositionStateType {
+ NORMAL,
+ START,
+ END,
+}
+
+export enum NodePositionType {
+ page,
+ section,
+ column,
+ line,
+ divide,
+ span,
+}
+
+export interface ICurrentNodePositionState {
+ page: NodePositionStateType;
+ section: NodePositionStateType;
+ column: NodePositionStateType;
+ line: NodePositionStateType;
+ divide: NodePositionStateType;
+ span: NodePositionStateType;
+}
+
+export const NodePositionMap = {
+ page: 0,
+ section: 1,
+ column: 2,
+ line: 3,
+ divide: 4,
+ span: 5,
+};
+
+export function compareNodePositionLogic(pos1: INodePosition, pos2: INodePosition) {
+ if (pos1.page > pos2.page) {
+ return false;
+ }
+
+ if (pos1.page < pos2.page) {
+ return true;
+ }
+
+ if (pos1.section > pos2.section) {
+ return false;
+ }
+
+ if (pos1.section < pos2.section) {
+ return true;
+ }
+
+ if (pos1.column > pos2.column) {
+ return false;
+ }
+
+ if (pos1.column < pos2.column) {
+ return true;
+ }
+
+ if (pos1.line > pos2.line) {
+ return false;
+ }
+
+ if (pos1.line < pos2.line) {
+ return true;
+ }
+
+ if (pos1.divide > pos2.divide) {
+ return false;
+ }
+
+ if (pos1.divide < pos2.divide) {
+ return true;
+ }
+
+ if (pos1.span > pos2.span) {
+ return false;
+ }
+
+ if (pos1.span < pos2.span) {
+ return true;
+ }
+
+ return true;
+}
+
+export function compareNodePosition(pos1: INodePosition, pos2: INodePosition) {
+ const compare = compareNodePositionLogic(pos1, pos2);
+ if (compare) {
+ return {
+ start: pos1,
+ end: pos2,
+ };
+ }
+ return {
+ start: pos2,
+ end: pos1,
+ };
+}
+
+export function getOneTextSelectionRange(rangeList: ITextSelectionRange[]): Nullable<ITextSelectionRange> {
+ const cursorList = rangeList;
+
+ if (rangeList.length === 0) {
+ return;
+ }
+
+ const firstCursor = cursorList[0];
+
+ const lastCursor = cursorList[cursorList.length - 1];
+
+ const isCollapse = cursorList.length === 1 && firstCursor.isCollapse;
+
+ return {
+ cursorStart: firstCursor.cursorStart,
+ cursorEnd: lastCursor.cursorEnd,
+ isStartBack: firstCursor.isStartBack,
+ isEndBack: lastCursor.isEndBack,
+ isCollapse,
+ };
+}
+
+export class NodePositionConvertToCursor {
+ private _Liquid = new Liquid();
+
+ private _documentOffsetConfig: Nullable<IDocumentOffsetConfig>;
+
+ private _docSkeleton: Nullable<DocumentSkeleton>;
+
+ private _currentStartState: ICurrentNodePositionState = {
+ page: NodePositionStateType.NORMAL,
+ section: NodePositionStateType.NORMAL,
+ column: NodePositionStateType.NORMAL,
+ line: NodePositionStateType.NORMAL,
+ divide: NodePositionStateType.NORMAL,
+ span: NodePositionStateType.NORMAL,
+ };
+
+ private _currentEndState: ICurrentNodePositionState = {
+ page: NodePositionStateType.NORMAL,
+ section: NodePositionStateType.NORMAL,
+ column: NodePositionStateType.NORMAL,
+ line: NodePositionStateType.NORMAL,
+ divide: NodePositionStateType.NORMAL,
+ span: NodePositionStateType.NORMAL,
+ };
+
+ constructor(documentOffsetConfig: IDocumentOffsetConfig, docSkeleton: DocumentSkeleton) {
+ this._documentOffsetConfig = documentOffsetConfig;
+
+ this._docSkeleton = docSkeleton;
+ }
+
+ getRangePointData(startOrigin: Nullable<INodePosition>, endOrigin: Nullable<INodePosition>) {
+ const pointGroup: IPoint[][] = [];
+
+ const cursorList: ITextSelectionRange[] = [];
+
+ if (startOrigin == null || endOrigin == null) {
+ return {
+ pointGroup,
+ cursorList,
+ };
+ }
+
+ const { start, end } = compareNodePosition(startOrigin, endOrigin);
+
+ // eslint-disable-next-line max-lines-per-function
+ this._selectionIterator(start!, end!, (start_sp, end_sp, isFirst, isLast, divide, line) => {
+ const { lineHeight } = line;
+
+ const { spanGroup, st } = divide;
+
+ const { x: startX, y: startY } = this._Liquid;
+
+ let position: IPosition;
+
+ const firstSpan = spanGroup[start_sp];
+ const lastSpan = spanGroup[end_sp];
+
+ const firstSpanLeft = firstSpan?.left || 0;
+ const firstSpanWidth = firstSpan?.width || 0;
+
+ const lastSpanLeft = lastSpan?.left || 0;
+ const lastSpanWidth = lastSpan?.width || 0;
+
+ const isCurrentList = firstSpan?.spanType === SpanType.LIST;
+
+ const hasList = spanGroup[0]?.spanType === SpanType.LIST;
+
+ let cursorStart = start_sp + st;
+
+ let cursorEnd = end_sp + st;
+
+ const isStartBack = start.span === start_sp && isFirst ? start.isBack : true;
+
+ const isEndBack = end.span === end_sp && isLast ? end.isBack : false;
+
+ // let isStartBackFin = isStartBack;
+
+ // let isEndBackFin = isEndBack;
+
+ const isCollapse = start === end;
+
+ if (start_sp === 0 && end_sp === spanGroup.length - 1) {
+ cursorEnd -= hasList ? 1 : 0;
+
+ position = {
+ startX: startX + firstSpanLeft + (isCurrentList ? firstSpanWidth : 0),
+ startY,
+ endX: startX + lastSpanLeft + lastSpanWidth,
+ endY: startY + lineHeight,
+ };
+ } else {
+ const isStartBackFin = isStartBack && !isCurrentList;
+
+ // isEndBackFin = isEndBack;
+
+ // cursorStart += isStartBackFin ? 0 : 1;
+
+ cursorStart -= hasList && !isCurrentList ? 1 : 0;
+
+ // cursorEnd += isEndBackFin ? 0 : 1;
+
+ cursorEnd -= hasList && !isCurrentList ? 1 : 0;
+
+ position = {
+ startX: startX + firstSpanLeft + (isStartBackFin ? 0 : firstSpanWidth),
+ startY,
+ endX: startX + lastSpanLeft + (isEndBack ? 0 : lastSpanWidth),
+ endY: startY + lineHeight,
+ };
+
+ // for (let sp = start_sp; sp <= end_sp; sp++) {
+ // const span = spanGroup[sp];
+ // const { width: spanWidth, left: spanLeft } = span;
+ // }
+ }
+
+ pointGroup.push(this._pushToPoints(position));
+ cursorList.push({
+ isStartBack,
+ isEndBack,
+ cursorStart,
+ cursorEnd,
+ isCollapse,
+ });
+ });
+
+ return {
+ pointGroup,
+ cursorList,
+ };
+ }
+
+ private _resetCurrentNodePositionState() {
+ this._currentStartState = {
+ page: NodePositionStateType.NORMAL,
+ section: NodePositionStateType.NORMAL,
+ column: NodePositionStateType.NORMAL,
+ line: NodePositionStateType.NORMAL,
+ divide: NodePositionStateType.NORMAL,
+ span: NodePositionStateType.NORMAL,
+ };
+
+ this._currentEndState = {
+ page: NodePositionStateType.NORMAL,
+ section: NodePositionStateType.NORMAL,
+ column: NodePositionStateType.NORMAL,
+ line: NodePositionStateType.NORMAL,
+ divide: NodePositionStateType.NORMAL,
+ span: NodePositionStateType.NORMAL,
+ };
+ }
+
+ private _setNodePositionState(type = NodePositionType.page, start: number, end: number, current: number) {
+ if (current === start) {
+ this._currentStartState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.START;
+ } else {
+ this._currentStartState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.NORMAL;
+ }
+
+ if (current === end) {
+ this._currentEndState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.END;
+ } else {
+ this._currentEndState[type as unknown as keyof ICurrentNodePositionState] = NodePositionStateType.NORMAL;
+ }
+ }
+
+ private _checkPreviousNodePositionState(typeIndex: number, isStart = true) {
+ let index = typeIndex;
+ let resultState: Nullable<NodePositionStateType>;
+ while (index >= 0) {
+ const type = NodePositionType[index] as keyof ICurrentNodePositionState;
+ let state;
+ if (isStart) {
+ state = this._currentStartState[type];
+ } else {
+ state = this._currentEndState[type];
+ }
+
+ if (state === undefined) {
+ return;
+ }
+ if (resultState === undefined) {
+ resultState = state;
+ }
+ if (state !== resultState) {
+ return NodePositionStateType.NORMAL;
+ }
+
+ index--;
+ }
+
+ return resultState;
+ }
+
+ private _getSelectionRuler(
+ typeIndex: number,
+ startPosition: INodePosition,
+ endPosition: INodePosition,
+ nextLength: number,
+ current: number
+ ) {
+ let start_next = 0;
+ let end_next = nextLength;
+
+ const type = NodePositionType[typeIndex] as keyof INodePosition;
+
+ const nextType = NodePositionType[typeIndex + 1] as keyof INodePosition;
+
+ if (nextType === null || type === null) {
+ return {
+ start_next,
+ end_next,
+ };
+ }
+
+ const start = startPosition[type] as number;
+
+ const end = endPosition[type] as number;
+
+ this._setNodePositionState(type as unknown as NodePositionType, start, end, current);
+
+ const preStartNestType = this._checkPreviousNodePositionState(typeIndex);
+
+ const preEndNestType = this._checkPreviousNodePositionState(typeIndex, false);
+
+ if (preStartNestType === NodePositionStateType.START) {
+ start_next = startPosition[nextType] as number;
+ }
+
+ if (preEndNestType === NodePositionStateType.END) {
+ end_next = endPosition[nextType] as number;
+ }
+
+ return {
+ start_next,
+ end_next,
+ };
+ }
+
+ private _pushToPoints(position: IPosition) {
+ const { startX, startY, endX, endY } = position;
+ const points: Array<{ x: number; y: number }> = [];
+ points.push({
+ x: startX,
+ y: startY,
+ });
+
+ points.push({
+ x: endX,
+ y: startY,
+ });
+
+ points.push({
+ x: endX,
+ y: endY,
+ });
+
+ points.push({
+ x: startX,
+ y: endY,
+ });
+ points.push({
+ x: startX,
+ y: startY,
+ });
+ return points;
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _selectionIterator(
+ startPosition: INodePosition,
+ endPosition: INodePosition,
+ func: (
+ startSpanIndex: number,
+ endSpanIndex: number,
+ isFirst: boolean,
+ isLast: boolean,
+ divide: IDocumentSkeletonDivide,
+ line: IDocumentSkeletonLine,
+ column: IDocumentSkeletonColumn,
+ section: IDocumentSkeletonSection,
+ page: IDocumentSkeletonPage
+ ) => void
+ ) {
+ const skeleton = this._docSkeleton;
+ if (!skeleton) {
+ return [];
+ }
+
+ this._Liquid.reset();
+
+ const skeletonData = skeleton.getSkeletonData();
+
+ if (skeletonData == null) {
+ return [];
+ }
+
+ const pages = skeletonData.pages;
+
+ const { page: pageIndex } = startPosition;
+
+ const { page: endPageIndex } = endPosition;
+
+ this._resetCurrentNodePositionState();
+
+ if (this._documentOffsetConfig == null) {
+ return [];
+ }
+
+ const { pageLayoutType, pageMarginLeft, pageMarginTop } = this._documentOffsetConfig;
+
+ for (let p = 0; p <= pageIndex - 1; p++) {
+ const page = pages[p];
+ this._Liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ }
+
+ for (let p = pageIndex; p <= endPageIndex; p++) {
+ const page = pages[p];
+ const sections = page.sections;
+
+ const { start_next: start_s, end_next: end_s } = this._getSelectionRuler(
+ NodePositionMap.page,
+ startPosition,
+ endPosition,
+ sections.length - 1,
+ p
+ );
+ this._Liquid.translateSave();
+ this._Liquid.translatePagePadding(page);
+
+ for (let s = start_s; s <= end_s; s++) {
+ const section = sections[s];
+ const columns = section.columns;
+ const { start_next: start_c, end_next: end_c } = this._getSelectionRuler(
+ NodePositionMap.section,
+ startPosition,
+ endPosition,
+ columns.length - 1,
+ s
+ );
+
+ this._Liquid.translateSection(section);
+
+ for (let c = start_c; c <= end_c; c++) {
+ const column = columns[c];
+ const lines = column.lines;
+ const { start_next: start_l, end_next: end_l } = this._getSelectionRuler(
+ NodePositionMap.column,
+ startPosition,
+ endPosition,
+ lines.length - 1,
+ c
+ );
+
+ this._Liquid.translateColumn(column);
+
+ for (let l = start_l; l <= end_l; l++) {
+ const line = lines[l];
+ const { divides, type, lineHeight = 0 } = line;
+ const { start_next: start_d, end_next: end_d } = this._getSelectionRuler(
+ NodePositionMap.line,
+ startPosition,
+ endPosition,
+ divides.length - 1,
+ l
+ );
+ this._Liquid.translateSave();
+ this._Liquid.translateLine(line);
+
+ for (let d = start_d; d <= end_d; d++) {
+ const divide = divides[d];
+
+ // console.log('div', divides, divide, startPosition, endPosition, start_d, end_d, d);
+
+ this._Liquid.translateSave();
+ this._Liquid.translateDivide(divide);
+
+ const spanGroup = divide.spanGroup;
+
+ const { start_next: start_sp, end_next: end_sp } = this._getSelectionRuler(
+ NodePositionMap.divide,
+ startPosition,
+ endPosition,
+ spanGroup.length - 1,
+ d
+ );
+
+ let isFirst = false;
+
+ let isLast = false;
+
+ if (p === pageIndex && s === start_s && c === start_c && l === start_l && d === start_d) {
+ isFirst = true;
+ }
+
+ if (p === endPageIndex && s === end_s && c === end_c && l === end_l && d === end_d) {
+ isLast = true;
+ }
+
+ func && func(start_sp, end_sp, isFirst, isLast, divide, line, column, section, page);
+
+ this._Liquid.translateRestore();
+ }
+
+ this._Liquid.translateRestore();
+ }
+ }
+ }
+
+ this._Liquid.translateRestore();
+ this._Liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ }
+ }
+}
diff --git a/packages/base-render/src/Component/Docs/Common/index.ts b/packages/base-render/src/Component/Docs/Common/index.ts
index 5759093008..5c8f58912e 100644
--- a/packages/base-render/src/Component/Docs/Common/index.ts
+++ b/packages/base-render/src/Component/Docs/Common/index.ts
@@ -1,8 +1,9 @@
-export * from './Column';
-export * from './Line';
-export * from './Liquid';
-export * from './Page';
-export * from './Section';
-export * from './Span';
-export * from './TextSelection';
-export * from './Tools';
+export * from './Column';
+export * from './convert-cursor';
+export * from './Line';
+export * from './Liquid';
+export * from './Page';
+export * from './Section';
+export * from './Span';
+export * from './TextSelection';
+export * from './Tools';
diff --git a/packages/base-render/src/Component/Docs/DocComponent.ts b/packages/base-render/src/Component/Docs/DocComponent.ts
index 5267f0c02b..8cc4f74998 100644
--- a/packages/base-render/src/Component/Docs/DocComponent.ts
+++ b/packages/base-render/src/Component/Docs/DocComponent.ts
@@ -1,13 +1,8 @@
import { Nullable } from '@univerjs/core';
import { RENDER_CLASS_TYPE } from '../../Basics/Const';
-import {
- IDocumentSkeletonLine,
- IDocumentSkeletonSpan,
- PageLayoutType,
- SpanType,
-} from '../../Basics/IDocumentSkeletonCached';
-import { INodeInfo, INodePosition, INodeSearch, ITransformChangeState } from '../../Basics/Interfaces';
+import { IDocumentSkeletonLine, IDocumentSkeletonSpan, PageLayoutType } from '../../Basics/IDocumentSkeletonCached';
+import { INodeInfo, ITransformChangeState } from '../../Basics/Interfaces';
import { IBoundRect } from '../../Basics/Vector2';
import { Canvas } from '../../Canvas';
import { Scene } from '../../Scene';
@@ -100,156 +95,12 @@ export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocum
syncSelection() {}
- getFirstViewport() {}
-
remainActiveSelection() {}
- findSpanByPosition(position: Nullable<INodePosition>) {
- const skeleton = this.getSkeleton();
-
- if (!skeleton || position == null) {
- return;
- }
-
- const skeletonData = skeleton.getSkeletonData();
-
- if (skeletonData == null) {
- return;
- }
-
- const { divide, line, column, section, page, isBack } = position;
-
- let { span } = position;
-
- if (isBack === true) {
- span -= 1;
- }
-
- span = span < 0 ? 0 : span;
-
- const spanGroup =
- skeletonData.pages[page].sections[section].columns[column].lines[line].divides[divide].spanGroup;
-
- if (spanGroup[span].spanType === SpanType.LIST) {
- return spanGroup[span + 1];
- }
-
- return spanGroup[span];
- }
-
- 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): Nullable<INodeInfo> {}
findCoordByNode(span: IDocumentSkeletonSpan) {}
- findNodeByCharIndex(charIndex: number): Nullable<IDocumentSkeletonSpan> {
- const skeleton = this.getSkeleton();
-
- if (!skeleton) {
- return;
- }
-
- const skeletonData = skeleton.getSkeletonData();
-
- if (!skeletonData) {
- return;
- }
-
- const pages = skeletonData.pages;
-
- for (const page of pages) {
- const { sections, st, ed } = page;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- for (const section of sections) {
- const { columns, st, ed } = section;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- for (const column of columns) {
- const { lines, st, ed } = column;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- for (const line of lines) {
- const { divides, lineHeight, st, ed } = line;
- const divideLength = divides.length;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- for (let i = 0; i < divideLength; i++) {
- const divide = divides[i];
- const { spanGroup, st, ed } = divide;
-
- if (charIndex < st || charIndex > ed) {
- continue;
- }
-
- if (spanGroup[0].spanType === SpanType.LIST) {
- charIndex++;
- }
-
- const span = spanGroup[charIndex - st];
-
- if (span) {
- return span;
- }
- }
- }
- }
- }
- }
- }
-
- getActiveViewportByCoord(offsetX: number, offsetY: number) {}
-
protected _getBounding(bounds?: IBoundRect) {}
protected _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
diff --git a/packages/base-render/src/Component/Docs/DocSkeleton.ts b/packages/base-render/src/Component/Docs/DocSkeleton.ts
index 9edd7e0b2b..72aa44be77 100644
--- a/packages/base-render/src/Component/Docs/DocSkeleton.ts
+++ b/packages/base-render/src/Component/Docs/DocSkeleton.ts
@@ -18,12 +18,17 @@ import {
import {
IDocumentSkeletonCached,
IDocumentSkeletonPage,
+ IDocumentSkeletonSpan,
ISkeletonResourceReference,
+ LineType,
+ PageLayoutType,
+ SpanType,
} from '../../Basics/IDocumentSkeletonCached';
-import { IDocsConfig, ISectionBreakConfig } from '../../Basics/Interfaces';
-import { IBoundRect } from '../../Basics/Vector2';
+import { IDocsConfig, INodeInfo, INodePosition, INodeSearch, ISectionBreakConfig } from '../../Basics/Interfaces';
+import { IBoundRect, Vector2 } from '../../Basics/Vector2';
import { Skeleton } from '../Skeleton';
import { dealWithSections } from './Block/Section';
+import { Liquid } from './Common/Liquid';
import { createSkeletonPage } from './Common/Page';
import { createSkeletonSection } from './Common/Section';
import { getLastPage, updateBlockIndex } from './Common/Tools';
@@ -51,13 +56,15 @@ export class DocumentSkeleton extends Skeleton {
private _renderedBlockIdMap = new Map<string, boolean>();
+ private _findLiquid: Liquid = new Liquid();
+
constructor(docModel: DocumentModelOrSimple, localeService: LocaleService) {
super(localeService);
this._docModel = docModel;
this.disposeWithMe(
fromObservable(
- this._docModel.bodyModel.modelChange$.subscribe(() => {
+ this._docModel.bodyModel?.modelChange$.subscribe(() => {
this.calculate();
})
)
@@ -89,6 +96,375 @@ export class DocumentSkeleton extends Skeleton {
return this._docModel.documentStyle.pageSize;
}
+ 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.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,
+ };
+ }
+
+ findNodePositionByCharIndex(charIndex: number, isBack: boolean = false): Nullable<INodePosition> {
+ const nodes = this._findNodeIterator(charIndex);
+
+ if (nodes == null) {
+ return;
+ }
+
+ const skeletonData = this.getSkeletonData();
+
+ if (!skeletonData) {
+ return;
+ }
+
+ const pages = skeletonData.pages;
+
+ const { span, divide, line, column, section, page } = nodes;
+
+ return {
+ span: divide.spanGroup.indexOf(span),
+ divide: line.divides.indexOf(divide),
+ line: column.lines.indexOf(line),
+ column: section.columns.indexOf(column),
+ section: page.sections.indexOf(section),
+ page: pages.indexOf(page),
+ isBack,
+ };
+ }
+
+ findNodeByCharIndex(charIndex: number): Nullable<IDocumentSkeletonSpan> {
+ const nodes = this._findNodeIterator(charIndex);
+
+ return nodes?.span;
+
+ // const skeletonData = this.getSkeletonData();
+
+ // if (!skeletonData) {
+ // return;
+ // }
+
+ // const pages = skeletonData.pages;
+
+ // for (const page of pages) {
+ // const { sections, st, ed } = page;
+
+ // if (charIndex < st || charIndex > ed) {
+ // continue;
+ // }
+
+ // for (const section of sections) {
+ // const { columns, st, ed } = section;
+
+ // if (charIndex < st || charIndex > ed) {
+ // continue;
+ // }
+
+ // for (const column of columns) {
+ // const { lines, st, ed } = column;
+
+ // if (charIndex < st || charIndex > ed) {
+ // continue;
+ // }
+
+ // for (const line of lines) {
+ // const { divides, lineHeight, st, ed } = line;
+ // const divideLength = divides.length;
+
+ // if (charIndex < st || charIndex > ed) {
+ // continue;
+ // }
+
+ // for (let i = 0; i < divideLength; i++) {
+ // const divide = divides[i];
+ // const { spanGroup, st, ed } = divide;
+
+ // if (charIndex < st || charIndex > ed) {
+ // continue;
+ // }
+
+ // if (spanGroup[0].spanType === SpanType.LIST) {
+ // charIndex++;
+ // }
+
+ // const span = spanGroup[charIndex - st];
+
+ // if (span) {
+ // return span;
+ // }
+ // }
+ // }
+ // }
+ // }
+ // }
+ }
+
+ findSpanByPosition(position: Nullable<INodePosition>) {
+ if (position == null) {
+ return;
+ }
+
+ const skeletonData = this.getSkeletonData();
+
+ if (skeletonData == null) {
+ return;
+ }
+
+ const { divide, line, column, section, page, isBack } = position;
+
+ let { span } = position;
+
+ if (isBack === true) {
+ span -= 1;
+ }
+
+ span = span < 0 ? 0 : span;
+
+ const spanGroup =
+ skeletonData.pages[page].sections[section].columns[column].lines[line].divides[divide].spanGroup;
+
+ if (spanGroup[span].spanType === SpanType.LIST) {
+ return spanGroup[span + 1];
+ }
+
+ return spanGroup[span];
+ }
+
+ findNodeByCoord(
+ coord: Vector2,
+ pageLayoutType: PageLayoutType,
+ pageMarginLeft: number,
+ pageMarginTop: number
+ ): Nullable<INodeInfo> {
+ const { x, y } = coord;
+
+ this._findLiquid.reset();
+
+ const skeletonData = this.getSkeletonData();
+
+ if (skeletonData == null) {
+ return;
+ }
+
+ const pages = skeletonData.pages;
+
+ let nearestNodeList: INodeInfo[] = [];
+
+ let nearestNodeDistanceList: number[] = [];
+
+ let nearestNodeDistanceY = Infinity;
+
+ for (let i = 0, len = pages.length; i < len; i++) {
+ const page = pages[i];
+
+ const { startX, startY, endX, endY } = this._getPageBoundingBox(page, pageLayoutType);
+
+ if (!(x >= startX && x <= endX && y >= startY && y <= endY)) {
+ this._translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ continue;
+ }
+
+ this._findLiquid.translatePagePadding(page);
+
+ const sections = page.sections;
+
+ for (const section of sections) {
+ const { columns, height } = section;
+
+ this._findLiquid.translateSection(section);
+
+ const { y: startY } = this._findLiquid;
+
+ // if (!(y >= startY && y <= startY + height)) {
+ // continue;
+ // }
+
+ for (const column of columns) {
+ const { lines, width: columnWidth } = column;
+
+ this._findLiquid.translateColumn(column);
+
+ const { x: startX } = this._findLiquid;
+
+ // if (!(x >= startX && x <= startX + columnWidth)) {
+ // continue;
+ // }
+
+ const linesCount = lines.length;
+
+ for (let i = 0; i < linesCount; i++) {
+ const line = lines[i];
+ const { divides, type, lineHeight = 0 } = line;
+
+ if (type === LineType.BLOCK) {
+ continue;
+ } else {
+ this._findLiquid.translateSave();
+ this._findLiquid.translateLine(line);
+
+ const { y: startY } = this._findLiquid;
+
+ const startY_fin = startY;
+
+ const endY_fin = startY + lineHeight;
+
+ const distanceY = Math.abs(y - endY_fin);
+
+ // if (!(y >= startY_fin && y <= endY_fin)) {
+ // this._findLiquid.translateRestore();
+ // continue;
+ // }
+
+ const divideLength = divides.length;
+ for (let i = 0; i < divideLength; i++) {
+ const divide = divides[i];
+ const { spanGroup, width: divideWidth } = divide;
+
+ this._findLiquid.translateSave();
+ this._findLiquid.translateDivide(divide);
+
+ const { x: startX } = this._findLiquid;
+
+ // if (!(x >= startX && x <= startX + divideWidth)) {
+ // this._findLiquid.translateRestore();
+ // continue;
+ // }
+
+ for (const span of spanGroup) {
+ if (!span.content || span.content.length === 0) {
+ continue;
+ }
+
+ const { width: spanWidth, left: spanLeft } = span;
+
+ const startX_fin = startX + spanLeft;
+
+ const endX_fin = startX + spanLeft + spanWidth;
+
+ const distanceX = Math.abs(x - endX_fin);
+
+ if (y >= startY_fin && y <= endY_fin) {
+ if (x >= startX_fin && x <= endX_fin) {
+ return {
+ node: span,
+ ratioX: x / (startX_fin + endX_fin),
+ ratioY: y / (startY_fin + endY_fin),
+ };
+ }
+
+ if (nearestNodeDistanceY !== -Infinity) {
+ nearestNodeList = [];
+ nearestNodeDistanceList = [];
+ }
+ nearestNodeList.push({
+ node: span,
+ ratioX: x / (startX_fin + endX_fin),
+ ratioY: y / (startY_fin + endY_fin),
+ });
+
+ nearestNodeDistanceList.push(distanceX);
+
+ nearestNodeDistanceY = -Infinity;
+ continue;
+ }
+
+ if (distanceY < nearestNodeDistanceY) {
+ nearestNodeDistanceY = distanceY;
+ nearestNodeList = [];
+ nearestNodeDistanceList = [];
+ }
+
+ if (distanceY === nearestNodeDistanceY) {
+ nearestNodeList.push({
+ node: span,
+ ratioX: x / (startX_fin + endX_fin),
+ ratioY: y / (startY_fin + endY_fin),
+ });
+
+ nearestNodeDistanceList.push(distanceX);
+ }
+ }
+ this._findLiquid.translateRestore();
+ }
+ this._findLiquid.translateRestore();
+ }
+ }
+ }
+ }
+ this._findLiquid.restorePagePadding(page);
+ this._translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ }
+
+ return this._getNearestNode(nearestNodeList, nearestNodeDistanceList);
+ }
+
+ private _getNearestNode(nearestNodeList: INodeInfo[], nearestNodeDistanceList: number[]) {
+ const miniValue = Math.min(...nearestNodeDistanceList);
+ const miniValueIndex = nearestNodeDistanceList.indexOf(miniValue);
+ return nearestNodeList[miniValueIndex];
+ }
+
+ private _getPageBoundingBox(page: IDocumentSkeletonPage, pageLayoutType: PageLayoutType) {
+ const { pageWidth, pageHeight } = page;
+ const { x: startX, y: startY } = this._findLiquid;
+
+ let endX = -1;
+ let endY = -1;
+ if (pageLayoutType === PageLayoutType.VERTICAL) {
+ endX = pageWidth;
+ endY = startY + pageHeight;
+ } else if (pageLayoutType === PageLayoutType.HORIZONTAL) {
+ endX = startX + pageWidth;
+ endY = pageHeight;
+ }
+
+ return {
+ startX,
+ startY,
+ endX,
+ endY,
+ };
+ }
+
+ private _translatePage(
+ page: IDocumentSkeletonPage,
+ pageLayoutType: PageLayoutType,
+ pageMarginLeft: number,
+ pageMarginTop: number
+ ) {
+ this._findLiquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ }
+
// updateDocumentDataPageSize(width?: number, height?: number) {
// const documentStyle = this._docModel.documentStyle;
// if (!documentStyle.pageSize) {
@@ -111,30 +487,30 @@ export class DocumentSkeleton extends Skeleton {
// }
/**
- * \v COLUMN_BREAK 换列
- * \f PAGE_BREAK 换页
- * \0 DOCS_END 文档结尾
- * \t TAB 制表符
+ * \v COLUMN_BREAK
+ * \f PAGE_BREAK
+ * \0 DOCS_END
+ * \t TAB
*
* Needs to be changed:
- * \r PARAGRAPH 段落
- * \n SECTION_BREAK 章节
+ * \r PARAGRAPH
+ * \n SECTION_BREAK
*
- * \b customBlock 图片 mention等不参与文档流的场景
+ * \b customBlock: Scenarios where customBlock, images, mentions, etc. do not participate in the document flow.
*
- * 表格
- * \x1A table start 表格开始
- * \x1B table row start 表格开始
- * \x1C table cell start 表格开始
- * \x1D table cell end 表格开始
- * \x1E table row end 表格开始
- * \x1F table end 表格结束
+ * Table
+ * \x1A table start
+ * \x1B table row start
+ * \x1C table cell start
+ * \x1D table cell end
+ * \x1E table row end
+ * \x1F table end
*
- * 文档流内的特殊范围:超链接,field,structured document tags, bookmark,comment
- * \x1F customRange start 自定义范围开始
- * \x1E customRange end 自定义范围结束
+ * Special ranges within the document flow::hyperlinks,field,structured document tags, bookmark,comment
+ * \x1F customRange start
+ * \x1E customRange end
*
- * 按照SectionBreak分割文档,进行布局计算
+ * Split the document according to SectionBreak and perform layout calculations.
* @returns view model: skeleton
*/
// eslint-disable-next-line max-lines-per-function
@@ -384,4 +760,73 @@ export class DocumentSkeleton extends Skeleton {
drawingAnchor: new Map(),
};
}
+
+ private _findNodeIterator(charIndex: number) {
+ const skeletonData = this.getSkeletonData();
+
+ if (!skeletonData) {
+ return;
+ }
+
+ const pages = skeletonData.pages;
+
+ for (const page of pages) {
+ const { sections, st, ed } = page;
+
+ if (charIndex < st || charIndex > ed) {
+ continue;
+ }
+
+ for (const section of sections) {
+ const { columns, st, ed } = section;
+
+ if (charIndex < st || charIndex > ed) {
+ continue;
+ }
+
+ for (const column of columns) {
+ const { lines, st, ed } = column;
+
+ if (charIndex < st || charIndex > ed) {
+ continue;
+ }
+
+ for (const line of lines) {
+ const { divides, lineHeight, st, ed } = line;
+ const divideLength = divides.length;
+
+ if (charIndex < st || charIndex > ed) {
+ continue;
+ }
+
+ for (let i = 0; i < divideLength; i++) {
+ const divide = divides[i];
+ const { spanGroup, st, ed } = divide;
+
+ if (charIndex < st || charIndex > ed) {
+ continue;
+ }
+
+ if (spanGroup[0].spanType === SpanType.LIST) {
+ charIndex++;
+ }
+
+ const span = spanGroup[charIndex - st];
+
+ if (span) {
+ return {
+ page,
+ section,
+ column,
+ line,
+ divide,
+ span,
+ };
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
diff --git a/packages/base-render/src/Component/Docs/Document.ts b/packages/base-render/src/Component/Docs/Document.ts
index a2547bc4b3..a9f737564f 100644
--- a/packages/base-render/src/Component/Docs/Document.ts
+++ b/packages/base-render/src/Component/Docs/Document.ts
@@ -17,22 +17,23 @@ import {
LineType,
PageLayoutType,
} from '../../Basics/IDocumentSkeletonCached';
-import { INodeInfo } from '../../Basics/Interfaces';
import { degToRad, fixLineWidthByScale, getScale } from '../../Basics/Tools';
+import { Transform } from '../../Basics/Transform';
import { IBoundRect, Vector2 } from '../../Basics/Vector2';
import { Scene } from '../../Scene';
import { DocumentsSpanAndLineExtensionRegistry, IExtensionConfig } from '../Extension';
import { Liquid } from './Common/Liquid';
-import { TextSelection } from './Common/TextSelection';
import { DocComponent } from './DocComponent';
import { DOCS_EXTENSION_TYPE } from './DocExtension';
import { DocumentSkeleton } from './DocSkeleton';
-import { DocsEditor } from './Document.Editor';
-export interface IDocumentsConfig {
- pageMarginLeft?: number;
- pageMarginTop?: number;
+interface PageMarginLayout {
+ pageMarginLeft: number;
+ pageMarginTop: number;
pageLayoutType?: PageLayoutType;
+}
+
+export interface IDocumentsConfig extends PageMarginLayout {
allowCache?: boolean;
hasEditor?: boolean;
}
@@ -44,6 +45,12 @@ export interface IPageRenderConfig {
ctx: CanvasRenderingContext2D;
}
+export interface IDocumentOffsetConfig extends PageMarginLayout {
+ docsLeft: number;
+ docsTop: number;
+ documentTransform: Transform;
+}
+
export class Documents extends DocComponent {
isCalculateSkeleton = true;
@@ -57,9 +64,9 @@ export class Documents extends DocComponent {
private _findLiquid: Liquid;
- private _hasEditor = false;
+ // private _hasEditor = false;
- private _editor: Nullable<DocsEditor>;
+ // private _editor: Nullable<DocsEditor>;
private _skeletonObserver: Nullable<Observer<IDocumentSkeletonCached>>;
@@ -81,45 +88,48 @@ export class Documents extends DocComponent {
this.makeDirty(true);
}
- get hasEditor() {
- return this._hasEditor;
- }
+ // get hasEditor() {
+ // return this._hasEditor;
+ // }
static create(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {
return new Documents(oKey, documentSkeleton, config);
}
setConfig(config?: IDocumentsConfig) {
- if (config?.pageMarginLeft === undefined) {
- this.pageMarginLeft = 17;
- } else {
- this.pageMarginLeft = config?.pageMarginLeft;
- }
+ this.pageMarginLeft = config?.pageMarginLeft || 17;
- if (config?.pageMarginTop === undefined) {
- this.pageMarginTop = 14;
- } else {
- this.pageMarginTop = config?.pageMarginTop;
- }
+ this.pageMarginTop = config?.pageMarginTop || 14;
this.pageLayoutType = config?.pageLayoutType || PageLayoutType.VERTICAL;
- this._hasEditor = config?.hasEditor || false;
+ // this._hasEditor = config?.hasEditor || false;
this.setAllowCache(config?.allowCache || false);
}
- getEditor(): Nullable<DocsEditor> {
- return this._editor;
+ getOffsetConfig(): IDocumentOffsetConfig {
+ return {
+ documentTransform: this.transform,
+ pageLayoutType: this.pageLayoutType,
+ pageMarginLeft: this.pageMarginLeft,
+ pageMarginTop: this.pageMarginTop,
+ docsLeft: this.left,
+ docsTop: this.top,
+ };
}
- getActiveSelection() {
- return this._editor?.getActiveTextSelection();
- }
+ // getEditor(): Nullable<DocsEditor> {
+ // return this._editor;
+ // }
- getSelection() {
- return this._editor?.getTextSelectionList();
- }
+ // getActiveSelection() {
+ // return this._editor?.getActiveTextSelection();
+ // }
+
+ // getSelection() {
+ // return this._editor?.getTextSelectionList();
+ // }
calculatePagePosition() {
const scene = this.getScene() as Scene;
@@ -164,83 +174,75 @@ export class Documents extends DocComponent {
return this;
}
- override getFirstViewport() {
- return (this.getScene() as Scene).getViewports()[0];
- }
-
- override getActiveViewportByCoord(offsetX: number, offsetY: number) {
- return (this.getScene() as Scene).getActiveViewportByCoord(Vector2.FromArray([offsetX, offsetY]));
- }
-
override getEngine() {
return (this.getScene() as Scene).getEngine();
}
- enableEditor() {
- if (this._hasEditor) {
- return;
- }
+ // enableEditor() {
+ // if (this._hasEditor) {
+ // return;
+ // }
- this._editor = DocsEditor.create(this);
- this._hasEditor = true;
- }
+ // this._editor = DocsEditor.create(this);
+ // this._hasEditor = true;
+ // }
- disableEditor() {
- this._editor?.dispose();
- this._hasEditor = false;
- }
+ // disableEditor() {
+ // this._editor?.dispose();
+ // this._hasEditor = false;
+ // }
- getEditorInputEvent() {
- if (!this._hasEditor || this._editor == null) {
- return;
- }
- const {
- onInputObservable,
- onCompositionstartObservable,
- onCompositionupdateObservable,
- onCompositionendObservable,
- onKeydownObservable,
- onSelectionStartObservable,
- } = this._editor;
- return {
- onInputObservable,
- onCompositionstartObservable,
- onCompositionupdateObservable,
- onCompositionendObservable,
- onKeydownObservable,
- onSelectionStartObservable,
- };
- }
+ // getEditorInputEvent() {
+ // if (!this._hasEditor || this._editor == null) {
+ // return;
+ // }
+ // const {
+ // onInputObservable,
+ // onCompositionstartObservable,
+ // onCompositionupdateObservable,
+ // onCompositionendObservable,
+ // onKeydownObservable,
+ // onSelectionStartObservable,
+ // } = this._editor;
+ // return {
+ // onInputObservable,
+ // onCompositionstartObservable,
+ // onCompositionupdateObservable,
+ // onCompositionendObservable,
+ // onKeydownObservable,
+ // onSelectionStartObservable,
+ // };
+ // }
- override remainActiveSelection() {
- if (!this._hasEditor) {
- return;
- }
- return this._editor?.remain();
- }
+ // override remainActiveSelection() {
+ // if (!this._hasEditor) {
+ // return;
+ // }
+ // return this._editor?.remain();
+ // }
- addSelection(textSelection: TextSelection) {
- if (!this._hasEditor) {
- return;
- }
- return this._editor?.add(textSelection);
- }
+ // addSelection(textSelection: TextSelection) {
+ // if (!this._hasEditor) {
+ // return;
+ // }
+ // return this._editor?.add(textSelection);
+ // }
- override syncSelection() {
- if (!this._hasEditor) {
- return;
- }
+ // override syncSelection() {
+ // if (!this._hasEditor) {
+ // return;
+ // }
- return this._editor?.sync();
- }
+ // return this._editor?.sync();
+ // }
- override scrollBySelection() {
- if (this._hasEditor == null) {
- return;
- }
+ // override scrollBySelection() {
+ // if (this._hasEditor == null) {
+ // return;
+ // }
- this._editor?.scroll();
- }
+ // this._editor?.scroll();
+ // }
// eslint-disable-next-line max-lines-per-function
override draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
@@ -505,181 +507,181 @@ export class Documents extends DocComponent {
}
// eslint-disable-next-line max-lines-per-function
- override findNodeByCoord(offsetX: number, offsetY: number): Nullable<INodeInfo> {
- const scene = this.getScene() as Scene;
- const originCoord = scene.transformToSceneCoord(Vector2.FromArray([offsetX, offsetY]));
+ // override findNodeByCoord(offsetX: number, offsetY: number): Nullable<INodeInfo> {
+ // const scene = this.getScene() as Scene;
+ // const originCoord = scene.transformToSceneCoord(Vector2.FromArray([offsetX, offsetY]));
- if (!originCoord) {
- return;
- }
+ // if (!originCoord) {
+ // return;
+ // }
- const coord = this._getInverseCoord(originCoord);
- const { x, y } = coord;
- const skeleton = this.getSkeleton();
+ // const coord = this._getInverseCoord(originCoord);
+ // const { x, y } = coord;
+ // const skeleton = this.getSkeleton();
- if (!skeleton) {
- return;
- }
+ // if (!skeleton) {
+ // return;
+ // }
- this._findLiquid.reset();
+ // this._findLiquid.reset();
- const skeletonData = skeleton.getSkeletonData();
+ // const skeletonData = skeleton.getSkeletonData();
- if (skeletonData == null) {
- return;
- }
+ // if (skeletonData == null) {
+ // return;
+ // }
- const pages = skeletonData.pages;
+ // const pages = skeletonData.pages;
- let nearestNodeList: INodeInfo[] = [];
+ // let nearestNodeList: INodeInfo[] = [];
- let nearestNodeDistanceList: number[] = [];
+ // let nearestNodeDistanceList: number[] = [];
- let nearestNodeDistanceY = Infinity;
+ // let nearestNodeDistanceY = Infinity;
- for (let i = 0, len = pages.length; i < len; i++) {
- const page = pages[i];
+ // for (let i = 0, len = pages.length; i < len; i++) {
+ // const page = pages[i];
- const { startX, startY, endX, endY } = this._getPageBoundingBox(page);
+ // const { startX, startY, endX, endY } = this._getPageBoundingBox(page);
- if (!(x >= startX && x <= endX && y >= startY && y <= endY)) {
- this._translatePage(page);
- continue;
- }
+ // if (!(x >= startX && x <= endX && y >= startY && y <= endY)) {
+ // this._translatePage(page);
+ // continue;
+ // }
- this._findLiquid.translatePagePadding(page);
+ // this._findLiquid.translatePagePadding(page);
- const sections = page.sections;
+ // const sections = page.sections;
- for (const section of sections) {
- const { columns, height } = section;
+ // for (const section of sections) {
+ // const { columns, height } = section;
- this._findLiquid.translateSection(section);
+ // this._findLiquid.translateSection(section);
- const { y: startY } = this._findLiquid;
+ // const { y: startY } = this._findLiquid;
- // if (!(y >= startY && y <= startY + height)) {
- // continue;
- // }
+ // // if (!(y >= startY && y <= startY + height)) {
+ // // continue;
+ // // }
- for (const column of columns) {
- const { lines, width: columnWidth } = column;
-
- this._findLiquid.translateColumn(column);
+ // for (const column of columns) {
+ // const { lines, width: columnWidth } = column;
- const { x: startX } = this._findLiquid;
+ // this._findLiquid.translateColumn(column);
- // if (!(x >= startX && x <= startX + columnWidth)) {
- // continue;
- // }
+ // const { x: startX } = this._findLiquid;
- const linesCount = lines.length;
+ // // if (!(x >= startX && x <= startX + columnWidth)) {
+ // // continue;
+ // // }
- for (let i = 0; i < linesCount; i++) {
- const line = lines[i];
- const { divides, type, lineHeight = 0 } = line;
-
- if (type === LineType.BLOCK) {
- continue;
- } else {
- this._findLiquid.translateSave();
- this._findLiquid.translateLine(line);
+ // const linesCount = lines.length;
- const { y: startY } = this._findLiquid;
+ // for (let i = 0; i < linesCount; i++) {
+ // const line = lines[i];
+ // const { divides, type, lineHeight = 0 } = line;
- const startY_fin = startY;
+ // if (type === LineType.BLOCK) {
+ // continue;
+ // } else {
+ // this._findLiquid.translateSave();
+ // this._findLiquid.translateLine(line);
- const endY_fin = startY + lineHeight;
+ // const { y: startY } = this._findLiquid;
- const distanceY = Math.abs(y - endY_fin);
+ // const startY_fin = startY;
- // if (!(y >= startY_fin && y <= endY_fin)) {
- // this._findLiquid.translateRestore();
- // continue;
- // }
+ // const endY_fin = startY + lineHeight;
- const divideLength = divides.length;
- for (let i = 0; i < divideLength; i++) {
- const divide = divides[i];
- const { spanGroup, width: divideWidth } = divide;
+ // const distanceY = Math.abs(y - endY_fin);
- this._findLiquid.translateSave();
- this._findLiquid.translateDivide(divide);
+ // // if (!(y >= startY_fin && y <= endY_fin)) {
+ // // this._findLiquid.translateRestore();
+ // // continue;
+ // // }
- const { x: startX } = this._findLiquid;
+ // const divideLength = divides.length;
+ // for (let i = 0; i < divideLength; i++) {
+ // const divide = divides[i];
+ // const { spanGroup, width: divideWidth } = divide;
- // if (!(x >= startX && x <= startX + divideWidth)) {
- // this._findLiquid.translateRestore();
- // continue;
- // }
+ // this._findLiquid.translateSave();
+ // this._findLiquid.translateDivide(divide);
- for (const span of spanGroup) {
- if (!span.content || span.content.length === 0) {
- continue;
- }
+ // const { x: startX } = this._findLiquid;
- const { width: spanWidth, left: spanLeft } = span;
+ // // if (!(x >= startX && x <= startX + divideWidth)) {
+ // // this._findLiquid.translateRestore();
+ // // continue;
+ // // }
- const startX_fin = startX + spanLeft;
+ // for (const span of spanGroup) {
+ // if (!span.content || span.content.length === 0) {
+ // continue;
+ // }
- const endX_fin = startX + spanLeft + spanWidth;
+ // const { width: spanWidth, left: spanLeft } = span;
- const distanceX = Math.abs(x - endX_fin);
+ // const startX_fin = startX + spanLeft;
- if (y >= startY_fin && y <= endY_fin) {
- if (x >= startX_fin && x <= endX_fin) {
- return {
- node: span,
- ratioX: x / (startX_fin + endX_fin),
- ratioY: y / (startY_fin + endY_fin),
- };
- }
+ // const endX_fin = startX + spanLeft + spanWidth;
- if (nearestNodeDistanceY !== -Infinity) {
- nearestNodeList = [];
- nearestNodeDistanceList = [];
- }
- nearestNodeList.push({
- node: span,
- ratioX: x / (startX_fin + endX_fin),
- ratioY: y / (startY_fin + endY_fin),
- });
+ // const distanceX = Math.abs(x - endX_fin);
- nearestNodeDistanceList.push(distanceX);
+ // if (y >= startY_fin && y <= endY_fin) {
+ // if (x >= startX_fin && x <= endX_fin) {
+ // return {
+ // node: span,
+ // ratioX: x / (startX_fin + endX_fin),
+ // ratioY: y / (startY_fin + endY_fin),
+ // };
+ // }
- nearestNodeDistanceY = -Infinity;
- continue;
- }
+ // if (nearestNodeDistanceY !== -Infinity) {
+ // nearestNodeList = [];
+ // nearestNodeDistanceList = [];
+ // }
+ // nearestNodeList.push({
+ // node: span,
+ // ratioX: x / (startX_fin + endX_fin),
+ // ratioY: y / (startY_fin + endY_fin),
+ // });
- if (distanceY < nearestNodeDistanceY) {
- nearestNodeDistanceY = distanceY;
- nearestNodeList = [];
- nearestNodeDistanceList = [];
- }
+ // nearestNodeDistanceList.push(distanceX);
- if (distanceY === nearestNodeDistanceY) {
- nearestNodeList.push({
- node: span,
- ratioX: x / (startX_fin + endX_fin),
- ratioY: y / (startY_fin + endY_fin),
- });
+ // nearestNodeDistanceY = -Infinity;
+ // continue;
+ // }
- nearestNodeDistanceList.push(distanceX);
- }
- }
- this._findLiquid.translateRestore();
- }
- this._findLiquid.translateRestore();
- }
- }
- }
- }
- this._findLiquid.restorePagePadding(page);
- this._translatePage(page);
- }
+ // if (distanceY < nearestNodeDistanceY) {
+ // nearestNodeDistanceY = distanceY;
+ // nearestNodeList = [];
+ // nearestNodeDistanceList = [];
+ // }
+
+ // if (distanceY === nearestNodeDistanceY) {
+ // nearestNodeList.push({
+ // node: span,
+ // ratioX: x / (startX_fin + endX_fin),
+ // ratioY: y / (startY_fin + endY_fin),
+ // });
+
+ // nearestNodeDistanceList.push(distanceX);
+ // }
+ // }
+ // this._findLiquid.translateRestore();
+ // }
+ // this._findLiquid.translateRestore();
+ // }
+ // }
+ // }
+ // }
+ // this._findLiquid.restorePagePadding(page);
+ // this._translatePage(page);
+ // }
- return this._getNearestNode(nearestNodeList, nearestNodeDistanceList);
- }
+ // return this._getNearestNode(nearestNodeList, nearestNodeDistanceList);
+ // }
// override findCoordByNode(span: IDocumentSkeletonSpan) {
// const divide = span.parent;
@@ -720,12 +722,6 @@ export class Documents extends DocComponent {
this.draw(ctx, bounds);
}
- private _getNearestNode(nearestNodeList: INodeInfo[], nearestNodeDistanceList: number[]) {
- const miniValue = Math.min(...nearestNodeDistanceList);
- const miniValueIndex = nearestNodeDistanceList.indexOf(miniValue);
- return nearestNodeList[miniValueIndex];
- }
-
private _horizontalHandler(
pageWidth: number,
pagePaddingLeft: number,
@@ -814,29 +810,29 @@ export class Documents extends DocComponent {
skeleton.onRecalculateChangeObservable.remove(this._skeletonObserver);
}
- private _getPageBoundingBox(page: IDocumentSkeletonPage) {
- const { pageWidth, pageHeight } = page;
- const { x: startX, y: startY } = this._findLiquid;
-
- let endX = -1;
- let endY = -1;
- if (this.pageLayoutType === PageLayoutType.VERTICAL) {
- endX = pageWidth;
- endY = startY + pageHeight;
- } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
- endX = startX + pageWidth;
- endY = pageHeight;
- }
+ // private _getPageBoundingBox(page: IDocumentSkeletonPage) {
+ // const { pageWidth, pageHeight } = page;
+ // const { x: startX, y: startY } = this._findLiquid;
- return {
- startX,
- startY,
- endX,
- endY,
- };
- }
+ // let endX = -1;
+ // let endY = -1;
+ // if (this.pageLayoutType === PageLayoutType.VERTICAL) {
+ // endX = pageWidth;
+ // endY = startY + pageHeight;
+ // } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
+ // endX = startX + pageWidth;
+ // endY = pageHeight;
+ // }
- private _translatePage(page: IDocumentSkeletonPage) {
- this._findLiquid.translatePage(page, this.pageLayoutType, this.pageMarginLeft, this.pageMarginTop);
- }
+ // return {
+ // startX,
+ // startY,
+ // endX,
+ // endY,
+ // };
+ // }
+
+ // private _translatePage(page: IDocumentSkeletonPage) {
+ // this._findLiquid.translatePage(page, this.pageLayoutType, this.pageMarginLeft, this.pageMarginTop);
+ // }
}
diff --git a/packages/base-render/src/Component/Docs/index.ts b/packages/base-render/src/Component/Docs/index.ts
index b4f94423a1..7698fdcf20 100644
--- a/packages/base-render/src/Component/Docs/index.ts
+++ b/packages/base-render/src/Component/Docs/index.ts
@@ -1,7 +1,7 @@
-export * from './Block';
-export * from './Common';
-export * from './DocSkeleton';
-export * from './Document';
-export * from './Document.Editor';
-export * from './HorizonBar';
-export * from './VerticalBar';
+export * from './Block';
+export * from './Common';
+export * from './DocSkeleton';
+export * from './Document';
+export * from './HorizonBar';
+export * from './text-selection-render-manager';
+export * from './VerticalBar';
diff --git a/packages/base-render/src/Component/Docs/Document.Editor.ts b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
similarity index 55%
rename from packages/base-render/src/Component/Docs/Document.Editor.ts
rename to packages/base-render/src/Component/Docs/text-selection-render-manager.ts
index a46b175f45..3794790e41 100644
--- a/packages/base-render/src/Component/Docs/Document.Editor.ts
+++ b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
@@ -1,41 +1,135 @@
-import { DataStreamTreeTokenType, Nullable, Observable, Observer, RxDisposable } from '@univerjs/core';
-import { fromEvent, Observable as RxObservable, share, takeUntil } from 'rxjs';
+import { DataStreamTreeTokenType, Nullable, Observer, RxDisposable } from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
+import { BehaviorSubject, Observable } from 'rxjs';
import { CURSOR_TYPE } from '../../Basics/Const';
-import { IDocumentSkeletonCached } from '../../Basics/IDocumentSkeletonCached';
+import { IDocumentSkeletonCached, PageLayoutType } from '../../Basics/IDocumentSkeletonCached';
import { IMouseEvent, IPointerEvent } from '../../Basics/IEvents';
import { INodeInfo, INodePosition } from '../../Basics/Interfaces';
import { getOffsetRectForDom, transformBoundingCoord } from '../../Basics/Position';
import { getCurrentScrollXY } from '../../Basics/ScrollXY';
+import {
+ ITextSelectionRangeWithStyle,
+ ITextSelectionStyle,
+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+} from '../../Basics/TextSelection';
import { checkStyle, injectStyle } from '../../Basics/Tools';
+import { Transform } from '../../Basics/Transform';
import { Vector2 } from '../../Basics/Vector2';
+import { Scene } from '../../Scene';
import { ScrollTimer } from '../../ScrollTimer';
import { IScrollObserverParam, Viewport } from '../../Viewport';
import { TextSelection } from './Common/TextSelection';
-import { DocComponent } from './DocComponent';
+import { DocumentSkeleton } from './DocSkeleton';
+import { IDocumentOffsetConfig } from './Document';
+
+export interface ITextSelectionRenderManager {
+ readonly onKeydown$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onInput$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onCompositionstart$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onCompositionupdate$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onCompositionend$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onSelectionStart$: Observable<Nullable<INodePosition>>;
+ readonly onPaste$: Observable<Nullable<IEditorInputConfig>>;
+
+ readonly textSelection$: Observable<TextSelection[]>;
+
+ enableSelection(): void;
+
+ disableSelection(): void;
+
+ setSegment(id: string): void;
+
+ setStyle(style: ITextSelectionStyle): void;
+
+ resetStyle(): void;
+
+ getActiveTextSelection(): Nullable<TextSelection>;
+
+ getTextSelectionList(): TextSelection[];
+
+ add(textSelection: Nullable<TextSelection>): void;
+
+ remain(): Nullable<TextSelection>;
+
+ sync(): void;
+
+ scroll(): void;
+
+ active(x: number, y: number): void;
+
+ focus(): void;
+
+ deactivate(withoutBlur: boolean): void;
+
+ changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene): void;
+
+ dispose(): void;
+
+ reset(): void;
+
+ activate(toLastPosition: boolean): void;
+
+ getRanges(): Array<Nullable<ITextSelectionRangeWithStyle>>;
+
+ getActiveRange(): Nullable<ITextSelectionRangeWithStyle>;
+
+ eventTrigger(evt: IPointerEvent | IMouseEvent, documentOffsetConfig: IDocumentOffsetConfig): void;
+}
export interface IEditorInputConfig {
event: Event | CompositionEvent | KeyboardEvent;
content?: string;
- document: DocComponent;
- activeSelection?: TextSelection;
+ activeRange?: Nullable<ITextSelectionRangeWithStyle>;
selectionList?: TextSelection[];
}
-export class DocsEditor extends RxDisposable {
- onKeydownObservable = new Observable<IEditorInputConfig>();
+export class TextSelectionRenderManager extends RxDisposable implements ITextSelectionRenderManager {
+ // onKeydownObservable = new Observable<IEditorInputConfig>();
- onInputObservable = new Observable<IEditorInputConfig>();
+ // onInputObservable = new Observable<IEditorInputConfig>();
- onCompositionstartObservable = new Observable<IEditorInputConfig>();
+ // onCompositionstartObservable = new Observable<IEditorInputConfig>();
- onCompositionupdateObservable = new Observable<IEditorInputConfig>();
+ // onCompositionupdateObservable = new Observable<IEditorInputConfig>();
- onCompositionendObservable = new Observable<IEditorInputConfig>();
+ // onCompositionendObservable = new Observable<IEditorInputConfig>();
- onSelectionStartObservable = new Observable<Nullable<INodePosition>>();
+ // onSelectionStartObservable = new Observable<Nullable<INodePosition>>();
- onPaste$!: RxObservable<ClipboardEvent>;
+ private readonly _onKeydown$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
+
+ readonly onKeydown$ = this._onKeydown$.asObservable();
+
+ private readonly _onInput$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
+
+ readonly onInput$ = this._onInput$.asObservable();
+
+ private readonly _onCompositionstart$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
+
+ readonly onCompositionstart$ = this._onCompositionstart$.asObservable();
+
+ private readonly _onCompositionupdate$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
+
+ readonly onCompositionupdate$ = this._onCompositionupdate$.asObservable();
+
+ private readonly _onCompositionend$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
+
+ readonly onCompositionend$ = this._onCompositionend$.asObservable();
+
+ private readonly _onSelectionStart$ = new BehaviorSubject<Nullable<INodePosition>>(null);
+
+ readonly onSelectionStart$ = this._onSelectionStart$.asObservable();
+
+ private readonly _onPaste$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
+
+ readonly onPaste$ = this._onPaste$.asObservable();
+
+ private readonly _textSelection$ = new BehaviorSubject<TextSelection[]>([]);
+
+ readonly textSelection$ = this._textSelection$.asObservable();
+
+ // onPaste$!: RxObservable<ClipboardEvent>;
private _container!: HTMLDivElement;
@@ -45,16 +139,10 @@ export class DocsEditor extends RxDisposable {
private _cursor!: HTMLDivElement;
- private _downObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
- private _moveInObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _moveOutObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
private _skeletonObserver: Nullable<Observer<IDocumentSkeletonCached>>;
private _viewportScrollX: number = 0;
@@ -65,6 +153,20 @@ export class DocsEditor extends RxDisposable {
private _activeViewport: Nullable<Viewport>;
+ private _currentSegmentId: string = '';
+
+ private _documentOffsetConfig: IDocumentOffsetConfig = {
+ documentTransform: new Transform(),
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ docsLeft: 0,
+ docsTop: 0,
+ };
+
+ private _selectionStyle: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE;
+
+ private _isSelectionEnabled: boolean = true;
private _viewPortObserverMap = new Map<
string,
{
@@ -75,13 +177,16 @@ export class DocsEditor extends RxDisposable {
private _isIMEInputApply = false;
- constructor(private _documents?: DocComponent) {
+ constructor(
+ private _docSkeleton?: Nullable<DocumentSkeleton>,
+ private _scene?: Nullable<Scene>
+ ) {
super();
this._initDOM();
- this.activeViewport = this._documents?.getFirstViewport();
- if (this._documents) {
- this.changeDocuments(this._documents);
+ // this.activeViewport = this._documents?.getFirstViewport();
+ if (this._docSkeleton && this._scene) {
+ this.changeRuntime(this._docSkeleton, this._scene);
}
}
@@ -90,8 +195,24 @@ export class DocsEditor extends RxDisposable {
this._activeViewport = viewport;
}
- static create(documents?: DocComponent) {
- return new DocsEditor(documents);
+ setSegment(id: string) {
+ this._currentSegmentId = id;
+ }
+
+ setStyle(style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE) {
+ this._selectionStyle = style;
+ }
+
+ resetStyle() {
+ this.setStyle();
+ }
+
+ enableSelection() {
+ this._isSelectionEnabled = true;
+ }
+
+ disableSelection() {
+ this._isSelectionEnabled = false;
}
getActiveTextSelection() {
@@ -107,7 +228,10 @@ export class DocsEditor extends RxDisposable {
return this._textSelectionList;
}
- add(textSelection: TextSelection) {
+ add(textSelection: Nullable<TextSelection>) {
+ if (textSelection == null) {
+ return;
+ }
this._addTextSelection(textSelection);
}
@@ -129,6 +253,35 @@ export class DocsEditor extends RxDisposable {
this._scrollToSelection();
}
+ getRanges(): Array<Nullable<ITextSelectionRangeWithStyle>> {
+ return this.getTextSelectionList()
+ .map((textSelection) => {
+ const range = textSelection.getRange();
+ if (range == null) {
+ return;
+ }
+ return {
+ ...range,
+ segmentId: this._currentSegmentId,
+ style: this._selectionStyle,
+ };
+ })
+ .filter((x) => x != null);
+ }
+
+ getActiveRange(): Nullable<ITextSelectionRangeWithStyle> {
+ const range = this.getActiveTextSelection()?.getRange();
+ if (range == null) {
+ return;
+ }
+
+ return {
+ ...range,
+ segmentId: this._currentSegmentId,
+ style: this._selectionStyle,
+ };
+ }
+
activate(toLastPosition = false): void {
// const documents = this._documents;
// if (!documents) {
@@ -188,7 +341,7 @@ export class DocsEditor extends RxDisposable {
}
// FIXME: for editor cell editor we don't need to blur the input element
- deactivate(withoutBlur = true) {
+ deactivate(withoutBlur: boolean = true) {
this._container.style.left = `0px`;
this._container.style.top = `0px`;
@@ -200,26 +353,122 @@ export class DocsEditor extends RxDisposable {
}
}
- changeDocuments(documents: DocComponent) {
- if (this._documents) {
- this._detachEvent(this._documents);
+ changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene) {
+ this._docSkeleton?.onRecalculateChangeObservable.remove(this._skeletonObserver);
+
+ this._docSkeleton = docSkeleton;
+
+ this._scene = scene;
+
+ this.activeViewport = scene.getViewports()[0];
+
+ // this._attachSelectionEvent(this._documents);
+ }
+
+ eventTrigger(evt: IPointerEvent | IMouseEvent, documentOffsetConfig: IDocumentOffsetConfig) {
+ // this._moveInObserver = documents.onPointerEnterObserver.add(() => {
+ // documents.cursor = CURSOR_TYPE.TEXT;
+ // });
+
+ // this._moveOutObserver = documents.onPointerLeaveObserver.add(() => {
+ // documents.cursor = CURSOR_TYPE.DEFAULT;
+ // this._scene?.resetCursor();
+ // });
+
+ // this._downObserver = documents.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+
+ // });
+
+ if (!this._scene || !this._isSelectionEnabled) {
+ return;
+ }
+
+ const scene = this._scene;
+
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ this.activeViewport = scene.getActiveViewportByCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+
+ this._documentOffsetConfig = documentOffsetConfig;
+
+ const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY);
+
+ const position = this._getNodePosition(startNode);
+
+ console.log('startNode', startNode, position, evtOffsetX, evtOffsetY);
+
+ if (position == null) {
+ this._deleteAllTextSelection();
+ return;
+ }
+
+ if (startNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH) {
+ position.isBack = true;
+ }
+
+ if (evt.ctrlKey || this._isEmptyTextSelection()) {
+ const newTextSelection = new TextSelection(scene, position);
+ this._addTextSelection(newTextSelection);
+ } else {
+ this._updateTextSelection(position);
}
- this._documents = documents;
- this._skeletonObserver = documents
- .getSkeleton()
- ?.onRecalculateChangeObservable.add((data: IDocumentSkeletonCached) => {
- this._deleteAllTextSelection();
+ this._activeSelectionRefresh();
+
+ this._syncDomToSelection();
+
+ scene.disableEvent();
+
+ const scrollTimer = ScrollTimer.create(scene);
+ scrollTimer.startScroll(evtOffsetX, evtOffsetY);
+
+ const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
+
+ this._viewportScrollX = scrollX;
+ this._viewportScrollY = scrollY;
+
+ this._onSelectionStart$.next(this.getActiveTextSelection()?.getStart());
+
+ let preMoveOffsetX = evtOffsetX;
+
+ let preMoveOffsetY = evtOffsetY;
+
+ this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+ scene.setCursor(CURSOR_TYPE.TEXT);
+ if (Math.sqrt((moveOffsetX - preMoveOffsetX) ** 2 + (moveOffsetY - preMoveOffsetY) ** 2) < 3) {
+ return;
+ }
+ this._moving(moveOffsetX, moveOffsetY, scrollTimer);
+ scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
+ this._moving(moveOffsetX, moveOffsetY, scrollTimer);
});
- this._attachSelectionEvent(this._documents);
+ preMoveOffsetX = moveOffsetX;
+ preMoveOffsetY = moveOffsetY;
+ });
+
+ this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
+ scene.onPointerMoveObserver.remove(this._moveObserver);
+ scene.onPointerUpObserver.remove(this._upObserver);
+ scene.enableEvent();
+
+ this._textSelection$.next(this.getTextSelectionList());
+
+ scrollTimer.dispose();
+ });
+
+ // state.stopPropagation();
+ }
+
+ reset() {
+ this._deleteAllTextSelection();
+ this.deactivate();
}
override dispose() {
super.dispose();
- if (this._documents) {
- this._detachEvent(this._documents);
- }
+ this._detachEvent();
+
this._container.remove();
}
@@ -341,10 +590,6 @@ export class DocsEditor extends RxDisposable {
}
}
- private _getSkeletonData() {
- return this._documents?.getSkeleton()?.getSkeletonData();
- }
-
private _getNodePosition(node: Nullable<INodeInfo>) {
if (node == null) {
return;
@@ -352,7 +597,7 @@ export class DocsEditor extends RxDisposable {
const { node: span, ratioX, ratioY } = node;
- const position = this._documents?.findPositionBySpan(span);
+ const position = this._docSkeleton?.findPositionBySpan(span);
if (position == null) {
return;
@@ -412,12 +657,12 @@ export class DocsEditor extends RxDisposable {
}
private _updateTextSelection(position: INodePosition) {
- if (!this._documents) {
+ if (!this._scene) {
return;
}
let lastTextSelection = this._textSelectionList.pop();
if (!lastTextSelection) {
- lastTextSelection = new TextSelection(this._documents.getScene(), position);
+ lastTextSelection = new TextSelection(this._scene, position);
}
this._deleteAllTextSelection();
lastTextSelection.activate();
@@ -431,7 +676,7 @@ export class DocsEditor extends RxDisposable {
}
private _getCanvasOffset() {
- const engine = this._documents?.getEngine();
+ const engine = this._scene?.getEngine();
const canvas = engine?.getCanvasElement();
if (!canvas) {
@@ -510,11 +755,11 @@ export class DocsEditor extends RxDisposable {
// const endX = moveOffsetX - this._viewportScrollX + scrollX;
// const endY = moveOffsetY - this._viewportScrollY + scrollY;
- if (!this._documents) {
+ if (this._docSkeleton == null) {
return;
}
- const endNode = this._documents.findNodeByCoord(moveOffsetX, moveOffsetY);
+ const endNode = this._findNodeByCoord(moveOffsetX, moveOffsetY);
const endPosition = this._getNodePosition(endNode);
@@ -532,7 +777,9 @@ export class DocsEditor extends RxDisposable {
activeTextSelection.endNodePosition = endPosition;
- activeTextSelection.refresh(this._documents);
+ activeTextSelection.refresh(this._documentOffsetConfig, this._docSkeleton);
+
+ this.deactivate();
this._interactTextSelection(activeTextSelection);
}
@@ -604,18 +851,9 @@ export class DocsEditor extends RxDisposable {
if (this._isIMEInputApply) {
return;
}
- const activeSelection = this.getActiveTextSelection();
- const selectionList = this.getTextSelectionList();
- if (this._documents == null) {
- return;
- }
- this._input.innerHTML = '';
- this.onKeydownObservable.notifyObservers({
- event: e,
- content: '',
- document: this._documents,
- activeSelection,
- selectionList,
+
+ this._eventHandle(e, (config) => {
+ this._onKeydown$.next(config);
});
});
@@ -624,208 +862,113 @@ export class DocsEditor extends RxDisposable {
return;
}
- const content = this._input.textContent || '';
-
- this._input.innerHTML = '';
-
- const activeSelection = this.getActiveTextSelection();
- const selectionList = this.getTextSelectionList();
-
- if (this._documents == null) {
- return;
- }
- this.onInputObservable.notifyObservers({
- event: e,
- content,
- document: this._documents,
- activeSelection,
- selectionList,
+ this._eventHandle(e, (config) => {
+ this._onInput$.next(config);
});
});
this._input.addEventListener('compositionstart', (e) => {
this._isIMEInputApply = true;
- const content = this._input.textContent || '';
-
- this._input.innerHTML = '';
-
- const activeSelection = this.getActiveTextSelection();
- const selectionList = this.getTextSelectionList();
-
- if (this._documents == null) {
- return;
- }
-
- this.onCompositionstartObservable.notifyObservers({
- event: e,
- content,
- document: this._documents,
- activeSelection,
- selectionList,
+ this._eventHandle(e, (config) => {
+ this._onCompositionstart$.next(config);
});
});
this._input.addEventListener('compositionend', (e) => {
this._isIMEInputApply = false;
- const content = this._input.textContent || '';
-
- this._input.innerHTML = '';
-
- const activeSelection = this.getActiveTextSelection();
- const selectionList = this.getTextSelectionList();
-
- if (this._documents == null) {
- return;
- }
- this.onCompositionendObservable.notifyObservers({
- event: e,
- content,
- document: this._documents,
- activeSelection,
- selectionList,
+ this._eventHandle(e, (config) => {
+ this._onCompositionend$.next(config);
});
});
this._input.addEventListener('compositionupdate', (e) => {
- const content = this._input.textContent || '';
+ this._eventHandle(e, (config) => {
+ this._onCompositionupdate$.next(config);
+ });
+ });
- this._input.innerHTML = '';
+ this._input.addEventListener('paste', (e) => {
+ this._eventHandle(e, (config) => {
+ this._onPaste$.next(config);
+ });
+ });
+ }
- const activeSelection = this.getActiveTextSelection();
- const selectionList = this.getTextSelectionList();
+ private _eventHandle(e: Event | CompositionEvent | KeyboardEvent, func: (config: IEditorInputConfig) => void) {
+ const content = this._input.textContent || '';
- if (this._documents == null) {
- return;
- }
+ this._input.innerHTML = '';
- this.onCompositionupdateObservable.notifyObservers({
- event: e,
- content,
- document: this._documents,
- activeSelection,
- selectionList,
- });
- });
+ const activeRange = this.getActiveRange();
+ const selectionList = this.getTextSelectionList();
- this.onPaste$ = (fromEvent(this._input, 'paste') as RxObservable<ClipboardEvent>).pipe(
- takeUntil(this.dispose$),
- share()
- );
+ func({
+ event: e,
+ content,
+ activeRange,
+ selectionList,
+ });
}
private _handlePaste(e: ClipboardEvent) {
// TODO: emit the paste event to subscribers
}
- // eslint-disable-next-line max-lines-per-function
- private _attachSelectionEvent(documents: DocComponent) {
- this._moveInObserver = documents.onPointerEnterObserver.add(() => {
- documents.cursor = CURSOR_TYPE.TEXT;
- });
-
- this._moveOutObserver = documents.onPointerLeaveObserver.add(() => {
- documents.cursor = CURSOR_TYPE.DEFAULT;
- scene.resetCursor();
- });
- const scene = documents.getScene();
-
- this._downObserver = documents.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
- if (!this._documents) {
- return;
- }
-
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- this.activeViewport = this._documents.getActiveViewportByCoord(evtOffsetX, evtOffsetY);
-
- const startNode = this._documents.findNodeByCoord(evtOffsetX, evtOffsetY);
-
- const position = this._getNodePosition(startNode);
-
- console.log('startNode', startNode, position, evtOffsetX, evtOffsetY);
-
- if (position == null) {
- this._deleteAllTextSelection();
- return;
- }
-
- if (startNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH) {
- position.isBack = true;
- }
-
- if (evt.ctrlKey || this._isEmptyTextSelection()) {
- const newTextSelection = new TextSelection(this._documents.getScene(), position);
- this._addTextSelection(newTextSelection);
- } else {
- this._updateTextSelection(position);
- }
-
- this._activeSelectionRefresh();
-
- this._syncDomToSelection();
-
- scene.disableEvent();
-
- const scrollTimer = ScrollTimer.create(scene);
- scrollTimer.startScroll(evtOffsetX, evtOffsetY);
-
- const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
-
- this._viewportScrollX = scrollX;
- this._viewportScrollY = scrollY;
+ private _getTransformCoordForDocumentOffset(evtOffsetX: number, evtOffsetY: number) {
+ const { documentTransform } = this._documentOffsetConfig;
+ if (this._scene == null || documentTransform == null) {
+ return;
+ }
+ this.activeViewport = this._scene.getActiveViewportByCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
- this.onSelectionStartObservable.notifyObservers(this.getActiveTextSelection()?.getStart());
+ const originCoord = this._scene.transformToSceneCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
- let preMoveOffsetX = evtOffsetX;
+ if (!originCoord) {
+ return;
+ }
- let preMoveOffsetY = evtOffsetY;
+ return documentTransform.clone().invert().applyPoint(originCoord);
+ }
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- scene.setCursor(CURSOR_TYPE.TEXT);
- if (Math.sqrt((moveOffsetX - preMoveOffsetX) ** 2 + (moveOffsetY - preMoveOffsetY) ** 2) < 3) {
- return;
- }
- this._moving(moveOffsetX, moveOffsetY, scrollTimer);
- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
- this._moving(moveOffsetX, moveOffsetY, scrollTimer);
- });
- preMoveOffsetX = moveOffsetX;
- preMoveOffsetY = moveOffsetY;
- });
+ private _findNodeByCoord(evtOffsetX: number, evtOffsetY: number) {
+ const coord = this._getTransformCoordForDocumentOffset(evtOffsetX, evtOffsetY);
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
+ if (coord == null) {
+ return;
+ }
- scrollTimer.dispose();
- });
+ const { pageLayoutType = PageLayoutType.VERTICAL, pageMarginLeft, pageMarginTop } = this._documentOffsetConfig;
- // state.stopPropagation();
- });
+ return this._docSkeleton?.findNodeByCoord(coord, pageLayoutType, pageMarginLeft, pageMarginTop);
}
- private _detachEvent(documents: DocComponent) {
- documents.onPointerEnterObserver.remove(this._moveInObserver);
- documents.onPointerLeaveObserver.remove(this._moveOutObserver);
- documents.onPointerDownObserver.remove(this._downObserver);
- documents.getSkeleton()?.onRecalculateChangeObservable.remove(this._skeletonObserver);
- this.onKeydownObservable.clear();
- this.onInputObservable.clear();
- this.onCompositionstartObservable.clear();
- this.onCompositionupdateObservable.clear();
- this.onCompositionendObservable.clear();
- this.onSelectionStartObservable.clear();
+ private _detachEvent() {
+ // documents.onPointerEnterObserver.remove(this._moveInObserver);
+ // documents.onPointerLeaveObserver.remove(this._moveOutObserver);
+ // documents.onPointerDownObserver.remove(this._downObserver);
+ this._docSkeleton?.onRecalculateChangeObservable.remove(this._skeletonObserver);
+ this._onKeydown$.complete();
+ this._onInput$.complete();
+ this._onCompositionstart$.complete();
+ this._onCompositionupdate$.complete();
+ this._onCompositionend$.complete();
+ this._onSelectionStart$.complete();
}
private _activeSelectionRefresh() {
- if (!this._documents) {
+ if (this._docSkeleton == null) {
return;
}
const activeSelection = this.getActiveTextSelection();
- activeSelection?.refresh(this._documents);
+ activeSelection?.refresh(this._documentOffsetConfig, this._docSkeleton);
+
+ // this._activeSelectionRefresh$.next(activeSelection);
}
}
+
+export const ITextSelectionRenderManager = createIdentifier<TextSelectionRenderManager>(
+ 'deprecated.univer.doc.text-selection-render-manager'
+);
diff --git a/packages/base-render/src/Component/Sheets/ColumnHeader.ts b/packages/base-render/src/Component/Sheets/ColumnHeader.ts
index a6f014a1bd..40d13e09f7 100644
--- a/packages/base-render/src/Component/Sheets/ColumnHeader.ts
+++ b/packages/base-render/src/Component/Sheets/ColumnHeader.ts
@@ -1,7 +1,6 @@
import { getTranslateInSpreadContextWithPixelRatio } from '../../Basics/Draw';
import { fixLineWidthByScale, getScale } from '../../Basics/Tools';
import { IBoundRect, Vector2 } from '../../Basics/Vector2';
-import { Engine } from '../../Engine';
import { SheetColumnHeaderExtensionRegistry } from '../Extension';
import { ColumnHeaderLayout } from './Extensions/ColumnHeaderLayout';
import { SpreadsheetHeader } from './SheetComponent';
@@ -42,11 +41,9 @@ export class SpreadsheetColumnHeader extends SpreadsheetHeader {
const { rowHeaderWidth } = spreadsheetSkeleton;
- const engine = this.getScene().getEngine() as Engine;
+ const { left: fixTranslateLeft, top: fixTranslateTop } = getTranslateInSpreadContextWithPixelRatio();
- const fixTranslate = getTranslateInSpreadContextWithPixelRatio(engine.getPixelRatio());
-
- ctx.translate(fixLineWidthByScale(rowHeaderWidth, scale) - fixTranslate / scale, -fixTranslate / scale);
+ ctx.translate(fixLineWidthByScale(rowHeaderWidth, scale) - fixTranslateLeft / scale, -fixTranslateTop / scale);
const extensions = this.getExtensionsByOrder();
for (const extension of extensions) {
diff --git a/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts b/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
index 9075a9c9b2..bb0a4c12a3 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
@@ -1,7 +1,9 @@
import { BooleanNumber, IRange, IScale } from '@univerjs/core';
+import { clearLineByBorderType, getLineWith } from '../../../Basics/Draw';
import { fixLineWidthByScale, getColor } from '../../../Basics/Tools';
import { SpreadsheetExtensionRegistry } from '../../Extension';
+import { BorderCacheItem } from '../Interfaces';
import { SpreadsheetSkeleton } from '../SheetSkeleton';
import { SheetExtension } from './SheetExtension';
@@ -22,7 +24,7 @@ export class BorderAuxiliary extends SheetExtension {
stylesCache,
showGridlines,
} = spreadsheetSkeleton;
-
+ const { border } = stylesCache;
const { startRow, endRow, startColumn, endColumn } = rowColumnSegment;
if (!spreadsheetSkeleton || showGridlines === BooleanNumber.FALSE) {
return;
@@ -43,8 +45,8 @@ export class BorderAuxiliary extends SheetExtension {
ctx.save();
const scale = this._getScale(parentScale);
ctx.beginPath();
- ctx.lineWidth = 1 / scale;
- ctx.strokeStyle = getColor([217, 217, 217])!;
+ ctx.lineWidth = getLineWith(1) / scale;
+ ctx.strokeStyle = getColor([212, 212, 212])!;
const width = fixLineWidthByScale(columnTotalWidth, scale);
const height = fixLineWidthByScale(rowTotalHeight, scale);
const columnWidthAccumulationLength = columnWidthAccumulation.length;
@@ -70,6 +72,52 @@ export class BorderAuxiliary extends SheetExtension {
ctx.stroke();
ctx.closePath();
+ const { scaleX = 1, scaleY = 1 } = parentScale;
+
+ // Clearing the dashed line issue caused by overlaid auxiliary lines and strokes
+ border?.forValue((rowIndex, columnIndex, borderCaches) => {
+ if (!borderCaches) {
+ return true;
+ }
+
+ const cellInfo = this.getCellIndex(
+ rowIndex,
+ columnIndex,
+ rowHeightAccumulation,
+ columnWidthAccumulation,
+ dataMergeCache
+ );
+
+ let { startY, endY, startX, endX } = cellInfo;
+ const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;
+
+ if (isMerged) {
+ return true;
+ }
+
+ if (isMergedMainCell) {
+ startY = mergeInfo.startY;
+ endY = mergeInfo.endY;
+ startX = mergeInfo.startX;
+ endX = mergeInfo.endX;
+ }
+
+ startY = fixLineWidthByScale(startY, scaleY);
+ endY = fixLineWidthByScale(endY, scaleY);
+ startX = fixLineWidthByScale(startX, scaleX);
+ endX = fixLineWidthByScale(endX, scaleX);
+
+ for (const key in borderCaches) {
+ const { type, style, color } = borderCaches[key] as BorderCacheItem;
+
+ // if (color.indexOf('255,255,255') === -1 || color.toLocaleLowerCase() !== '#ffffff') {
+ // continue;
+ // }
+
+ clearLineByBorderType(ctx, type, { startX, startY, endX, endY }, scaleX, scaleY);
+ }
+ });
+ ctx.closePath();
// merge cell
this._clearRectangle(ctx, scale, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
diff --git a/packages/base-render/src/Component/Sheets/RowHeader.ts b/packages/base-render/src/Component/Sheets/RowHeader.ts
index e655bd358a..90a9a0e050 100644
--- a/packages/base-render/src/Component/Sheets/RowHeader.ts
+++ b/packages/base-render/src/Component/Sheets/RowHeader.ts
@@ -1,7 +1,6 @@
import { getTranslateInSpreadContextWithPixelRatio } from '../../Basics/Draw';
import { fixLineWidthByScale, getScale } from '../../Basics/Tools';
import { IBoundRect, Vector2 } from '../../Basics/Vector2';
-import { Engine } from '../../Engine';
import { SheetRowHeaderExtensionRegistry } from '../Extension';
import { RowHeaderLayout } from './Extensions/RowHeaderLayout';
import { SpreadsheetHeader } from './SheetComponent';
@@ -42,11 +41,12 @@ export class SpreadsheetRowHeader extends SpreadsheetHeader {
const { columnHeaderHeight } = spreadsheetSkeleton;
- const engine = this.getScene().getEngine() as Engine;
+ const { left: fixTranslateLeft, top: fixTranslateTop } = getTranslateInSpreadContextWithPixelRatio();
- const fixTranslate = getTranslateInSpreadContextWithPixelRatio(engine.getPixelRatio());
-
- ctx.translate(-fixTranslate / scale, fixLineWidthByScale(columnHeaderHeight, scale) - fixTranslate / scale);
+ ctx.translate(
+ -fixTranslateLeft / scale,
+ fixLineWidthByScale(columnHeaderHeight, scale) - fixTranslateTop / scale
+ );
const extensions = this.getExtensionsByOrder();
for (const extension of extensions) {
diff --git a/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
index 049c548ed2..4ae15133f2 100644
--- a/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
@@ -117,7 +117,6 @@ export class SelectionTransformerShapeManager implements ISelectionTransformerSh
private readonly _selectionRangeWithStyle$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
- // eslint-disable-next-line @typescript-eslint/member-ordering
readonly selectionRangeWithStyle$ = this._selectionRangeWithStyle$.asObservable();
static create() {
diff --git a/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape.ts b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape.ts
index ff66003f80..a9104deb65 100644
--- a/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape.ts
@@ -367,7 +367,7 @@ export class SelectionTransformerShape {
this._columnHeaderHeight = columnHeaderHeight || 0;
- this.selectionShape.makeDirty(true);
+ this.selectionShape.makeDirtyNoDebounce(true);
}
update(
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index 70c46edac5..d9b2a1177a 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -128,15 +128,13 @@ export class Spreadsheet extends SheetComponent {
const scale = getScale(parentScale);
- const engine = this.getScene().getEngine() as Engine;
-
- const fixTranslate = getTranslateInSpreadContextWithPixelRatio(engine.getPixelRatio());
+ const { left: fixTranslateLeft, top: fixTranslateTop } = getTranslateInSpreadContextWithPixelRatio();
const { rowHeaderWidth, columnHeaderHeight } = spreadsheetSkeleton;
ctx.translate(
- fixLineWidthByScale(rowHeaderWidth, scale) - fixTranslate / scale,
- fixLineWidthByScale(columnHeaderHeight, scale) - fixTranslate / scale
+ fixLineWidthByScale(rowHeaderWidth, scale) - fixTranslateLeft / scale,
+ fixLineWidthByScale(columnHeaderHeight, scale) - fixTranslateTop / scale
);
// insert overflow cache
diff --git a/packages/base-render/src/Component/Skeleton.ts b/packages/base-render/src/Component/Skeleton.ts
index 156a7ffb21..3c36b735a8 100644
--- a/packages/base-render/src/Component/Skeleton.ts
+++ b/packages/base-render/src/Component/Skeleton.ts
@@ -28,25 +28,25 @@ export class Skeleton extends Disposable {
private _localeInitial() {
// TODO: should be load from config file
- this._fontLocale = {
- defaultFont: 'Times New Roman',
- fontList: [
- 'Times New Roman',
- 'Arial',
- 'Tahoma',
- 'Verdana',
- '微软雅黑',
- '宋体',
- '黑体',
- '楷体',
- '仿宋',
- '新宋体',
- '华文新魏',
- '华文行楷',
- '华文隶书',
- ],
- defaultFontSize: 14,
- unit: 'pt',
- } as IFontLocale;
+ // this._fontLocale = {
+ // defaultFont: 'Times New Roman',
+ // fontList: [
+ // 'Times New Roman',
+ // 'Arial',
+ // 'Tahoma',
+ // 'Verdana',
+ // '微软雅黑',
+ // '宋体',
+ // '黑体',
+ // '楷体',
+ // '仿宋',
+ // '新宋体',
+ // '华文新魏',
+ // '华文行楷',
+ // '华文隶书',
+ // ],
+ // defaultFontSize: 14,
+ // unit: 'pt',
+ // } as IFontLocale;
}
}
diff --git a/packages/base-render/src/Engine.ts b/packages/base-render/src/Engine.ts
index 13cc627839..2fee50d5d7 100644
--- a/packages/base-render/src/Engine.ts
+++ b/packages/base-render/src/Engine.ts
@@ -272,7 +272,7 @@ export class Engine extends ThinEngine<Scene> {
return null;
}
- if (this._canvasEle && this._canvasEle.ownerDocument && this._canvasEle.ownerDocument.defaultView) {
+ if (this._canvasEle?.ownerDocument?.defaultView) {
return this._canvasEle.ownerDocument.defaultView;
}
diff --git a/packages/base-render/src/Render-manager.service.ts b/packages/base-render/src/Render-manager.service.ts
index f094b6851b..14da8514ac 100644
--- a/packages/base-render/src/Render-manager.service.ts
+++ b/packages/base-render/src/Render-manager.service.ts
@@ -8,12 +8,13 @@ import { SheetComponent } from './Component/Sheets/SheetComponent';
import { Slide } from './Component/Slides/Slide';
import { Engine } from './Engine';
import { Scene } from './Scene';
+import { SceneViewer } from './SceneViewer';
export interface IRenderManagerService {
dispose(): void;
- createRenderWithNewEngine(unitId: string): IRenderManagerService;
- createRenderWithDefaultEngine(unitId: string): IRenderManagerService;
- createRender(unitId: string, engine: Engine): IRenderManagerService;
+ // createRenderWithNewEngine(unitId: string): IRenderManagerService;
+ createRenderWithParent(unitId: string, parentUnitId: string): IRender;
+ createRender(unitId: string): IRender;
addItem(unitId: string, item: IRender): void;
removeItem(unitId: string): void;
setCurrent(unitId: string): void;
@@ -30,6 +31,7 @@ export interface IRender {
scene: Scene;
mainComponent: Nullable<RenderComponentType>;
components: Map<string, RenderComponentType>;
+ isMainScene: boolean;
}
const DEFAULT_SCENE_SIZE = { width: 1500, height: 1000 };
@@ -61,16 +63,32 @@ export class RenderManagerService implements IRenderManagerService {
this._currentRender$.complete();
}
- createRenderWithNewEngine(unitId: string): RenderManagerService {
- const engine = new Engine();
- return this.createRender(unitId, engine);
+ createRenderWithParent(unitId: string, parentUnitId: string): IRender {
+ const parent = this.getRenderById(parentUnitId);
+ if (parent == null) {
+ throw new Error('parent render is null');
+ }
+ const { scene, engine } = parent;
+
+ const current = this._createRender(unitId, engine, false);
+
+ const currentScene = current.scene;
+
+ const sv = new SceneViewer(unitId);
+
+ sv.addSubScene(currentScene);
+
+ scene.addObject(sv);
+
+ return current;
}
- createRenderWithDefaultEngine(unitId: string): RenderManagerService {
- return this.createRender(unitId, this._defaultEngine);
+ createRender(unitId: string): IRender {
+ const engine = new Engine();
+ return this._createRender(unitId, engine);
}
- createRender(unitId: string, engine: Engine): RenderManagerService {
+ private _createRender(unitId: string, engine: Engine, isMainScene: boolean = true): IRender {
const existItem = this.getRenderById(unitId);
let shouldDestroyEngine = true;
if (existItem != null) {
@@ -94,11 +112,12 @@ export class RenderManagerService implements IRenderManagerService {
scene,
mainComponent: null,
components: new Map(),
+ isMainScene,
};
this.addItem(unitId, item);
- return this;
+ return item;
}
addItem(unitId: string, item: IRender) {
diff --git a/packages/base-render/src/Shape/Shape.ts b/packages/base-render/src/Shape/Shape.ts
index 15c2a9c068..60715c82b4 100644
--- a/packages/base-render/src/Shape/Shape.ts
+++ b/packages/base-render/src/Shape/Shape.ts
@@ -2,10 +2,11 @@ import { IKeyValue, IScale, Nullable } from '@univerjs/core';
import { BASE_OBJECT_ARRAY, BaseObject } from '../BaseObject';
import { SHAPE_TYPE } from '../Basics/Const';
+import { getDevicePixelRatio } from '../Basics/Draw';
import { IObjectFullState } from '../Basics/Interfaces';
import { transformBoundingCoord } from '../Basics/Position';
import { IBoundRect, Vector2 } from '../Basics/Vector2';
-import { Canvas, getDevicePixelRatio } from '../Canvas';
+import { Canvas } from '../Canvas';
export type LineJoin = 'round' | 'bevel' | 'miter';
export type LineCap = 'butt' | 'round' | 'square';
diff --git a/packages/base-render/src/services/object-transform-manager.service.ts b/packages/base-render/src/services/object-transform-manager.service.ts
new file mode 100644
index 0000000000..208d07a96d
--- /dev/null
+++ b/packages/base-render/src/services/object-transform-manager.service.ts
@@ -0,0 +1,166 @@
+import { Nullable } from '@univerjs/core';
+import { IDisposable } from '@wendellhu/redi';
+import { BehaviorSubject } from 'rxjs';
+
+export interface ITransformObject {
+ unitId: string;
+ objectId: string;
+ top?: number;
+ left?: number;
+ width?: number;
+ height?: number;
+ angle?: number;
+ scaleX?: number;
+ scaleY?: number;
+ skewX?: number;
+ skewY?: number;
+ flipX?: number;
+ flipY?: number;
+ strokeWidth?: number;
+}
+
+export interface IObjectTransformManagerSearch {
+ unitId: string;
+ objectId: string;
+}
+
+export interface IObjectTransformManagerInsert extends IObjectTransformManagerSearch {
+ object: ITransformObject;
+}
+
+/**
+ * This service is for worksheet build sheet skeleton.
+ */
+export class ObjectTransformManagerService implements IDisposable {
+ private _currentObject: IObjectTransformManagerSearch = {
+ unitId: '',
+ objectId: '',
+ };
+
+ private _objectParam: Map<string, Map<string, ITransformObject>> = new Map();
+
+ private readonly _currentObject$ = new BehaviorSubject<Nullable<ITransformObject>>(null);
+
+ readonly currentObject$ = this._currentObject$.asObservable();
+
+ dispose(): void {
+ this._currentObject$.complete();
+ this._objectParam = new Map();
+ }
+
+ updateObject(transformObject: ITransformObject) {
+ const {
+ unitId,
+ objectId,
+ top,
+ left,
+ width,
+ height,
+ angle,
+ scaleX,
+ scaleY,
+ skewX,
+ skewY,
+ flipX,
+ flipY,
+ strokeWidth,
+ } = transformObject;
+
+ const currentObject = this.getObjectBySearch({
+ unitId,
+ objectId,
+ });
+
+ if (currentObject == null) {
+ return;
+ }
+
+ if (top != null) {
+ currentObject.top = top;
+ }
+
+ if (left != null) {
+ currentObject.top = top;
+ }
+
+ if (width != null) {
+ currentObject.top = top;
+ }
+
+ if (height != null) {
+ currentObject.top = top;
+ }
+
+ if (angle != null) {
+ currentObject.top = top;
+ }
+
+ if (scaleX != null) {
+ currentObject.top = top;
+ }
+
+ if (scaleY != null) {
+ currentObject.top = top;
+ }
+
+ if (skewX != null) {
+ currentObject.top = top;
+ }
+
+ if (skewY != null) {
+ currentObject.top = top;
+ }
+
+ if (flipX != null) {
+ currentObject.top = top;
+ }
+
+ if (flipY != null) {
+ currentObject.top = top;
+ }
+
+ if (strokeWidth != null) {
+ currentObject.top = top;
+ }
+ }
+
+ setCurrent(searchParam: IObjectTransformManagerSearch) {
+ const { unitId, objectId } = searchParam;
+ this._currentObject = {
+ unitId,
+ objectId,
+ };
+
+ this._currentObject$.next(this.getObjectBySearch(this._currentObject));
+ }
+
+ getCurrentObject(): Nullable<ITransformObject> {
+ return this.getObjectBySearch(this._currentObject);
+ }
+
+ setObject(insertParam: IObjectTransformManagerInsert): ITransformObject {
+ const { unitId, object, objectId } = insertParam;
+
+ if (!this._objectParam.has(unitId)) {
+ this._objectParam.set(unitId, new Map());
+ }
+
+ const baseObjectData = this._objectParam.get(unitId)!;
+
+ baseObjectData.set(objectId, object);
+
+ this._currentObject = {
+ unitId,
+ objectId,
+ };
+
+ this._currentObject$.next(object);
+
+ return object;
+ }
+
+ getObjectBySearch(searchParam: IObjectTransformManagerSearch): Nullable<ITransformObject> {
+ const { unitId, objectId } = searchParam;
+ return this._objectParam.get(unitId)?.get(objectId);
+ }
+}
diff --git a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
index 3691b8e031..929deeb636 100644
--- a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
+++ b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
@@ -36,6 +36,7 @@ import { SetFrozenCommand } from '../commands/commands/set-frozen.command';
import { SetFrozenCancelCommand } from '../commands/commands/set-frozen-cancel.command';
import { SetRangeFormattedValueCommand } from '../commands/commands/set-range-formatted-value.command';
import { SetRangeValuesCommand } from '../commands/commands/set-range-values.command';
+import { ScrollCommand } from '../commands/commands/set-scroll.command';
import {
ResetBackgroundColorCommand,
ResetTextColorCommand,
@@ -81,7 +82,6 @@ import { SetWorksheetOrderMutation } from '../commands/mutations/set-worksheet-o
import { SetWorksheetRowHeightMutation } from '../commands/mutations/set-worksheet-row-height.mutation';
import { SetWorksheetRowHideMutation } from '../commands/mutations/set-worksheet-row-hide.mutation';
import { SetWorksheetRowShowMutation } from '../commands/mutations/set-worksheet-row-show.mutation';
-import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
export interface IStyleTypeValue<T> {
type: keyof IStyleData;
@@ -185,7 +185,7 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetFrozenCommand,
SetFrozenMutation,
SetFrozenCancelCommand,
- SetZoomRatioOperation,
+ ScrollCommand,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
}
diff --git a/packages/base-sheets/src/Controller/scroll.controller.ts b/packages/base-sheets/src/Controller/scroll.controller.ts
index 376b9adb19..8598931721 100644
--- a/packages/base-sheets/src/Controller/scroll.controller.ts
+++ b/packages/base-sheets/src/Controller/scroll.controller.ts
@@ -35,7 +35,7 @@ export class ScrollController extends Disposable {
}
private _scrollEventBinding() {
- const scene = this._renderManagerService.getCurrent()?.scene;
+ const scene = this._getSheetObject()?.scene;
if (scene == null) {
return;
}
@@ -46,11 +46,14 @@ export class ScrollController extends Disposable {
if (skeleton == null || param.isTrigger === false) {
return;
}
- const scene = this._renderManagerService.getCurrent()?.scene;
- if (scene == null) {
+
+ const sheetObject = this._getSheetObject();
+ if (skeleton == null || sheetObject == null) {
return;
}
+ const scene = sheetObject.scene;
+
const { rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop } = skeleton;
const { scaleX, scaleY } = scene.getAncestorScale();
@@ -72,22 +75,24 @@ export class ScrollController extends Disposable {
sheetViewStartRow: row,
sheetViewStartColumn: column,
});
+
+ // this._commandService.executeCommand(SetScrollOperation.id, {
+ // sheetViewStartRow: row,
+ // sheetViewStartColumn: column,
+ // });
});
}
private _scrollSubscribeBinding() {
this._scrollManagerService.scrollInfo$.subscribe((param) => {
const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- const scene = this._renderManagerService.getCurrent()?.scene;
- if (skeleton == null || scene == null) {
- return;
- }
-
const sheetObject = this._getSheetObject();
- if (sheetObject == null) {
+ if (skeleton == null || sheetObject == null) {
return;
}
+ const scene = sheetObject.scene;
+
const { scaleX, scaleY } = sheetObject.scene.getAncestorScale();
const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
@@ -160,9 +165,9 @@ export class ScrollController extends Disposable {
if (param == null) {
return;
}
- const { skeleton } = param;
+ const { skeleton, unitId } = param;
- const scene = this._renderManagerService.getCurrent()?.scene;
+ const scene = this._renderManagerService.getRenderById(unitId)?.scene;
if (skeleton == null || scene == null) {
return;
diff --git a/packages/base-sheets/src/Controller/zoom.controller.ts b/packages/base-sheets/src/Controller/zoom.controller.ts
index f338aa73f9..e647477bd6 100644
--- a/packages/base-sheets/src/Controller/zoom.controller.ts
+++ b/packages/base-sheets/src/Controller/zoom.controller.ts
@@ -46,7 +46,7 @@ export class ZoomController extends Disposable {
}
private _zoomEventBinding() {
- const scene = this._renderManagerService.getCurrent()?.scene;
+ const scene = this._getSheetObject()?.scene;
if (scene == null) {
return;
}
diff --git a/packages/base-sheets/src/View/sheet-canvas-view.ts b/packages/base-sheets/src/View/sheet-canvas-view.ts
index d24b8d2405..e21fed18c3 100644
--- a/packages/base-sheets/src/View/sheet-canvas-view.ts
+++ b/packages/base-sheets/src/View/sheet-canvas-view.ts
@@ -51,10 +51,18 @@ export class SheetCanvasView {
const unitId = workbook.getUnitId();
const container = workbook.getContainer();
- if (container == null) {
- this._renderManagerService.createRenderWithDefaultEngine(unitId);
+ const parentRenderUnitId = workbook.getParentRenderUnitId();
+
+ if (container != null && parentRenderUnitId != null) {
+ throw new Error('container or parentRenderUnitId can only exist one');
+ }
+
+ const isAddedToExistedScene = container == null && parentRenderUnitId != null;
+
+ if (isAddedToExistedScene) {
+ this._renderManagerService.createRenderWithParent(unitId, parentRenderUnitId);
} else {
- this._renderManagerService.createRenderWithNewEngine(unitId);
+ this._renderManagerService.createRender(unitId);
}
this._renderManagerService.setCurrent(unitId);
@@ -78,7 +86,7 @@ export class SheetCanvasView {
const should = workbook.getShouldRenderLoopImmediately();
- if (should) {
+ if (should && !isAddedToExistedScene) {
engine.runRenderLoop(() => {
// document.getElementById('app')!.innerHTML = engine.getFps().toString();
scene.render();
diff --git a/packages/core/src/Docs/Domain/DocumentModel.ts b/packages/core/src/Docs/Domain/DocumentModel.ts
index 8d14b4ee91..4b3213be3d 100644
--- a/packages/core/src/Docs/Domain/DocumentModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentModel.ts
@@ -49,6 +49,19 @@ export class DocumentModelSimple {
return this.snapshot.body;
}
+ getShouldRenderLoopImmediately() {
+ const should = this.snapshot.shouldStartRenderingImmediately;
+ return should !== false;
+ }
+
+ getContainer() {
+ return this.snapshot.container;
+ }
+
+ getParentRenderUnitId() {
+ return this.snapshot.parentRenderUnitId;
+ }
+
getBodyModel(segmentId?: string) {
if (segmentId == null) {
return this.bodyModel;
@@ -124,6 +137,10 @@ export class DocumentModel extends DocumentModelSimple {
this._initializeRowColTree();
}
+ getSettings() {
+ return this.snapshot.settings;
+ }
+
reset(snapshot: Partial<IDocumentData>) {
if (snapshot.id && snapshot.id !== this._unitId) {
throw new Error('Cannot reset a document model with a different unit id!');
diff --git a/packages/core/src/Sheets/Domain/Workbook.ts b/packages/core/src/Sheets/Domain/Workbook.ts
index f2218b194d..a9691e0c4e 100644
--- a/packages/core/src/Sheets/Domain/Workbook.ts
+++ b/packages/core/src/Sheets/Domain/Workbook.ts
@@ -80,13 +80,17 @@ export class Workbook {
return this._unitId;
}
+ getShouldRenderLoopImmediately() {
+ const should = this._config.shouldStartRenderingImmediately;
+ return should !== false;
+ }
+
getContainer() {
return this._config.container;
}
- getShouldRenderLoopImmediately() {
- const should = this._config.shouldRenderLoopImmediately;
- return should !== false;
+ getParentRenderUnitId() {
+ return this._config.parentRenderUnitId;
}
getWorksheets(): Map<string, Worksheet> {
diff --git a/packages/core/src/Types/Interfaces/IDocumentData.ts b/packages/core/src/Types/Interfaces/IDocumentData.ts
index 2edd4304dd..61f3113f56 100644
--- a/packages/core/src/Types/Interfaces/IDocumentData.ts
+++ b/packages/core/src/Types/Interfaces/IDocumentData.ts
@@ -1,4 +1,5 @@
import { BooleanNumber, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../Enum';
+import { IExtraModelConfig } from './IExtraModelConfig';
import { IImageProperties } from './IImageProperties';
import { IShapeProperties } from './IShapeProperties';
import { IColorStyle, IStyleBase } from './IStyleData';
@@ -7,12 +8,13 @@ import { IColorStyle, IStyleBase } from './IStyleData';
/**
* Properties of document
*/
-export interface IDocumentData extends IReferenceSource {
+export interface IDocumentData extends IReferenceSource, IExtraModelConfig {
id: string; // unit id
locale?: LocaleType;
title?: string;
body?: IDocumentBody;
documentStyle: IDocumentStyle;
+ settings?: IDocumentSettings;
}
export interface IReferenceSource {
@@ -22,6 +24,10 @@ export interface IReferenceSource {
drawings?: IDrawings;
}
+export interface IDocumentSettings {
+ zoomRatio?: number;
+}
+
/**
* Set of headers
*/
diff --git a/packages/core/src/Types/Interfaces/IExtraModelConfig.ts b/packages/core/src/Types/Interfaces/IExtraModelConfig.ts
new file mode 100644
index 0000000000..1e531739ec
--- /dev/null
+++ b/packages/core/src/Types/Interfaces/IExtraModelConfig.ts
@@ -0,0 +1,21 @@
+export interface IExtraModelConfig {
+ /**
+ * should start renderLoop Immediately
+ * default is true
+ */
+ shouldStartRenderingImmediately?: boolean;
+
+ // Union field properties can be only one of the following:
+ /**
+ * HTML selector
+ * default is null
+ */
+ container?: string;
+
+ /**
+ * Specify the unitID of the parent render. In this case, the scene will enter
+ * the sceneViewer and become a child application of the parent scene.
+ * default is null
+ */
+ parentRenderUnitId?: string;
+}
diff --git a/packages/core/src/Types/Interfaces/IWorkbookData.ts b/packages/core/src/Types/Interfaces/IWorkbookData.ts
index 8117590c59..e5c63be83f 100644
--- a/packages/core/src/Types/Interfaces/IWorkbookData.ts
+++ b/packages/core/src/Types/Interfaces/IWorkbookData.ts
@@ -1,5 +1,6 @@
import { IKeyType, Nullable } from '../../Shared/Types';
import { LocaleType } from '../Enum';
+import { IExtraModelConfig } from './IExtraModelConfig';
import { IStyleData } from './IStyleData';
import { IWorksheetConfig } from './IWorksheetData';
@@ -8,7 +9,7 @@ import { IWorksheetConfig } from './IWorksheetData';
/**
* Properties of a workbook's configuration
*/
-export interface IWorkbookConfig {
+export interface IWorkbookConfig extends IExtraModelConfig {
appVersion: string;
createdTime: string;
creator: string;
@@ -25,16 +26,4 @@ export interface IWorkbookConfig {
sheets: { [sheetId: string]: Partial<IWorksheetConfig> };
styles: IKeyType<Nullable<IStyleData>>;
timeZone: string;
-
- /**
- * HTML selector
- * default is null
- */
- container?: string;
-
- /**
- * should start renderLoop Immediately
- * default is true
- */
- shouldRenderLoopImmediately?: boolean;
}
diff --git a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
index dc3b6e4c6a..1bbfb26669 100644
--- a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
@@ -1,7 +1,6 @@
import {
ExpandSelectionCommand,
MoveSelectionCommand,
- ScrollCommand,
SelectAllCommand,
SetBoldCommand,
SetFontFamilyCommand,
@@ -144,7 +143,6 @@ export class SheetUIController extends Disposable {
SetUnderlineCommand,
SetFontFamilyCommand,
SetFontSizeCommand,
- ScrollCommand,
QuitCellEditorCommand,
diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
index 886dcff598..d1b1eb67cb 100644
--- a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
+++ b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
@@ -1,13 +1,20 @@
import './desktop.module.less';
-import { CoverCommand, DocsView, DocsViewManagerService, ICoverCommandParams } from '@univerjs/base-docs';
import {
- DocsEditor,
+ CoverCommand,
+ DocsView,
+ getDocObject,
+ ICoverCommandParams,
+ TextSelectionManagerService,
+} from '@univerjs/base-docs';
+import {
Engine,
+ IEditorInputConfig,
IMouseEvent,
IPointerEvent,
IRenderManagerService,
ISelectionTransformerShapeManager,
+ ITextSelectionRenderManager,
Layer,
Scene,
Viewport,
@@ -67,7 +74,9 @@ export class DesktopCellEditorService extends RxDisposable implements ICellEdito
@ICommandService private readonly _commandService: ICommandService,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@IContextService private readonly _contextService: IContextService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
) {
super();
@@ -109,7 +118,7 @@ export class DesktopCellEditorService extends RxDisposable implements ICellEdito
this._contextService.setContextValue(SHEET_EDITOR_ACTIVATED, true);
this._currentUniverService.focusUniverInstance(SHEET_CELL_EDITOR_MODEL_ID); // focus the UniverDoc instance to enable rich text editing
- this._getCellEditor()?.activate();
+ this._textSelectionRenderManager.activate(true);
}
quitEditing(): void {
@@ -127,7 +136,7 @@ export class DesktopCellEditorService extends RxDisposable implements ICellEdito
const model = this._currentUniverService.getUniverDocInstance(SHEET_CELL_EDITOR_MODEL_ID)!;
const dataStream = model.getBodyModel().getText();
- this._getCellEditor()?.deactivate(true);
+ this._textSelectionRenderManager.deactivate(true);
this._commandService.executeCommand(SetRangeValuesCommand.id, <ISetRangeValuesCommandParams>{
workbookId,
@@ -194,7 +203,7 @@ export class DesktopCellEditorService extends RxDisposable implements ICellEdito
scene.addLayer(Layer.create(scene, [], 0), Layer.create(scene, [], 2));
const docsView = this._injector.createInstance(DocsView, docModel);
docsView.initialize(scene);
- docsView.getDocs().enableEditor();
+ // docsView.getDocs().enableEditor();
engine.runRenderLoop(() => {
scene.render();
@@ -205,17 +214,19 @@ export class DesktopCellEditorService extends RxDisposable implements ICellEdito
}
private _initPasteHandler(): void {
- this._enableEditor();
-
- const editor = this._getCellEditor();
- if (!editor) {
- throw new Error('[DesktopCellEditorService]: Could not init paste handler, cell editor not found!');
- }
-
- editor.onPaste$.pipe(takeUntil(this.dispose$)).subscribe((e: ClipboardEvent) => {
- console.log('paste event', e);
- // TODO: handle paste event from the editor input element
- });
+ this._textSelectionRenderManager.enableSelection();
+
+ // const editor = this._getCellEditor();
+ // if (!editor) {
+ // throw new Error('[DesktopCellEditorService]: Could not init paste handler, cell editor not found!');
+ // }
+
+ this._textSelectionRenderManager.onPaste$
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((config: Nullable<IEditorInputConfig>) => {
+ console.log('paste event', config?.event);
+ // TODO: handle paste event from the editor input element
+ });
}
private _positionCellEditor(currentCell: ISelectionCell) {
@@ -333,21 +344,18 @@ export class DesktopCellEditorService extends RxDisposable implements ICellEdito
return this._getActiveRange()?.getTextStyle();
}
- private _enableEditor(): void {
- return this._injector
- .get(DocsViewManagerService)
- .getDocsView(SHEET_CELL_EDITOR_MODEL_ID)
- ?.getDocs()
- .enableEditor();
- }
+ // private _enableEditor(): void {
+ // return this._getDocObject()?.document
+ // .enableEditor();
+ // }
- private _getCellEditor(): Nullable<DocsEditor> {
- return this._injector
- .get(DocsViewManagerService)
- .getDocsView(SHEET_CELL_EDITOR_MODEL_ID)
- ?.getDocs()
- .getEditor();
- }
+ // private _getCellEditor(): Nullable<DocsEditor> {
+ // return this._injector
+ // .get(DocsViewManagerService)
+ // .getDocsView(SHEET_CELL_EDITOR_MODEL_ID)
+ // ?.getDocs()
+ // .getEditor();
+ // }
private _getActiveRange() {
const primary = this._selectionManagerService.getLast()?.primary;
@@ -365,6 +373,10 @@ export class DesktopCellEditorService extends RxDisposable implements ICellEdito
.getActiveSheet()
.getRange(actualRow, actualColumn);
}
+
+ private _getDocObject() {
+ return getDocObject(this._currentUniverService, this._renderManagerService);
+ }
}
function getRangeFromPrimary(primary: ISelectionCell): IRange {
diff --git a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
index 6ea409a14f..e8687b9d13 100644
--- a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
@@ -1,3 +1,5 @@
+import { TextSelectionManagerService } from '@univerjs/base-docs';
+import { ITextSelectionRenderManager, TextSelectionRenderManager } from '@univerjs/base-render';
import { ZIndexManager } from '@univerjs/base-ui';
import { ICurrentUniverService, LocaleService, Plugin, PluginType } from '@univerjs/core';
import { Dependency, Inject, Injector } from '@wendellhu/redi';
@@ -37,6 +39,8 @@ export class SheetUIPlugin extends Plugin {
[ICellEditorService, { useClass: DesktopCellEditorService }],
[ISheetClipboardService, { useClass: SheetClipboardService }],
[ISheetBarService, { useClass: SheetBarService }],
+ [ITextSelectionRenderManager, { useClass: TextSelectionRenderManager }],
+ [TextSelectionManagerService],
// controllers
[SheetClipboardController],