Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(sheet): zen editor (#741)
Ran Luo0210f67134ec
diff --git a/examples/package.json b/examples/package.jsonindex 13b1f7f330..6076453b0f 100644--- a/examples/package.json+++ b/examples/package.json@@ -15,6 +15,7 @@"@univerjs/docs-ui": "workspace:*","@univerjs/engine-formula": "workspace:*","@univerjs/engine-render": "workspace:*",+ "@univerjs/icons": "^0.1.18","@univerjs/local-save": "workspace:*","@univerjs/rpc": "workspace:*","@univerjs/sheets": "workspace:*",@@ -26,6 +27,7 @@"@univerjs/ui": "workspace:*","@univerjs/uniscript": "workspace:*","@wendellhu/redi": "^0.12.12",+ "clsx": "^2.0.0","monaco-editor": "0.45.0","react": "^18.2.0","react-dom": "^18.2.0",diff --git a/examples/src/plugins/debugger/controllers/performance-monitor.controller.ts b/examples/src/plugins/debugger/controllers/performance-monitor.controller.tsindex fc5a85120a..603ad7a88a 100644--- a/examples/src/plugins/debugger/controllers/performance-monitor.controller.ts+++ b/examples/src/plugins/debugger/controllers/performance-monitor.controller.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { DocumentType, IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';+import { IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable, UniverInstanceType } from '@univerjs/core';import { DocCanvasView } from '@univerjs/docs';import { SheetCanvasView } from '@univerjs/sheets-ui';import { Inject, Injector } from '@wendellhu/redi';@@ -22,7 +22,7 @@ import { interval, takeUntil, throttle } from 'rxjs';@OnLifecycle(LifecycleStages.Rendered, PerformanceMonitorController)export class PerformanceMonitorController extends RxDisposable {- private _documentType: DocumentType = DocumentType.UNKNOWN;+ private _documentType: UniverInstanceType = UniverInstanceType.UNKNOWN;private _hasWatched = false;@@ -78,14 +78,14 @@ export class PerformanceMonitorController extends RxDisposable {document.head.appendChild(document.createElement('style')).innerText = style;- if (this._documentType === DocumentType.DOC) {+ if (this._documentType === UniverInstanceType.DOC) {this._docCanvasView.fps$.pipe(takeUntil(this.dispose$)).pipe(throttle(() => interval(THROTTLE_TIME))).subscribe((fps) => {container.innerText = `FPS: ${fps}`;});- } else if (this._documentType === DocumentType.SHEET) {+ } else if (this._documentType === UniverInstanceType.SHEET) {this._injector.get(SheetCanvasView).fps$.pipe(takeUntil(this.dispose$))diff --git a/examples/src/plugins/zen-editor/commands/commands/zen-editor.command.ts b/examples/src/plugins/zen-editor/commands/commands/zen-editor.command.tsnew file mode 100644index 0000000000..4024d0b04f--- /dev/null+++ b/examples/src/plugins/zen-editor/commands/commands/zen-editor.command.ts@@ -0,0 +1,91 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand } from '@univerjs/core';+import { CommandType, IUniverInstanceService } from '@univerjs/core';+import { TextSelectionManagerService } from '@univerjs/docs';+import { DeviceInputEventType } from '@univerjs/engine-render';+import { IEditorBridgeService } from '@univerjs/sheets-ui';+import { IZenZoneService, KeyCode } from '@univerjs/ui';++export const CancelZenEditCommand: ICommand = {+ id: 'zen-editor.command.cancel-zen-edit',++ type: CommandType.COMMAND,++ handler: async (accessor) => {+ const zenZoneEditorService = accessor.get(IZenZoneService);++ const editorBridgeService = accessor.get(IEditorBridgeService);++ const univerInstanceManager = accessor.get(IUniverInstanceService);++ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ const visibleState = editorBridgeService.isVisible();+ if (visibleState.visible) {+ editorBridgeService.changeVisible({+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ keycode: KeyCode.ESC,+ });+ }++ zenZoneEditorService.close();++ const currentSheetInstance = univerInstanceManager.getCurrentUniverSheetInstance();++ univerInstanceManager.focusUniverInstance(currentSheetInstance.getUnitId());++ textSelectionManagerService.replaceTextRanges([]);++ return true;+ },+};++export const ConfirmZenEditCommand: ICommand = {+ id: 'zen-editor.command.confirm-zen-edit',++ type: CommandType.COMMAND,++ handler: async (accessor) => {+ const zenZoneEditorService = accessor.get(IZenZoneService);++ const editorBridgeService = accessor.get(IEditorBridgeService);++ const univerInstanceManager = accessor.get(IUniverInstanceService);++ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ const visibleState = editorBridgeService.isVisible();+ if (visibleState.visible) {+ editorBridgeService.changeVisible({+ visible: false,+ eventType: DeviceInputEventType.PointerDown,+ });+ }++ zenZoneEditorService.close();++ const currentSheetInstance = univerInstanceManager.getCurrentUniverSheetInstance();++ univerInstanceManager.focusUniverInstance(currentSheetInstance.getUnitId());++ textSelectionManagerService.replaceTextRanges([]);++ return true;+ },+};diff --git a/examples/src/plugins/zen-editor/commands/operations/zen-editor.operation.ts b/examples/src/plugins/zen-editor/commands/operations/zen-editor.operation.tsnew file mode 100644index 0000000000..9a1c7735fd--- /dev/null+++ b/examples/src/plugins/zen-editor/commands/operations/zen-editor.operation.ts@@ -0,0 +1,28 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IOperation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++export const OpenZenEditorOperation: IOperation = {+ id: 'zen-editor.operation.open-zen-editor',++ type: CommandType.OPERATION,++ handler: (accessor) => {+ return true;+ },+};diff --git a/examples/src/plugins/zen-editor/controllers/zen-editor-ui.controller.ts b/examples/src/plugins/zen-editor/controllers/zen-editor-ui.controller.tsnew file mode 100644index 0000000000..f61c30f4ff--- /dev/null+++ b/examples/src/plugins/zen-editor/controllers/zen-editor-ui.controller.ts@@ -0,0 +1,66 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';+import type { IMenuItemFactory } from '@univerjs/ui';+import { IMenuService, IZenZoneService } from '@univerjs/ui';+import { Inject, Injector } from '@wendellhu/redi';++import { CancelZenEditCommand, ConfirmZenEditCommand } from '../commands/commands/zen-editor.command';+import { OpenZenEditorOperation } from '../commands/operations/zen-editor.operation';+import { ZenEditorMenuItemFactory } from '../views/menu';+import { ZEN_EDITOR_COMPONENT, ZenEditor } from '../views/zen-editor';++@OnLifecycle(LifecycleStages.Ready, ZenEditorUIController)+export class ZenEditorUIController extends Disposable {+ constructor(+ @Inject(Injector) private readonly _injector: Injector,+ @IZenZoneService private readonly _zenZoneService: IZenZoneService,+ @ICommandService private readonly _commandService: ICommandService,+ @IMenuService private readonly _menuService: IMenuService+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._initCustomComponents();+ this._initCommands();+ this._initMenus();+ }++ private _initCustomComponents(): void {+ this.disposeWithMe(this._zenZoneService.set(ZEN_EDITOR_COMPONENT, ZenEditor));+ }++ private _initCommands(): void {+ [OpenZenEditorOperation, CancelZenEditCommand, ConfirmZenEditCommand].forEach((c) => {+ this.disposeWithMe(this._commandService.registerCommand(c));+ });+ }++ private _initMenus(): void {+ (+ [+ // context menu+ ZenEditorMenuItemFactory,+ ] as IMenuItemFactory[]+ ).forEach((factory) => {+ this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));+ });+ }+}diff --git a/examples/src/plugins/zen-editor/controllers/zen-editor.controller.ts b/examples/src/plugins/zen-editor/controllers/zen-editor.controller.tsnew file mode 100644index 0000000000..c39647f47a--- /dev/null+++ b/examples/src/plugins/zen-editor/controllers/zen-editor.controller.ts@@ -0,0 +1,365 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommandInfo, IParagraph, ITextRun } from '@univerjs/core';+import {+ DEFAULT_EMPTY_DOCUMENT_VALUE,+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ ICommandService,+ IUndoRedoService,+ IUniverInstanceService,+ LifecycleStages,+ OnLifecycle,+ RxDisposable,+} from '@univerjs/core';+import type { IDocObjectParam, IRichTextEditingMutationParams } from '@univerjs/docs';+import {+ DocSkeletonManagerService,+ DocViewModelManagerService,+ getDocObject,+ RichTextEditingMutation,+ TextSelectionManagerService,+ VIEWPORT_KEY,+} from '@univerjs/docs';+import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';+import { getEditorObject } from '@univerjs/sheets-ui';+import type { IEditorBridgeServiceParam } from '@univerjs/sheets-ui/services/editor-bridge.service.js';+import { IEditorBridgeService } from '@univerjs/sheets-ui/services/editor-bridge.service.js';+import { IZenZoneService } from '@univerjs/ui';+import { Inject } from '@wendellhu/redi';+import { takeUntil } from 'rxjs';++import { OpenZenEditorOperation } from '../commands/operations/zen-editor.operation';+import { IZenEditorManagerService } from '../services/zen-editor.service';++export const DOCS_ZEN_EDITOR_UNIT_ID_KEY = '__defaultDocumentZenEditorSpecialUnitId_20231218__';++@OnLifecycle(LifecycleStages.Steady, ZenEditorController)+export class ZenEditorController extends RxDisposable {+ constructor(+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,+ @IZenEditorManagerService private readonly _zenEditorManagerService: IZenEditorManagerService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @ICommandService private readonly _commandService: ICommandService,+ @IZenZoneService private readonly _zenZoneService: IZenZoneService,+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,+ @IUndoRedoService private readonly _undoRedoService: IUndoRedoService,+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,+ @Inject(DocViewModelManagerService) private readonly _docViewModelManagerService: DocViewModelManagerService+ ) {+ super();++ this._initialize();+ }++ private _initialize() {+ this._syncZenEditorSize();++ this._commandExecutedListener();++ this._createZenEditorInstance();+ }++ private _createZenEditorInstance() {+ // create univer doc formula bar editor instance+ const INITIAL_SNAPSHOT = {+ id: DOCS_ZEN_EDITOR_UNIT_ID_KEY,+ body: {+ dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,+ textRuns: [],+ paragraphs: [+ {+ startIndex: 0,+ },+ ],+ },+ documentStyle: {+ pageSize: {+ width: 595,+ height: 842,+ },+ marginTop: 50,+ marginBottom: 50,+ marginRight: 40,+ marginLeft: 40,+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ },+ };++ this._currentUniverService.createDoc(INITIAL_SNAPSHOT);+ }++ // Listen to changes in the size of the zen editor container to set the size of the editor.+ private _syncZenEditorSize() {+ this._zenEditorManagerService.position$.pipe(takeUntil(this.dispose$)).subscribe((position) => {+ if (position == null) {+ return;+ }+ const editorObject = getEditorObject(DOCS_ZEN_EDITOR_UNIT_ID_KEY, this._renderManagerService);+ const zenEditorDataModel = this._currentUniverService.getUniverDocInstance(DOCS_ZEN_EDITOR_UNIT_ID_KEY);++ if (editorObject == null || zenEditorDataModel == null) {+ return;+ }++ const { width, height } = position;++ const { engine, scene, document } = editorObject;++ const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);++ const skeleton = this._docSkeletonManagerService.getSkeletonByUnitId(DOCS_ZEN_EDITOR_UNIT_ID_KEY)?.skeleton;++ // Update page size when container resized.+ // zenEditorDataModel.updateDocumentDataPageSize(width);++ // resize canvas+ requestIdleCallback(() => {+ engine.resizeBySize(width, height);++ this._calculatePagePosition(editorObject);++ if (skeleton) {+ // TODO: @JOCS, get offset config from document at runtime.+ this._textSelectionRenderManager.changeRuntime(+ skeleton,+ scene,+ viewportMain,+ document.getOffsetConfig()+ );++ this._textSelectionManagerService.refreshSelection();+ }+ });+ });+ }++ private _handleOpenZenEditor() {+ this._zenZoneService.open();++ // Need to clear undo/redo service when open zen mode.+ this._undoRedoService.clearUndoRedo(DOCS_ZEN_EDITOR_UNIT_ID_KEY);++ this._currentUniverService.focusUniverInstance(DOCS_ZEN_EDITOR_UNIT_ID_KEY);++ this._currentUniverService.setCurrentUniverDocInstance(DOCS_ZEN_EDITOR_UNIT_ID_KEY);++ const visibleState = this._editorBridgeService.isVisible();+ if (visibleState.visible === false) {+ this._editorBridgeService.changeVisible({+ visible: true,+ eventType: DeviceInputEventType.PointerDown,+ });+ }++ const param = this._editorBridgeService.getState();++ if (param == null) {+ return;+ }++ this._editorSyncHandler(param);++ const textRanges = [+ {+ startOffset: 0,+ endOffset: 0,+ },+ ];++ this._textSelectionManagerService.replaceTextRanges(textRanges);+ }++ private _editorSyncHandler(param: IEditorBridgeServiceParam) {+ const body = param.documentLayoutObject.documentModel?.getBody();++ const dataStream = body?.dataStream;+ const paragraphs = body?.paragraphs;+ let textRuns: ITextRun[] = [];++ if (dataStream == null || paragraphs == null) {+ return;+ }++ if (body?.textRuns?.length) {+ textRuns = body?.textRuns;+ }++ this._syncContentAndRender(DOCS_ZEN_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, textRuns);++ // Also need to resize document and scene after sync content.+ // this._autoScroll();+ }++ private _syncContentAndRender(+ unitId: string,+ dataStream: string,+ paragraphs: IParagraph[],+ textRuns: ITextRun[] = []+ ) {+ const INCLUDE_LIST = [+ DOCS_ZEN_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ ];++ const docsSkeletonObject = this._docSkeletonManagerService.getSkeletonByUnitId(unitId);+ const docDataModel = this._currentUniverService.getUniverDocInstance(unitId);+ const docViewModel = this._docViewModelManagerService.getViewModel(unitId);++ if (docDataModel == null || docViewModel == null || docsSkeletonObject == null) {+ return;+ }++ const docBody = docDataModel.getBody()!;++ docBody.dataStream = dataStream;+ docBody.paragraphs = paragraphs;++ // Need to empty textRuns(previous formula highlight) every time when sync content(change selection or edit cell or edit formula bar).+ if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ docBody.textRuns = [];+ }++ if (textRuns.length > 0) {+ docBody.textRuns = textRuns;+ }++ docViewModel.reset(docDataModel);++ const { skeleton } = docsSkeletonObject;++ const currentRender = this._getDocObject();++ if (currentRender == null) {+ return;+ }++ skeleton.calculate();++ if (INCLUDE_LIST.includes(unitId)) {+ currentRender.document.makeDirty();+ }+ }++ private _calculatePagePosition(currentRender: IDocObjectParam) {+ const { document: docsComponent, scene } = currentRender;++ const parent = scene?.getParent();++ const { width: docsWidth, height: docsHeight, pageMarginLeft, pageMarginTop } = docsComponent;+ if (parent == null || docsWidth === Infinity || docsHeight === Infinity) {+ return;+ }+ const { width: engineWidth, height: engineHeight } = parent;++ let docsLeft = 0;+ let docsTop = 0;++ let sceneWidth = 0;++ let sceneHeight = 0;++ let scrollToX = Infinity;++ const { scaleX, scaleY } = scene.getAncestorScale();++ if (engineWidth > (docsWidth + pageMarginLeft * 2) * scaleX) {+ docsLeft = engineWidth / 2 - (docsWidth * scaleX) / 2;+ docsLeft /= scaleX;+ sceneWidth = (engineWidth - pageMarginLeft * 2) / scaleX;++ scrollToX = 0;+ } else {+ docsLeft = pageMarginLeft;+ sceneWidth = docsWidth + pageMarginLeft * 2;++ scrollToX = (sceneWidth - engineWidth / scaleX) / 2;+ }++ if (engineHeight > docsHeight) {+ docsTop = engineHeight / 2 - docsHeight / 2;+ sceneHeight = (engineHeight - pageMarginTop * 2) / scaleY;+ } else {+ docsTop = pageMarginTop;+ sceneHeight = docsHeight + pageMarginTop * 2;+ }++ scene.resize(sceneWidth, sceneHeight + 200);++ docsComponent.translate(docsLeft, docsTop);++ const viewport = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);+ if (scrollToX !== Infinity && viewport != null) {+ const actualX = viewport.getBarScroll(scrollToX, 0).x;+ viewport.scrollTo({+ x: actualX,+ });+ }++ return this;+ }++ private _commandExecutedListener() {+ const updateCommandList = [OpenZenEditorOperation.id];++ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (updateCommandList.includes(command.id)) {+ this._handleOpenZenEditor();+ }+ })+ );++ const editCommandList = [RichTextEditingMutation.id];++ // const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];++ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (editCommandList.includes(command.id)) {+ const params = command.params as IRichTextEditingMutationParams;+ const { unitId } = params;++ if (unitId === DOCS_ZEN_EDITOR_UNIT_ID_KEY) {+ // sync cell content to formula editor bar when edit cell editor and vice verse.+ const editorDocDataModel = this._currentUniverService.getUniverDocInstance(unitId);+ const docBody = editorDocDataModel?.getBody();+ const dataStream = docBody?.dataStream;+ const paragraphs = docBody?.paragraphs;+ const textRuns = docBody?.textRuns;++ if (dataStream == null || paragraphs == null) {+ return;+ }++ this._syncContentAndRender(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, textRuns);+ }+ }+ })+ );+ }++ private _getDocObject() {+ return getDocObject(this._currentUniverService, this._renderManagerService);+ }+}diff --git a/examples/src/plugins/zen-editor/index.ts b/examples/src/plugins/zen-editor/index.tsnew file mode 100644index 0000000000..58aacd9771--- /dev/null+++ b/examples/src/plugins/zen-editor/index.ts@@ -0,0 +1,17 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export * from './zen-editor-plugin';diff --git a/examples/src/plugins/zen-editor/services/zen-editor.service.ts b/examples/src/plugins/zen-editor/services/zen-editor.service.tsnew file mode 100644index 0000000000..9e0fcbb622--- /dev/null+++ b/examples/src/plugins/zen-editor/services/zen-editor.service.ts@@ -0,0 +1,59 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Nullable } from '@univerjs/core';+import type { IDisposable } from '@wendellhu/redi';+import { createIdentifier } from '@wendellhu/redi';+import type { Observable } from 'rxjs';+import { BehaviorSubject } from 'rxjs';++export interface IZenEditorManagerService {+ position$: Observable<Nullable<DOMRect>>;++ dispose(): void;+ setPosition(param: DOMRect): void;+ getPosition(): Readonly<Nullable<DOMRect>>;+}++export class ZenEditorManagerService implements IDisposable {+ private _position: Nullable<DOMRect> = null;++ private readonly _position$ = new BehaviorSubject<Nullable<DOMRect>>(null);+ readonly position$ = this._position$.asObservable();++ dispose(): void {+ this._position$.complete();+ this._position = null;+ }++ setPosition(param: DOMRect) {+ this._position = param;++ this._refresh(param);+ }++ getPosition(): Readonly<Nullable<DOMRect>> {+ return this._position;+ }++ private _refresh(param: DOMRect): void {+ this._position$.next(param);+ }+}++export const IZenEditorManagerService = createIdentifier<ZenEditorManagerService>(+ 'univer.sheet-zen-editor-manager.service'+);diff --git a/examples/src/plugins/zen-editor/views/menu.ts b/examples/src/plugins/zen-editor/views/menu.tsnew file mode 100644index 0000000000..88b1840366--- /dev/null+++ b/examples/src/plugins/zen-editor/views/menu.ts@@ -0,0 +1,30 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { type IMenuButtonItem, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';++import { OpenZenEditorOperation } from '../commands/operations/zen-editor.operation';++export function ZenEditorMenuItemFactory(): IMenuButtonItem {+ return {+ id: OpenZenEditorOperation.id,+ group: MenuGroup.CONTEXT_MENU_OTHERS,+ type: MenuItemType.BUTTON,+ title: 'rightClick.zenEditor',+ icon: 'NoColor',+ positions: [MenuPosition.CONTEXT_MENU],+ };+}diff --git a/examples/src/plugins/zen-editor/views/zen-editor/ZenEditor.tsx b/examples/src/plugins/zen-editor/views/zen-editor/ZenEditor.tsxnew file mode 100644index 0000000000..a3effdb374--- /dev/null+++ b/examples/src/plugins/zen-editor/views/zen-editor/ZenEditor.tsx@@ -0,0 +1,100 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { ICommandService } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import { CheckMarkSingle, CloseSingle } from '@univerjs/icons';+import { useDependency } from '@wendellhu/redi/react-bindings';+import clsx from 'clsx';+import React, { useEffect, useRef } from 'react';++import { CancelZenEditCommand, ConfirmZenEditCommand } from '../../commands/commands/zen-editor.command';+import { DOCS_ZEN_EDITOR_UNIT_ID_KEY } from '../../controllers/zen-editor.controller';+import { IZenEditorManagerService } from '../../services/zen-editor.service';+import styles from './index.module.less';++const COMPONENT_PREFIX = 'ZEN_EDITOR_PLUGIN_';+export const ZEN_EDITOR_COMPONENT = `${COMPONENT_PREFIX}ZEN_EDITOR_COMPONENT`;++export function ZenEditor() {+ const editorRef = useRef<HTMLDivElement>(null);++ const renderManagerService: IRenderManagerService = useDependency(IRenderManagerService);++ const zenEditorManagerService = useDependency(IZenEditorManagerService);++ const commandService = useDependency(ICommandService);++ useEffect(() => {+ const editor = editorRef.current;++ if (!editor) {+ return;+ }++ const renderSubscription = renderManagerService.currentRender$.subscribe((param) => {+ if (param !== DOCS_ZEN_EDITOR_UNIT_ID_KEY) {+ return;+ }++ const engine = renderManagerService.getRenderById(DOCS_ZEN_EDITOR_UNIT_ID_KEY)?.engine;+ engine?.setContainer(editor);+ });++ const resizeObserver = new ResizeObserver(() => {+ const editorRect = editor.getBoundingClientRect();++ zenEditorManagerService.setPosition(editorRect);+ });++ resizeObserver.observe(editor);++ // Clean up on unmount+ return () => {+ resizeObserver.unobserve(editor);+ renderSubscription.unsubscribe();+ };+ }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount++ function handleCloseBtnClick() {+ commandService.executeCommand(CancelZenEditCommand.id);+ }++ function handleConfirmBtnClick() {+ commandService.executeCommand(ConfirmZenEditCommand.id);+ }++ return (+ <div className={styles.zenEditor}>+ <div className={styles.zenEditorIconWrapper}>+ <span+ className={clsx(styles.zenEditorIconContainer, styles.zenEditorIconError)}+ onClick={handleCloseBtnClick}+ >+ <CloseSingle style={{ fontSize: '22px' }} />+ </span>++ <span+ className={clsx(styles.zenEditorIconContainer, styles.zenEditorIconSuccess)}+ onClick={handleConfirmBtnClick}+ >+ <CheckMarkSingle style={{ fontSize: '22px' }} />+ </span>+ </div>+ <div className={styles.zenEditorCanvasContainer} ref={editorRef} />+ </div>+ );+}diff --git a/examples/src/plugins/zen-editor/views/zen-editor/index.module.less b/examples/src/plugins/zen-editor/views/zen-editor/index.module.lessnew file mode 100644index 0000000000..522bcd4abd--- /dev/null+++ b/examples/src/plugins/zen-editor/views/zen-editor/index.module.less@@ -0,0 +1,52 @@+.zen-editor {+ position: absolute;+ top: 0;+ left: 0;++ width: 100%;+ height: 100%;++ &-icon {+ &-wrapper {+ position: absolute;+ z-index: 10;+ top: 0;+ right: 20px;++ display: flex;+ align-items: center;+ justify-content: space-around;++ width: 60px;+ height: 30px;+ }++ &-container {+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 30px;+ height: 30px;+ }++ &-success {+ color: rgb(var(--success-color));+ }++ &-error {+ color: rgb(var(--error-color));+ }+ }++ &-canvas-container {+ position: absolute;+ top: 0;+ left: 0;++ width: 100%;+ height: 100%;+ }+}\ No newline at end of filediff --git a/examples/src/plugins/zen-editor/views/zen-editor/index.ts b/examples/src/plugins/zen-editor/views/zen-editor/index.tsnew file mode 100644index 0000000000..d4c92b496a--- /dev/null+++ b/examples/src/plugins/zen-editor/views/zen-editor/index.ts@@ -0,0 +1,17 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export { ZEN_EDITOR_COMPONENT, ZenEditor } from './ZenEditor';diff --git a/examples/src/plugins/zen-editor/zen-editor-plugin.ts b/examples/src/plugins/zen-editor/zen-editor-plugin.tsnew file mode 100644index 0000000000..03f91b2511--- /dev/null+++ b/examples/src/plugins/zen-editor/zen-editor-plugin.ts@@ -0,0 +1,51 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Plugin, PluginType } from '@univerjs/core';+import type { Dependency } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';++import { ZenEditorController } from './controllers/zen-editor.controller';+import { ZenEditorUIController } from './controllers/zen-editor-ui.controller';+import { IZenEditorManagerService, ZenEditorManagerService } from './services/zen-editor.service';++export interface IZenEditorPluginConfig {}++export class ZenEditorPlugin extends Plugin {+ static override type = PluginType.Doc;++ constructor(+ config: IZenEditorPluginConfig,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super('zen-editor');+ this._initializeDependencies(this._injector);+ }++ private _initializeDependencies(injector: Injector) {+ const dependencies: Dependency[] = [+ [ZenEditorUIController],+ [ZenEditorController],+ [IZenEditorManagerService, { useClass: ZenEditorManagerService }],+ ];++ dependencies.forEach((dependency) => injector.add(dependency));+ }++ override onRendered(): void {}++ override onDestroy(): void {}+}diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex 995c55ca15..43d760a82f 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -17,6 +17,7 @@import { LocaleType, LogLevel, Univer } from '@univerjs/core';import { defaultTheme } from '@univerjs/design';import { UniverDocsPlugin } from '@univerjs/docs';+import { UniverDocsUIPlugin } from '@univerjs/docs-ui';import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { UniverRenderEnginePlugin } from '@univerjs/engine-render';import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';@@ -29,6 +30,7 @@ import { UniverUIPlugin } from '@univerjs/ui';import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data';import { DebuggerPlugin } from '../plugins/debugger';+import { ZenEditorPlugin } from '../plugins/zen-editor';import { locales } from './locales';const LOAD_LAZY_PLUGINS_TIMEOUT = 5_000;@@ -55,11 +57,13 @@ univer.registerPlugin(UniverSheetsPlugin, {notExecuteFormula: true,});univer.registerPlugin(UniverSheetsUIPlugin);+univer.registerPlugin(UniverDocsUIPlugin);// sheet feature pluginsuniver.registerPlugin(UniverSheetsNumfmtPlugin);univer.registerPlugin(DebuggerPlugin);+univer.registerPlugin(ZenEditorPlugin);univer.registerPlugin(UniverFormulaEnginePlugin, {notExecuteFormula: true,});diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 86a7c65762..a18075657b 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -64,7 +64,7 @@ export {type IFloatingObjectManagerSearchItemParam,IFloatingObjectManagerService,} from './services/floating-object/floating-object-manager.service';-export { DocumentType, IUniverInstanceService } from './services/instance/instance.service';+export { IUniverInstanceService, UniverInstanceType } from './services/instance/instance.service';export { LifecycleStages, OnLifecycle, runOnLifecycle } from './services/lifecycle/lifecycle';export { LifecycleService } from './services/lifecycle/lifecycle.service';export { ILocalStorageService } from './services/local-storage/local-storage.service';diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.tsindex 28fb3360e8..a0728155b5 100644--- a/packages/core/src/services/instance/instance.service.ts+++ b/packages/core/src/services/instance/instance.service.ts@@ -27,7 +27,7 @@ import type { IDocumentData, ISlideData, IWorkbookData } from '../../types/interimport { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from '../context/context';import { IContextService } from '../context/context.service';-export const enum DocumentType {+export const enum UniverInstanceType {UNKNOWN = 0,DOC = 1,SHEET = 2,@@ -87,14 +87,14 @@ export interface IUniverInstanceService {getAllUniverDocsInstance(): DocumentDataModel[];getAllUniverSlidesInstance(): Slide[];- getDocumentType(unitID: string): DocumentType;+ getDocumentType(unitId: string): UniverInstanceType;disposeDocument(unitId: string): boolean;}export const IUniverInstanceService = createIdentifier<IUniverInstanceService>('univer.current');export class UniverInstanceService extends Disposable implements IUniverInstanceService {- private readonly _focused$ = new BehaviorSubject<Nullable<string>>(null);private _focused: DocumentDataModel | Workbook | Slide | null = null;+ private readonly _focused$ = new BehaviorSubject<Nullable<string>>(null);readonly focused$ = this._focused$.asObservable();private readonly _currentSheet$ = new BehaviorSubject<Nullable<Workbook>>(null);@@ -276,18 +276,20 @@ export class UniverInstanceService extends Disposable implements IUniverInstancereturn this._focused;}- getDocumentType(unitID: string): DocumentType {- if (this.getUniverDocInstance(unitID)) {- return DocumentType.DOC;+ getDocumentType(unitId: string): UniverInstanceType {+ if (this.getUniverDocInstance(unitId)) {+ return UniverInstanceType.DOC;}- if (this.getUniverSheetInstance(unitID)) {- return DocumentType.SHEET;++ if (this.getUniverSheetInstance(unitId)) {+ return UniverInstanceType.SHEET;}- if (this.getUniverSlideInstance(unitID)) {- return DocumentType.SLIDE;++ if (this.getUniverSlideInstance(unitId)) {+ return UniverInstanceType.SLIDE;}- throw new Error(`[UniverInstanceService]: No document with unitID ${unitID}`);+ throw new Error(`[UniverInstanceService]: No document with unitId ${unitId}`);}disposeDocument(unitId: string): boolean {diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.tsindex e01c77e4e8..95a2fff83c 100644--- a/packages/core/src/services/undoredo/undoredo.service.ts+++ b/packages/core/src/services/undoredo/undoredo.service.ts@@ -23,7 +23,7 @@ import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } fimport { Disposable, toDisposable } from '../../shared/lifecycle';import type { ICommand, IMutationInfo } from '../command/command.service';import { CommandType, ICommandService, sequenceExecute } from '../command/command.service';-import { FOCUSING_EDITOR, FOCUSING_FORMULA_EDITOR } from '../context/context';+import { FOCUSING_EDITOR, FOCUSING_FORMULA_EDITOR, FOCUSING_SHEET } from '../context/context';import { IContextService } from '../context/context.service';import { IUniverInstanceService } from '../instance/instance.service';@@ -223,10 +223,18 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServiceprivate _getFocusedUniverInstanceId() {let unitID: string = '';- if (this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR)) {- unitID = DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;- } else if (this._contextService.getContextValue(FOCUSING_EDITOR)) {- unitID = DOCS_NORMAL_EDITOR_UNIT_ID_KEY;+ const isFocusSheet = this._contextService.getContextValue(FOCUSING_SHEET);+ const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR);+ const isFocusEditor = this._contextService.getContextValue(FOCUSING_EDITOR);++ if (isFocusSheet) {+ if (isFocusFormulaEditor) {+ unitID = DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;+ } else if (isFocusEditor) {+ unitID = DOCS_NORMAL_EDITOR_UNIT_ID_KEY;+ } else {+ unitID = this._univerInstanceService.getFocusedUniverInstance()?.getUnitId() ?? '';+ }} else {unitID = this._univerInstanceService.getFocusedUniverInstance()?.getUnitId() ?? '';}diff --git a/packages/docs-ui/src/controllers/menu/menu.ts b/packages/docs-ui/src/controllers/menu/menu.tsindex 0e6e6b66f6..a9ab453d97 100644--- a/packages/docs-ui/src/controllers/menu/menu.ts+++ b/packages/docs-ui/src/controllers/menu/menu.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import { UniverInstanceType } from '@univerjs/core';import {BulletListCommand,OrderListCommand,@@ -25,7 +26,7 @@ import {SetInlineFormatUnderlineCommand,} from '@univerjs/docs';import type { IMenuButtonItem } from '@univerjs/ui';-import { MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';+import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';// TODO @Dushusir: use for test, change id later@@ -38,6 +39,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {title: 'Set bold',tooltip: 'toolbar.bold',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}@@ -50,6 +52,7 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {title: 'Set italic',tooltip: 'toolbar.italic',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}@@ -62,6 +65,7 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {title: 'Set underline',tooltip: 'toolbar.underline',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}@@ -74,6 +78,7 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIttitle: 'Set strike through',tooltip: 'toolbar.strikethrough',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}@@ -85,6 +90,7 @@ export function SubscriptMenuItemFactory(accessor: IAccessor): IMenuButtonItem {icon: 'FontSizeReduceSingleSingle',tooltip: 'toolbar.subscript',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}@@ -96,6 +102,7 @@ export function SuperscriptMenuItemFactory(accessor: IAccessor): IMenuButtonItemicon: 'FontSizeIncreaseSingle',tooltip: 'toolbar.superscript',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}@@ -107,6 +114,7 @@ export function OrderListMenuItemFactory(accessor: IAccessor): IMenuButtonItem {icon: 'OrderSingle',tooltip: 'toolbar.superscript',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}@@ -118,5 +126,6 @@ export function BulletListMenuItemFactory(accessor: IAccessor): IMenuButtonItemicon: 'UnorderSingle',tooltip: 'toolbar.superscript',positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),};}diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex d24da01825..c03da14e09 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -17,6 +17,7 @@import {DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ ILogService,IUniverInstanceService,LocaleService,Plugin,@@ -39,7 +40,8 @@ export class UniverDocsUIPlugin extends Plugin {constructor(private readonly _config: IUniverDocsUIConfig,@Inject(Injector) override _injector: Injector,- @Inject(LocaleService) private readonly _localeService: LocaleService+ @Inject(LocaleService) private readonly _localeService: LocaleService,+ @ILogService private _logService: ILogService) {super(DOC_UI_PLUGIN_NAME);@@ -77,11 +79,16 @@ export class UniverDocsUIPlugin extends Plugin {private _markDocAsFocused() {const currentService = this._injector.get(IUniverInstanceService);- const doc = currentService.getCurrentUniverDocInstance();- const id = doc.getUnitId();- if (id !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY && id !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {- currentService.focusUniverInstance(doc.getUnitId());+ try {+ const doc = currentService.getCurrentUniverDocInstance();+ const id = doc.getUnitId();++ if (id !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY && id !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ currentService.focusUniverInstance(doc.getUnitId());+ }+ } catch (err) {+ this._logService.warn(err);}}diff --git a/packages/docs/src/controllers/page-render.controller.ts b/packages/docs/src/controllers/page-render.controller.tsindex 38c77e2484..85cde6abe3 100644--- a/packages/docs/src/controllers/page-render.controller.ts+++ b/packages/docs/src/controllers/page-render.controller.ts@@ -76,13 +76,14 @@ export class PageRenderController extends Disposable {// Draw page bordersconst { page, pageLeft, pageTop, ctx } = config;- const { width, height } = page;+ const { width, pageWidth, height, pageHeight } = page;+ctx.save();// eslint-disable-next-line no-magic-numbersctx.translate(pageLeft - 0.5, pageTop - 0.5);Rect.drawWith(ctx, {- width: pageSize?.width || width,- height: pageSize?.height || height,+ width: pageSize?.width ?? pageWidth ?? width,+ height: pageSize?.height ?? pageHeight ?? height,strokeWidth: 1,stroke: PAGE_STROKE_COLOR,fill: PAGE_FILL_COLOR,diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex 6a868df75d..14cdabff81 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -14,6 +14,7 @@* limitations under the License.*/+export type { IDocObjectParam } from './basics/component-tools';export { getDocObject } from './basics/component-tools';export * from './basics/docs-view-key';export { BreakLineCommand } from './commands/commands/break-line.command';diff --git a/packages/engine-render/src/components/docs/doc-component.ts b/packages/engine-render/src/components/docs/doc-component.tsindex 9ee1611dfa..0b50171de6 100644--- a/packages/engine-render/src/components/docs/doc-component.ts+++ b/packages/engine-render/src/components/docs/doc-component.ts@@ -62,6 +62,7 @@ export class DocComponent extends RenderComponent<}const m = this.transform.getMatrix();+mainCtx.save();// eslint-disable-next-line no-magic-numbersmainCtx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.tsindex 7714350099..557dbcb5f5 100644--- a/packages/engine-render/src/scene.ts+++ b/packages/engine-render/src/scene.ts@@ -486,6 +486,7 @@ export class Scene extends ThinScene {if (!this.isDirty()) {return;}+!parentCtx && this.getEngine()?.clearCanvas();const layers = this._layers.sort(sortRules);diff --git a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.tsindex 33c695c2ac..282636c2f2 100644--- a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts+++ b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts@@ -17,12 +17,12 @@import type { IMutationInfo } from '@univerjs/core';import {CommandType,- DocumentType,ICommandService,IUniverInstanceService,LifecycleStages,OnLifecycle,RxDisposable,+ UniverInstanceType,} from '@univerjs/core';import { Inject, Injector } from '@wendellhu/redi';import { takeUntil } from 'rxjs/operators';@@ -79,7 +79,7 @@ export class DataSyncPrimaryController extends RxDisposable {// If a sheet is created, it should sync the data to the worker thread.this._remoteInstanceService.createInstance({unitID: sheet.getUnitId(),- type: DocumentType.SHEET,+ type: UniverInstanceType.SHEET,snapshot: sheet.getSnapshot(),});});diff --git a/packages/rpc/src/services/remote-instance/remote-instance.service.ts b/packages/rpc/src/services/remote-instance/remote-instance.service.tsindex b1a678d38c..e224ff2387 100644--- a/packages/rpc/src/services/remote-instance/remote-instance.service.ts+++ b/packages/rpc/src/services/remote-instance/remote-instance.service.ts@@ -15,7 +15,7 @@*/import type { IExecutionOptions, IMutationInfo, IWorkbookData } from '@univerjs/core';-import { DocumentType, ICommandService, IUniverInstanceService } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';export interface IRemoteSyncMutationOptions extends IExecutionOptions {@@ -56,7 +56,7 @@ export interface IRemoteInstanceService {/** Tell other modules if the `IRemoteInstanceService` is ready to load files. */whenReady(): Promise<true>;- createInstance(params: { unitID: string; type: DocumentType; snapshot: IWorkbookData }): Promise<boolean>;+ createInstance(params: { unitID: string; type: UniverInstanceType; snapshot: IWorkbookData }): Promise<boolean>;disposeInstance(params: { unitID: string }): Promise<boolean>;syncMutation(params: { mutationInfo: IMutationInfo }): Promise<boolean>;}@@ -77,11 +77,15 @@ export class RemoteInstanceReplicaService implements IRemoteInstanceService {});}- async createInstance(params: { unitID: string; type: DocumentType; snapshot: IWorkbookData }): Promise<boolean> {+ async createInstance(params: {+ unitID: string;+ type: UniverInstanceType;+ snapshot: IWorkbookData;+ }): Promise<boolean> {const { type, snapshot } = params;try {switch (type) {- case DocumentType.SHEET:+ case UniverInstanceType.SHEET:return !!this._univerInstanceService.createSheet(snapshot);default:throw new Error(diff --git a/packages/sheets-formula/src/controllers/menu.ts b/packages/sheets-formula/src/controllers/menu.tsindex bf682d63cf..22bc54ef80 100644--- a/packages/sheets-formula/src/controllers/menu.ts+++ b/packages/sheets-formula/src/controllers/menu.ts@@ -14,9 +14,10 @@* limitations under the License.*/+import { UniverInstanceType } from '@univerjs/core';import { PASTE_SPECIAL_MENU_ID } from '@univerjs/sheets-ui';import type { IMenuItem } from '@univerjs/ui';-import { MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';+import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';import { SheetOnlyPasteFormulaCommand } from '../commands/commands/formula-clipboard.command';@@ -58,6 +59,7 @@ export function InsertFunctionMenuItemFactory(accessor: IAccessor): IMenuItem {icon: 'MinSingle',},],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.tsindex b00919fafa..6d0ba512ef 100644--- a/packages/sheets-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts@@ -228,14 +228,21 @@ export class PromptController extends Disposable {private _initialCursorSync() {this.disposeWithMe(toDisposable(- this._textSelectionManagerService.textSelection$.subscribe(() => {+ this._textSelectionManagerService.textSelection$.subscribe((params) => {if (this._editorBridgeService.isVisible().visible === false ||- this._formulaInputService.isSelectionMoving()+ this._formulaInputService.isSelectionMoving() ||+ params?.unitId == null) {return;}+ const INCLUDE_LIST = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];++ if (!INCLUDE_LIST.includes(params.unitId)) {+ return;+ }+const currentBody = this._getCurrentBody();const dataStream = currentBody?.dataStream || '';diff --git a/packages/sheets-numfmt/src/menu/menu.ts b/packages/sheets-numfmt/src/menu/menu.tsindex 3cd5a0bbdd..df7c44db8b 100644--- a/packages/sheets-numfmt/src/menu/menu.ts+++ b/packages/sheets-numfmt/src/menu/menu.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import { ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';import { AddDigitsSingle, MoreDownSingle, ReduceDigitsSingle, RmbSingle } from '@univerjs/icons';import { INumfmtService, SelectionManagerService, SetNumfmtMutation } from '@univerjs/sheets';import type { ComponentManager, IMenuSelectorItem } from '@univerjs/ui';-import { MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';+import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';import { merge, Observable } from 'rxjs';@@ -34,21 +34,25 @@ export const CurrencyMenuItem = (componentManager: ComponentManager) => {const iconKey = 'icon-rmbSingle';componentManager.register(iconKey, RmbSingle);componentManager.register('MoreDownSingle', MoreDownSingle);- return () => ({- icon: iconKey,- id: SetCurrencyCommand.id,- title: 'sheet.numfmt.currency',- tooltip: 'sheet.numfmt.currency',- type: MenuItemType.BUTTON,- group: MenuGroup.TOOLBAR_FORMULAS_INSERT,- positions: [MenuPosition.TOOLBAR_START],- });++ return (accessor: IAccessor) => {+ return {+ icon: iconKey,+ id: SetCurrencyCommand.id,+ title: 'sheet.numfmt.currency',+ tooltip: 'sheet.numfmt.currency',+ type: MenuItemType.BUTTON,+ group: MenuGroup.TOOLBAR_FORMULAS_INSERT,+ positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),+ };+ };};export const AddDecimalMenuItem = (componentManager: ComponentManager) => {const iconKey = 'icon-addDigitsSingle';componentManager.register(iconKey, AddDigitsSingle);- return () => ({+ return (accessor: IAccessor) => ({icon: iconKey,id: AddDecimalCommand.id,title: 'sheet.numfmt.addDecimal',@@ -56,12 +60,13 @@ export const AddDecimalMenuItem = (componentManager: ComponentManager) => {type: MenuItemType.BUTTON,positions: [MenuPosition.TOOLBAR_START],group: MenuGroup.TOOLBAR_FORMULAS_INSERT,+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),});};export const SubtractDecimalMenuItem = (componentManager: ComponentManager) => {const iconKey = 'icon-reduceDigitsSingle';componentManager.register(iconKey, ReduceDigitsSingle);- return () => ({+ return (accessor: IAccessor) => ({icon: iconKey,id: SubtractDecimalCommand.id,title: 'sheet.numfmt.subtractDecimal',@@ -69,6 +74,7 @@ export const SubtractDecimalMenuItem = (componentManager: ComponentManager) => {type: MenuItemType.BUTTON,group: MenuGroup.TOOLBAR_FORMULAS_INSERT,positions: [MenuPosition.TOOLBAR_START],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),});};@@ -121,6 +127,7 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {}}));+return {// icon: 'MoreDownSingle',label: moreTypeKey,@@ -138,6 +145,7 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {},],value$,+ hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.SHEET),} as IMenuSelectorItem;};};diff --git a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/end-edit.controller.tsindex 49b9452d40..8013e2b067 100644--- a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts+++ b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { DocumentDataModel, ICellData, ICommandInfo, Nullable, Observer } from '@univerjs/core';+import type { DocumentDataModel, ICellData, ICommandInfo, IDocumentBody, Nullable, Observer } from '@univerjs/core';import {DEFAULT_EMPTY_DOCUMENT_VALUE,Direction,@@ -56,6 +56,15 @@ import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-briimport { IEditorBridgeService } from '../../services/editor-bridge.service';import { MOVE_SELECTION_KEYCODE_LIST } from '../shortcuts/editor.shortcut';+function isRichText(body: IDocumentBody) {+ const { textRuns = [], paragraphs = [] } = body;++ return (+ textRuns.some((textRun) => textRun.ts && !Tools.isEmptyObject(textRun.ts)) ||+ paragraphs.some((paragraph) => paragraph.bullet)+ );+}+enum CursorChange {InitialState,StartEditor,@@ -214,7 +223,7 @@ export class EndEditController extends Disposable {cellData.f = newDataStream;cellData.v = null;cellData.p = null;- } else if (body.textRuns && body.textRuns.length > 1) {+ } else if (isRichText(body)) {cellData.p = snapshot;cellData.v = null;cellData.f = null;diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.tsindex 343624d028..302cd96b62 100644--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts@@ -173,6 +173,7 @@ export class FormulaEditorController extends RxDisposable {this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, true);this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);+ // When clicking on the formula bar, the cell editor also needs to enter the edit stateconst visibleState = this._editorBridgeService.isVisible();if (visibleState.visible === false) {this._editorBridgeService.changeVisible({diff --git a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/start-edit.controller.tsindex 5e7d7e85de..91a5ca36b1 100644--- a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts+++ b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts@@ -23,6 +23,7 @@ import {FOCUSING_EDITOR,FOCUSING_EDITOR_BUT_HIDDEN,FOCUSING_FORMULA_EDITOR,+ FOCUSING_SHEET,HorizontalAlign,ICommandService,IContextService,@@ -585,8 +586,9 @@ export class StartEditController extends Disposable {private _initialKeyboardListener() {this._textSelectionRenderManager.onInputBefore$.subscribe((config) => {const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR);+ const isFocusSheets = this._contextService.getContextValue(FOCUSING_SHEET);- if (!isFocusFormulaEditor) {+ if (isFocusSheets && !isFocusFormulaEditor) {this._showEditorByKeyboard(config);}});diff --git a/packages/sheets-ui/src/controllers/menu/border.menu.ts b/packages/sheets-ui/src/controllers/menu/border.menu.tsindex 69b9bcc712..ba02cbbaa0 100644--- a/packages/sheets-ui/src/controllers/menu/border.menu.ts+++ b/packages/sheets-ui/src/controllers/menu/border.menu.ts@@ -28,6 +28,7 @@ export function CellBorderSelectorMenuItemFactory(accessor: IAccessor): IMenuSel// const permissionService = accessor.get(IPermissionService);const borderStyleManagerService = accessor.get(BorderStyleManagerService);+return {id: SetBorderBasicCommand.id,icon: new Observable<string>((subscriber) => {@@ -67,5 +68,8 @@ export function CellBorderSelectorMenuItemFactory(accessor: IAccessor): IMenuSel},],value$: borderStyleManagerService.borderInfo$,+ hidden$: new Observable((subscriber) => {+ subscriber.next(true);+ }),};}diff --git a/packages/sheets-ui/src/controllers/menu/menu.ts b/packages/sheets-ui/src/controllers/menu/menu.tsindex 2c3c63d851..7a82b6af28 100644--- a/packages/sheets-ui/src/controllers/menu/menu.ts+++ b/packages/sheets-ui/src/controllers/menu/menu.ts@@ -23,6 +23,7 @@ import {IUniverInstanceService,RANGE_TYPE,ThemeService,+ UniverInstanceType,VerticalAlign,WrapStrategy,} from '@univerjs/core';@@ -51,7 +52,15 @@ import {SheetPermissionService,} from '@univerjs/sheets';import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';-import { CopyCommand, CutCommand, MenuGroup, MenuItemType, MenuPosition, PasteCommand } from '@univerjs/ui';+import {+ CopyCommand,+ CutCommand,+ getMenuHiddenObservable,+ MenuGroup,+ MenuItemType,+ MenuPosition,+ PasteCommand,+} from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';import { Observable } from 'rxjs';@@ -67,8 +76,6 @@ import {SetRangeFontSizeCommand,SetRangeItalicCommand,SetRangeStrickThroughCommand,- SetRangeSubscriptCommand,- SetRangeSuperscriptCommand,SetRangeTextColorCommand,SetRangeUnderlineCommand,} from '../../commands/commands/inline-format.command';@@ -96,6 +103,8 @@ export enum SheetMenuPosition {export function FormatPainterMenuItemFactory(accessor: IAccessor): IMenuButtonItem {const formatPainterService = accessor.get(IFormatPainterService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+return {id: SetOnceFormatPainterCommand.id,subId: SetInfiniteFormatPainterCommand.id,@@ -119,6 +128,7 @@ export function FormatPainterMenuItemFactory(accessor: IAccessor): IMenuButtonItstatus$.unsubscribe();};}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -129,6 +139,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {const selectionManagerService = accessor.get(SelectionManagerService);const unitId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();const sheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();+return {id: SetRangeBoldCommand.id,group: MenuGroup.TOOLBAR_FORMAT,@@ -168,6 +179,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {return disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -215,6 +227,7 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {subscriber.next(false);return disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -262,6 +275,7 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {subscriber.next(false);return disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -309,72 +323,7 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonItsubscriber.next(false);return disposable.dispose;}),- };-}--export function SubScriptMenuItemFactory(accessor: IAccessor): IMenuButtonItem {- const commandService = accessor.get(ICommandService);- const univerInstanceService = accessor.get(IUniverInstanceService);- const sheetPermissionService = accessor.get(SheetPermissionService);- const unitId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();- const sheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();- return {- id: SetRangeSubscriptCommand.id,- group: MenuGroup.TOOLBAR_FORMAT,- type: MenuItemType.BUTTON,- icon: 'FontSizeReduceSingleSingle',- tooltip: 'toolbar.subscript',- positions: [MenuPosition.TOOLBAR_START],- disabled$: new Observable<boolean>((subscriber) => {- const permission$ = sheetPermissionService.getEditable$(unitId, sheetId)?.subscribe((e) => {- subscriber.next(!e.value);- });-- return () => {- permission$?.unsubscribe();- };- }),- activated$: new Observable<boolean>((subscriber) => {- const disposable = commandService.onCommandExecuted((c) => {- // TODO- });-- subscriber.next(false);- return disposable.dispose;- }),- };-}--export function SuperScriptMenuItemFactory(accessor: IAccessor): IMenuButtonItem {- const commandService = accessor.get(ICommandService);- const univerInstanceService = accessor.get(IUniverInstanceService);- const sheetPermissionService = accessor.get(SheetPermissionService);- const unitId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();- const sheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();- return {- id: SetRangeSuperscriptCommand.id,- group: MenuGroup.TOOLBAR_FORMAT,- type: MenuItemType.BUTTON,- icon: 'FontSizeIncreaseSingle',- tooltip: 'toolbar.superscript',- positions: [MenuPosition.TOOLBAR_START],- disabled$: new Observable<boolean>((subscriber) => {- const permission$ = sheetPermissionService.getEditable$(unitId, sheetId)?.subscribe((e) => {- subscriber.next(!e.value);- });-- return () => {- permission$?.unsubscribe();- };- }),- activated$: new Observable<boolean>((subscriber) => {- const disposable = commandService.onCommandExecuted((c) => {- // TODO- });-- subscriber.next(false);- return disposable.dispose;- }),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -559,6 +508,7 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSelsubscriber.next(defaultValue);return disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -569,6 +519,7 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelecconst sheetPermissionService = accessor.get(SheetPermissionService);const unitId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();const sheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();+return {id: SetRangeFontSizeCommand.id,group: MenuGroup.TOOLBAR_FORMAT,@@ -614,6 +565,7 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelecreturn disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -630,6 +582,7 @@ export function ResetTextColorMenuItemFactory(): IMenuButtonItem {export function TextColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {const commandService = accessor.get(ICommandService);const themeService = accessor.get(ThemeService);+ const univerInstanceService = accessor.get(IUniverInstanceService);return {id: SetRangeTextColorCommand.id,@@ -659,6 +612,7 @@ export function TextColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSelesubscriber.next(defaultColor);return disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -675,6 +629,7 @@ export function ResetBackgroundColorMenuItemFactory(): IMenuButtonItem {export function BackgroundColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {const commandService = accessor.get(ICommandService);const themeService = accessor.get(ThemeService);+ const univerInstanceService = accessor.get(IUniverInstanceService);return {id: SetBackgroundColorCommand.id,@@ -703,6 +658,7 @@ export function BackgroundColorSelectorMenuItemFactory(accessor: IAccessor): IMesubscriber.next(defaultColor);return disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -727,6 +683,7 @@ export const HORIZONTAL_ALIGN_CHILDREN = [export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<HorizontalAlign> {const univerInstanceService = accessor.get(IUniverInstanceService);const selectionManagerService = accessor.get(SelectionManagerService);+return {id: SetHorizontalTextAlignCommand.id,icon: HORIZONTAL_ALIGN_CHILDREN[0].icon,@@ -757,6 +714,7 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelectreturn disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -811,6 +769,7 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelectorreturn disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -865,6 +824,7 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<return disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}@@ -904,6 +864,7 @@ export const TEXT_ROTATE_CHILDREN = [export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<number | string> {const univerInstanceService = accessor.get(IUniverInstanceService);const selectionManagerService = accessor.get(SelectionManagerService);+return {id: SetTextRotationCommand.id,tooltip: 'toolbar.textRotateMode.main',@@ -938,6 +899,7 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorItereturn disposable.dispose;}),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}diff --git a/packages/sheets-ui/src/controllers/menu/merge.menu.ts b/packages/sheets-ui/src/controllers/menu/merge.menu.tsindex 8d24ee56d9..4ebd7cd679 100644--- a/packages/sheets-ui/src/controllers/menu/merge.menu.ts+++ b/packages/sheets-ui/src/controllers/menu/merge.menu.ts@@ -14,9 +14,10 @@* limitations under the License.*/+import { UniverInstanceType } from '@univerjs/core';import { RemoveWorksheetMergeCommand } from '@univerjs/sheets';import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';-import { MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';+import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';import {@@ -35,6 +36,7 @@ export function CellMergeMenuItemFactory(accessor: IAccessor): IMenuSelectorItemgroup: MenuGroup.TOOLBAR_LAYOUT,type: MenuItemType.SUBITEMS,// selections: [...MERGE_CHILDREN],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),};}export function CellMergeAllMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.tsindex 443d75d854..d98cf50e00 100644--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts@@ -145,8 +145,6 @@ import {ShowColMenuItemFactory,ShowRowMenuItemFactory,StrikeThroughMenuItemFactory,- SubScriptMenuItemFactory,- SuperScriptMenuItemFactory,TextColorSelectorMenuItemFactory,TextRotateMenuItemFactory,UnderlineMenuItemFactory,@@ -337,8 +335,6 @@ export class SheetUIController extends Disposable {ItalicMenuItemFactory,UnderlineMenuItemFactory,StrikeThroughMenuItemFactory,- SubScriptMenuItemFactory,- SuperScriptMenuItemFactory,FontFamilySelectorMenuItemFactory,FontSizeSelectorMenuItemFactory,ResetTextColorMenuItemFactory,diff --git a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.tsindex a82ef5d469..77b1c5a558 100644--- a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts@@ -14,7 +14,6 @@* limitations under the License.*/-import { FOCUSING_EDITOR } from '@univerjs/core';import { BreakLineCommand, DeleteLeftCommand } from '@univerjs/docs';import { DeviceInputEventType } from '@univerjs/engine-render';import type { IShortcutItem } from '@univerjs/ui';@@ -25,6 +24,7 @@ import {SetCellEditVisibleOperation,} from '../../commands/operations/cell-edit.operation';import {+ whenEditorActivated,whenEditorActivatedIsVisible,whenEditorDidNotInputFormulaActivated,whenEditorFocusIsHidden,@@ -101,7 +101,7 @@ export const EditorCursorEscShortcut: IShortcutItem = {binding: KeyCode.ESC,description: 'shortcut.sheet.abort-editing',group: '4_sheet-edit',- preconditions: (contextService) => contextService.getContextValue(FOCUSING_EDITOR),+ preconditions: (contextService) => whenEditorActivated(contextService),staticParameters: {visible: false,eventType: DeviceInputEventType.Keyboard,@@ -113,7 +113,7 @@ export const EditorBreakLineShortcut: IShortcutItem = {id: BreakLineCommand.id,description: 'shortcut.sheet.break-line',group: '4_sheet-edit',- preconditions: (contextService) => contextService.getContextValue(FOCUSING_EDITOR),+ preconditions: (contextService) => whenEditorActivated(contextService),binding: KeyCode.ENTER | MetaKeys.ALT,};diff --git a/packages/sheets-ui/src/controllers/shortcuts/utils.ts b/packages/sheets-ui/src/controllers/shortcuts/utils.tsindex 66c66598e3..3ed0022abc 100644--- a/packages/sheets-ui/src/controllers/shortcuts/utils.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/utils.ts@@ -27,6 +27,10 @@ export function whenEditorNotActivated(contextService: IContextService) {return contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_EDITOR);}+export function whenEditorActivated(contextService: IContextService) {+ return contextService.getContextValue(FOCUSING_SHEET) && contextService.getContextValue(FOCUSING_EDITOR);+}+export function whenEditorFocusIsHidden(contextService: IContextService) {return (contextService.getContextValue(FOCUSING_EDITOR_BUT_HIDDEN) && !contextService.getContextValue(FOCUSING_EDITOR)@@ -45,12 +49,15 @@ export function whenFormulaEditorFocused(contextService: IContextService) {export function whenEditorInputFormulaActivated(contextService: IContextService) {return (- contextService.getContextValue(FOCUSING_EDITOR) && contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)+ contextService.getContextValue(FOCUSING_SHEET) &&+ contextService.getContextValue(FOCUSING_EDITOR) &&+ contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA));}export function whenEditorDidNotInputFormulaActivated(contextService: IContextService) {return (+ contextService.getContextValue(FOCUSING_SHEET) &&contextService.getContextValue(FOCUSING_EDITOR) &&!contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA));diff --git a/packages/sheets-ui/src/locale/en-US.ts b/packages/sheets-ui/src/locale/en-US.tsindex f4eca170fe..9418658049 100644--- a/packages/sheets-ui/src/locale/en-US.ts+++ b/packages/sheets-ui/src/locale/en-US.ts@@ -533,6 +533,7 @@ export default {freezeCol: 'Freeze to this column',freezeRow: 'Freeze to this row',cancelFreeze: 'Cancel freeze',+ zenEditor: 'Full Screen Editor',},info: {tooltip: 'Tooltip',diff --git a/packages/sheets-ui/src/locale/zh-CN.ts b/packages/sheets-ui/src/locale/zh-CN.tsindex 2b0586eba4..34d5fca2d2 100644--- a/packages/sheets-ui/src/locale/zh-CN.ts+++ b/packages/sheets-ui/src/locale/zh-CN.ts@@ -397,6 +397,7 @@ export default {freezeCol: '冻结列',freezeRow: '冻结行',cancelFreeze: '取消冻结',+ zenEditor: '禅模式编辑',},info: {tooltip: '提示',diff --git a/packages/ui/src/common/menu-hidden-observable.ts b/packages/ui/src/common/menu-hidden-observable.tsnew file mode 100644index 0000000000..cca9793756--- /dev/null+++ b/packages/ui/src/common/menu-hidden-observable.ts@@ -0,0 +1,49 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { UniverInstanceType } from '@univerjs/core';+import { IUniverInstanceService } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';+import { Observable } from 'rxjs';++export function getMenuHiddenObservable(+ accessor: IAccessor,+ targetUniverType: UniverInstanceType+): Observable<boolean> {+ const univerInstanceService = accessor.get(IUniverInstanceService);++ return new Observable((subscriber) => {+ const subscription = univerInstanceService.focused$.subscribe((unitId) => {+ if (unitId == null) {+ return subscriber.next(true);+ }+ const univerType = univerInstanceService.getDocumentType(unitId);++ subscriber.next(univerType !== targetUniverType);+ });++ const focusedUniverInstance = univerInstanceService.getFocusedUniverInstance();++ if (focusedUniverInstance == null) {+ return subscriber.next(true);+ }++ const univerType = univerInstanceService.getDocumentType(focusedUniverInstance.getUnitId());+ subscriber.next(univerType !== targetUniverType);++ return () => subscription.unsubscribe();+ });+}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex c655a42d65..d680d7426c 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -16,6 +16,7 @@export * from './BaseComponent';export * from './common';+export { getMenuHiddenObservable } from './common/menu-hidden-observable';export * from './components';export { useObservable } from './components/hooks/observable';export {@@ -70,6 +71,7 @@ export { DesktopShortcutService, type IShortcutItem, IShortcutService } from './export { ShortcutExperienceService } from './services/shortcut/shortcut-experience.service';export { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';export { ISidebarService } from './services/sidebar/sidebar.service';+export { IZenZoneService } from './services/zen-zone/zen-zone.service';export { UniverUIPlugin } from './ui-plugin';export * from './utils';export { type IConfirmPartMethodOptions } from './views/components/confirm-part/interface';diff --git a/packages/ui/src/services/zen-zone/desktop-zen-zone.service.ts b/packages/ui/src/services/zen-zone/desktop-zen-zone.service.tsnew file mode 100644index 0000000000..8d91d395de--- /dev/null+++ b/packages/ui/src/services/zen-zone/desktop-zen-zone.service.ts@@ -0,0 +1,49 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { toDisposable } from '@univerjs/core';+import { type IDisposable, Inject } from '@wendellhu/redi';+import type { ForwardRefExoticComponent } from 'react';+import { Subject } from 'rxjs';++import { ComponentManager } from '../../common/component-manager';+import type { IZenZoneService } from './zen-zone.service';++export class DesktopZenZoneService implements IZenZoneService {+ readonly visible$ = new Subject<boolean>();+ readonly componentKey$ = new Subject<string>();++ constructor(@Inject(ComponentManager) private readonly _componentManager: ComponentManager) {}++ set(key: string, component: ForwardRefExoticComponent<any>): IDisposable {+ this._componentManager.register(key, component);+ this.componentKey$.next(key);++ return toDisposable(() => {+ this._componentManager.delete(key);+ this.visible$.complete();+ this.componentKey$.complete();+ });+ }++ open(): void {+ this.visible$.next(true);+ }++ close() {+ this.visible$.next(false);+ }+}diff --git a/packages/ui/src/services/zen-zone/zen-zone.service.ts b/packages/ui/src/services/zen-zone/zen-zone.service.tsnew file mode 100644index 0000000000..0e314e0b0e--- /dev/null+++ b/packages/ui/src/services/zen-zone/zen-zone.service.ts@@ -0,0 +1,32 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IDisposable } from '@wendellhu/redi';+import { createIdentifier } from '@wendellhu/redi';+import type { Subject } from 'rxjs';++export const IZenZoneService = createIdentifier<IZenZoneService>('univer.zen-zone-service');++export interface IZenZoneService {+ readonly visible$: Subject<boolean>;+ readonly componentKey$: Subject<string>;++ set(key: string, component: any): IDisposable;++ open(): void;++ close(): void;+}diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.tsindex 32a06cfbed..c7977b04ba 100644--- a/packages/ui/src/ui-plugin.ts+++ b/packages/ui/src/ui-plugin.ts@@ -48,6 +48,8 @@ import { ShortcutExperienceService } from './services/shortcut/shortcut-experienimport { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';import { ISidebarService } from './services/sidebar/sidebar.service';+import { DesktopZenZoneService } from './services/zen-zone/desktop-zen-zone.service';+import { IZenZoneService } from './services/zen-zone/zen-zone.service';const PLUGIN_NAME = 'ui';@@ -104,6 +106,7 @@ export class UniverUIPlugin extends Plugin {[IDialogService, { useClass: DesktopDialogService, lazy: true }],[IConfirmService, { useClass: DesktopConfirmService, lazy: true }],[ISidebarService, { useClass: DesktopSidebarService, lazy: true }],+ [IZenZoneService, { useClass: DesktopZenZoneService, lazy: true }],[IMessageService, { useClass: DesktopMessageService, lazy: true }],[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],diff --git a/packages/ui/src/views/App.tsx b/packages/ui/src/views/App.tsxindex fa23686dd0..fb154244b6 100644--- a/packages/ui/src/views/App.tsx+++ b/packages/ui/src/views/App.tsx@@ -27,6 +27,7 @@ import styles from './app.module.less';import { ComponentContainer } from './components/ComponentContainer';import { Toolbar } from './components/doc-bars/Toolbar';import { Sidebar } from './components/sidebar/Sidebar';+import { ZenZone } from './components/zen-zone/ZenZone';import { globalComponents } from './parts';export interface IUniverAppProps extends IWorkbenchOptions {@@ -132,6 +133,8 @@ export function App(props: IUniverAppProps) {<ComponentContainer components={footerComponents} /></footer>)}++ <ZenZone /></section></div>diff --git a/packages/ui/src/views/app.module.less b/packages/ui/src/views/app.module.lessindex 58dba43ff5..07669db239 100644--- a/packages/ui/src/views/app.module.less+++ b/packages/ui/src/views/app.module.less@@ -11,6 +11,7 @@}&-container {+ position: relative;display: flex;flex: 1;flex-direction: column;diff --git a/packages/ui/src/views/components/doc-bars/ToolbarItem.tsx b/packages/ui/src/views/components/doc-bars/ToolbarItem.tsxindex f94150d50a..58b4b3c695 100644--- a/packages/ui/src/views/components/doc-bars/ToolbarItem.tsx+++ b/packages/ui/src/views/components/doc-bars/ToolbarItem.tsx@@ -40,6 +40,7 @@ export const ToolbarItem = forwardRef((props: IDisplayMenuItem<IMenuItem>, ref:const [value, setValue] = useState<any>();const [disabled, setDisabled] = useState(false);const [activated, setActivated] = useState(false);+ const [hidden, setHidden] = useState(false);useEffect(() => {const subscriptions: Subscription[] = [];@@ -51,6 +52,13 @@ export const ToolbarItem = forwardRef((props: IDisplayMenuItem<IMenuItem>, ref:}));+ props.hidden$ &&+ subscriptions.push(+ props.hidden$.subscribe((hidden) => {+ setHidden(hidden);+ })+ );+if (props.type === MenuItemType.BUTTON) {props.activated$ &&subscriptions.push(@@ -78,17 +86,17 @@ export const ToolbarItem = forwardRef((props: IDisplayMenuItem<IMenuItem>, ref:const tooltipTitle = localeService.t(tooltip ?? '') + (shortcut ? ` (${shortcut})` : '');- function renderSelectorType(menuType: MenuItemType) {- const { selections } = props as IDisplayMenuItem<IMenuSelectorItem>;-- const options = selections as IValueOption[];- let iconToDisplay = icon;- if (isObservable(icon)) {- iconToDisplay = useObservable(icon, undefined, true);- } else {- iconToDisplay = options?.find((o) => o.value === value)?.icon ?? icon;- }+ const { selections } = props as IDisplayMenuItem<IMenuSelectorItem>;++ const options = selections as IValueOption[];+ let iconToDisplay = icon;+ if (isObservable(icon)) {+ iconToDisplay = useObservable(icon, undefined, true);+ } else {+ iconToDisplay = options?.find((o) => o.value === value)?.icon ?? icon;+ }+ function renderSelectorType(menuType: MenuItemType) {function handleSelect(option: IValueOption) {let commandId = id;const value = option;@@ -183,7 +191,9 @@ export const ToolbarItem = forwardRef((props: IDisplayMenuItem<IMenuItem>, ref:}// ref component- return (+ return hidden ? (+ <></>+ ) : (<Tooltip ref={ref} title={tooltipTitle} placement="bottom">{renderItem()}</Tooltip>diff --git a/packages/ui/src/views/components/zen-zone/ZenZone.tsx b/packages/ui/src/views/components/zen-zone/ZenZone.tsxnew file mode 100644index 0000000000..e4a3390a4c--- /dev/null+++ b/packages/ui/src/views/components/zen-zone/ZenZone.tsx@@ -0,0 +1,60 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { useDependency } from '@wendellhu/redi/react-bindings';+import clsx from 'clsx';+import React, { useEffect, useMemo, useState } from 'react';++import { ComponentManager } from '../../../common/component-manager';+import { IZenZoneService } from '../../../services/zen-zone/zen-zone.service';+import styles from './index.module.less';++export function ZenZone() {+ const zenZoneService = useDependency(IZenZoneService);++ const [visible, setVisible] = useState(false);+ const [componentKey, setComponentKey] = useState<string>();++ const componentManager = useDependency(ComponentManager);++ useEffect(() => {+ const subscriptions = [+ zenZoneService.visible$.subscribe((visible) => {+ setVisible(visible);+ }),+ zenZoneService.componentKey$.subscribe((componentKey) => {+ setComponentKey(componentKey);+ }),+ ];++ return () => {+ subscriptions.forEach((subscription) => {+ subscription.unsubscribe();+ });+ };+ }, []);++ const _className = clsx(styles.zenZone, visible ? styles.zenZoneOpen : styles.zenZoneClose);++ const Component = useMemo(() => {+ const Component = componentManager.get(componentKey ?? '');+ if (Component) {+ return Component;+ }+ }, [componentKey]);++ return <section className={_className}>{Component && <Component />}</section>;+}diff --git a/packages/ui/src/views/components/zen-zone/index.module.less b/packages/ui/src/views/components/zen-zone/index.module.lessnew file mode 100644index 0000000000..cb5bd3df53--- /dev/null+++ b/packages/ui/src/views/components/zen-zone/index.module.less@@ -0,0 +1,21 @@+.zen-zone {+ position: absolute;+ display: none;++ &-open {+ z-index: 100;+ top: 0;+ left: 0;++ display: block;++ width: 100%;+ height: 100%;++ background: rgb(var(--bg-color));+ }++ &-close {+ display: none;+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 54991187d5..f1f594dae3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -155,6 +155,9 @@ importers:'@univerjs/engine-render':specifier: workspace:*version: link:../packages/engine-render+ '@univerjs/icons':+ specifier: ^0.1.18+ version: 0.1.18([email protected])([email protected])'@univerjs/local-save':specifier: workspace:*version: link:../packages/local-save@@ -188,6 +191,9 @@ importers:'@wendellhu/redi':specifier: ^0.12.12version: 0.12.12+ clsx:+ specifier: ^2.0.0+ version: 2.0.0monaco-editor:specifier: 0.45.0version: 0.45.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex a280a406ac..eb7d4d6959 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,4 +1,4 @@packages:# all packages in sub dirs of packages/ and Components/- - 'packages/**'- - 'examples/**'+ - ./packages/*+ - ./examples