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
refactor(*): refactor global focus management system (#1421)
Wenzhao Hub1d186fca0ba
diff --git a/docs/plugin-extension-capability.md b/docs/plugin-extension-capability.mdindex 35394d3896..7df3cd6557 100644--- a/docs/plugin-extension-capability.md+++ b/docs/plugin-extension-capability.md@@ -42,7 +42,7 @@ Provides basic operations and UI capabilities:* Rendering custom content at specified locations* Copy and paste (IClipboardService)* Supplementing clipboard content when copying to the clipboard, supplementing or modifying mutations when pasting from the clipboard-* Focus management (IFocusService)+* Focus management (ILayoutService)## base-renderdiff --git a/packages/docs-ui/src/controllers/app-ui-controller.ts b/packages/docs-ui/src/controllers/app-ui-controller.tsindex 3ad189a301..a96c766063 100644--- a/packages/docs-ui/src/controllers/app-ui-controller.ts+++ b/packages/docs-ui/src/controllers/app-ui-controller.ts@@ -18,7 +18,7 @@ import type { LocaleType } from '@univerjs/core';import { LocaleService, RxDisposable } from '@univerjs/core';import { Inject, Injector, Optional } from '@wendellhu/redi';-import { LayoutService } from '@univerjs/ui';+import { ILayoutService } from '@univerjs/ui';import { ITextSelectionRenderManager } from '@univerjs/engine-render';import type { IUniverDocsUIConfig } from '../basics';import { DocContainerUIController } from './doc-container-ui-controller';@@ -31,7 +31,7 @@ export class AppUIController extends RxDisposable {@Inject(LocaleService) private readonly _localeService: LocaleService,@Inject(Injector) private readonly _injector: Injector,@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,- @Optional(LayoutService) private readonly _layoutService?: LayoutService+ @Optional(ILayoutService) private readonly _layoutService?: ILayoutService) {super();this._docContainerController = this._injector.createInstance(DocContainerUIController, _config);@@ -42,7 +42,7 @@ export class AppUIController extends RxDisposable {if (this._layoutService) {this.disposeWithMe(// the content editable div should be regarded as part of the applications container- this._layoutService.registerContainer(this._textSelectionRenderManager.__getEditorContainer())+ this._layoutService.registerContainerElement(this._textSelectionRenderManager.__getEditorContainer()));}}diff --git a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts b/packages/docs-ui/src/shortcuts/core-editing.shortcut.tsindex d31e8c19bc..13920ae2a2 100644--- a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts+++ b/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts@@ -14,26 +14,26 @@* limitations under the License.*/-import { FOCUSING_DOC } from '@univerjs/core';import type { IShortcutItem } from '@univerjs/ui';import { KeyCode } from '@univerjs/ui';import { BreakLineCommand, DeleteLeftCommand, DeleteRightCommand } from '@univerjs/docs';+import { whenDocAndEditorFocused } from './utils';export const BreakLineShortcut: IShortcutItem = {id: BreakLineCommand.id,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,binding: KeyCode.ENTER,};export const DeleteLeftShortcut: IShortcutItem = {id: DeleteLeftCommand.id,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,binding: KeyCode.BACKSPACE,};export const DeleteRightShortcut: IShortcutItem = {id: DeleteRightCommand.id,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,binding: KeyCode.DELETE,};diff --git a/packages/docs-ui/src/shortcuts/cursor.shortcut.ts b/packages/docs-ui/src/shortcuts/cursor.shortcut.tsindex 7f8c826acf..650088609a 100644--- a/packages/docs-ui/src/shortcuts/cursor.shortcut.ts+++ b/packages/docs-ui/src/shortcuts/cursor.shortcut.ts@@ -14,16 +14,17 @@* limitations under the License.*/-import { Direction, EDITOR_ACTIVATED, FOCUSING_DOC } from '@univerjs/core';+import { Direction, EDITOR_ACTIVATED, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';import type { IShortcutItem } from '@univerjs/ui';import { KeyCode, MetaKeys } from '@univerjs/ui';import { MoveCursorOperation, MoveSelectionOperation, SelectAllOperation } from '@univerjs/docs';+import { whenDocAndEditorFocused } from './utils';export const MoveCursorUpShortcut: IShortcutItem = {id: MoveCursorOperation.id,binding: KeyCode.ARROW_UP,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.UP,},@@ -32,7 +33,7 @@ export const MoveCursorUpShortcut: IShortcutItem = {export const MoveCursorDownShortcut: IShortcutItem = {id: MoveCursorOperation.id,binding: KeyCode.ARROW_DOWN,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.DOWN,},@@ -41,7 +42,7 @@ export const MoveCursorDownShortcut: IShortcutItem = {export const MoveCursorLeftShortcut: IShortcutItem = {id: MoveCursorOperation.id,binding: KeyCode.ARROW_LEFT,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.LEFT,},@@ -50,7 +51,7 @@ export const MoveCursorLeftShortcut: IShortcutItem = {export const MoveCursorRightShortcut: IShortcutItem = {id: MoveCursorOperation.id,binding: KeyCode.ARROW_RIGHT,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.RIGHT,},@@ -59,7 +60,7 @@ export const MoveCursorRightShortcut: IShortcutItem = {export const MoveSelectionUpShortcut: IShortcutItem = {id: MoveSelectionOperation.id,binding: KeyCode.ARROW_UP | MetaKeys.SHIFT,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.UP,},@@ -68,7 +69,7 @@ export const MoveSelectionUpShortcut: IShortcutItem = {export const MoveSelectionDownShortcut: IShortcutItem = {id: MoveSelectionOperation.id,binding: KeyCode.ARROW_DOWN | MetaKeys.SHIFT,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.DOWN,},@@ -77,7 +78,7 @@ export const MoveSelectionDownShortcut: IShortcutItem = {export const MoveSelectionLeftShortcut: IShortcutItem = {id: MoveSelectionOperation.id,binding: KeyCode.ARROW_LEFT | MetaKeys.SHIFT,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.LEFT,},@@ -86,7 +87,7 @@ export const MoveSelectionLeftShortcut: IShortcutItem = {export const MoveSelectionRightShortcut: IShortcutItem = {id: MoveSelectionOperation.id,binding: KeyCode.ARROW_RIGHT | MetaKeys.SHIFT,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ preconditions: whenDocAndEditorFocused,staticParameters: {direction: Direction.RIGHT,},@@ -96,5 +97,5 @@ export const SelectAllShortcut: IShortcutItem = {id: SelectAllOperation.id,binding: KeyCode.A | MetaKeys.CTRL_COMMAND,preconditions: (contextService) =>- contextService.getContextValue(FOCUSING_DOC) || contextService.getContextValue(EDITOR_ACTIVATED),+ contextService.getContextValue(FOCUSING_UNIVER_EDITOR) && (contextService.getContextValue(FOCUSING_DOC) || contextService.getContextValue(EDITOR_ACTIVATED)),};diff --git a/packages/docs-ui/src/shortcuts/utils.ts b/packages/docs-ui/src/shortcuts/utils.tsnew file mode 100644index 0000000000..b033863a81--- /dev/null+++ b/packages/docs-ui/src/shortcuts/utils.ts@@ -0,0 +1,22 @@+/**+ * 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 { IContextService } from '@univerjs/core';+import { FOCUSING_DOC, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';++export function whenDocAndEditorFocused(contextService: IContextService): boolean {+ return contextService.getContextValue(FOCUSING_DOC) && contextService.getContextValue(FOCUSING_UNIVER_EDITOR);+}diff --git a/packages/engine-render/src/components/docs/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection-render-manager.tsindex 7a5790aead..f9a959b2bb 100644--- a/packages/engine-render/src/components/docs/text-selection-render-manager.ts+++ b/packages/engine-render/src/components/docs/text-selection-render-manager.ts@@ -154,13 +154,12 @@ export interface ITextSelectionRenderManager {sync(): void;activate(x: number, y: number): void;+ deactivate(): void;+ hasFocus(): boolean;focus(): void;-blur(): void;- deactivate(): void;-changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene, document: Documents): void;dispose(): void;@@ -321,6 +320,10 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel// requestAnimationFrame(() => this.focus());}+ hasFocus(): boolean {+ return document.activeElement === this._input;+ }+focus(): void {this._input.focus();}diff --git a/packages/find-replace/src/controllers/find-replace.controller.ts b/packages/find-replace/src/controllers/find-replace.controller.tsindex 662cab9f83..22e9f986ca 100644--- a/packages/find-replace/src/controllers/find-replace.controller.ts+++ b/packages/find-replace/src/controllers/find-replace.controller.ts@@ -23,7 +23,7 @@ import {RxDisposable,} from '@univerjs/core';import { SearchSingle16 } from '@univerjs/icons';-import { ComponentManager, IDialogService, IFocusService, IMenuService, IShortcutService } from '@univerjs/ui';+import { ComponentManager, IDialogService, ILayoutService, IMenuService, IShortcutService } from '@univerjs/ui';import { Inject, Injector } from '@wendellhu/redi';import { takeUntil } from 'rxjs';@@ -58,7 +58,7 @@ export class FindReplaceController extends RxDisposable {@IFindReplaceService private readonly _findReplaceService: IFindReplaceService,@IDialogService private readonly _dialogService: IDialogService,@IContextService private readonly _contextService: IContextService,- @IFocusService private readonly _focusService: IFocusService,+ @ILayoutService private readonly _layoutService: ILayoutService,@Inject(LocaleService) private readonly _localeService: LocaleService,@Inject(ComponentManager) private readonly _componentManager: ComponentManager,@Inject(Injector) private readonly _injector: Injector@@ -129,8 +129,7 @@ export class FindReplaceController extends RxDisposable {private _closePanel(): void {this._dialogService.close(FIND_REPLACE_DIALOG_ID);this._contextService.setContextValue(FIND_REPLACE_ACTIVATED, false);- this._focusService.forceFocus();-+ this._layoutService.focus();this._findReplaceService.end();}}diff --git a/packages/find-replace/src/views/dialog/Dialog.tsx b/packages/find-replace/src/views/dialog/Dialog.tsxindex a1f9e629a0..f0a49c0026 100644--- a/packages/find-replace/src/views/dialog/Dialog.tsx+++ b/packages/find-replace/src/views/dialog/Dialog.tsx@@ -16,7 +16,7 @@import { LocaleService } from '@univerjs/core';import { Button, FormLayout, Input, InputWithSlot, Pager, Select, useObservable } from '@univerjs/design';-import { LayoutService } from '@univerjs/ui';+import { ILayoutService } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';import { useDependency } from '@wendellhu/redi/react-bindings';import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react';@@ -29,7 +29,7 @@ const FIND_THROTTLE_TIME = 500;export function FindReplaceDialog() {const findReplaceService = useDependency(IFindReplaceService);const localeService = useDependency(LocaleService);- const layoutService = useDependency(LayoutService);+ const layoutService = useDependency(ILayoutService);const [findString, setFindString] = useState<string>('');const [replaceString, setReplaceString] = useState<string>('');@@ -65,7 +65,7 @@ export function FindReplaceDialog() {useEffect(() => {let disposable: IDisposable | undefined;if (dialogContainerRef.current) {- disposable = layoutService.registerContainer(dialogContainerRef.current);+ disposable = layoutService.registerContainerElement(dialogContainerRef.current);}return () => disposable?.dispose();diff --git a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts b/packages/sheets-ui/src/controllers/editor-bridge.controller.tsindex b0cebc3a92..f52a694b23 100644--- a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts+++ b/packages/sheets-ui/src/controllers/editor-bridge.controller.ts@@ -16,7 +16,7 @@import type { ICommandInfo, IExecutionOptions, Nullable } from '@univerjs/core';import { ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';-import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';+import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';import type { ISelectionWithStyle } from '@univerjs/sheets';import {COMMAND_LISTENER_SKELETON_CHANGE,@@ -24,8 +24,9 @@ import {SelectionManagerService,SetWorksheetActiveOperation,} from '@univerjs/sheets';-import { Inject } from '@wendellhu/redi';+import { Inject, Injector, Quantity } from '@wendellhu/redi';import { merge, takeUntil } from 'rxjs';+import { ILayoutService } from '@univerjs/ui';import { SetZoomRatioCommand } from '../commands/commands/set-zoom-ratio.command';import { SetActivateCellEditOperation } from '../commands/operations/activate-cell-edit.operation';@@ -37,11 +38,13 @@ import { getSheetObject } from './utils/component-tools';@OnLifecycle(LifecycleStages.Rendered, EditorBridgeController)export class EditorBridgeController extends RxDisposable {constructor(+ @Inject(Injector) private readonly _injector: Injector,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,@ICommandService private readonly _commandService: ICommandService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,+ @ILayoutService private readonly _layoutService: ILayoutService,@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService) {super();@@ -76,8 +79,12 @@ export class EditorBridgeController extends RxDisposable {return;}- const currentSkeleton = this._sheetSkeletonManagerService.getCurrent();+ const textSelectionRenderManager = this._injector.get(ITextSelectionRenderManager, Quantity.OPTIONAL);+ if (!this._layoutService.checkCanvasIsFocused() && textSelectionRenderManager && !textSelectionRenderManager!.hasFocus()) {+ return;+ }+ const currentSkeleton = this._sheetSkeletonManagerService.getCurrent();if (currentSkeleton == null) {return;}@@ -92,15 +99,12 @@ export class EditorBridgeController extends RxDisposable {}const sheetObject = this._getSheetObject();-if (sheetObject == null) {return;}const { unitId, sheetId } = currentSkeleton;-const { scene, engine } = sheetObject;-this._commandService.executeCommand(SetActivateCellEditOperation.id, {scene,engine,diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.tsindex a287eb77a3..18b93a3c82 100644--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { Disposable, ICommandService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';import {SetBoldCommand,SetFontFamilyCommand,@@ -24,10 +24,11 @@ import {SetUnderlineCommand,} from '@univerjs/sheets';import type { IDesktopUIController, IMenuItemFactory } from '@univerjs/ui';-import { ComponentManager, IMenuService, IShortcutService, IUIController } from '@univerjs/ui';+import { ComponentManager, ILayoutService, IMenuService, IShortcutService, IUIController } from '@univerjs/ui';import { Inject, Injector } from '@wendellhu/redi';import { connectInjector } from '@wendellhu/redi/react-bindings';+import { ITextSelectionRenderManager } from '@univerjs/engine-render';import {AddWorksheetMergeAllCommand,AddWorksheetMergeCommand,@@ -230,7 +231,8 @@ export class SheetUIController extends Disposable {@ICommandService private readonly _commandService: ICommandService,@IShortcutService private readonly _shortcutService: IShortcutService,@IMenuService private readonly _menuService: IMenuService,- @IUIController private readonly _uiController: IDesktopUIController+ @IUIController private readonly _uiController: IDesktopUIController,+ @ILayoutService private readonly _layoutService: ILayoutService) {super();@@ -464,5 +466,16 @@ export class SheetUIController extends Disposable {this._initMenus();this._initShortcuts();this._initWorkbenchParts();+ this._initFocusHandler();+ }++ private _initFocusHandler(): void {+ this.disposeWithMe(+ this._layoutService.registerFocusHandler(UniverInstanceType.SHEET, (_unitId: string) => {+ // DEBT: `_unitId` is not used hence we cannot support Univer mode now+ const textSelectionManagerService = this._injector.get(ITextSelectionRenderManager);+ textSelectionManagerService.focus();+ })+ );}}diff --git a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.tsindex edc17953c8..d21b03b34b 100644--- a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts@@ -119,7 +119,8 @@ export const EditorBreakLineShortcut: IShortcutItem = {export const EditorDeleteLeftShortcut: IShortcutItem = {id: DeleteLeftCommand.id,- preconditions: (contextService) => whenEditorActivated(contextService) || whenFormulaEditorFocused(contextService),+ preconditions: (contextService) =>+ whenEditorActivated(contextService) || whenFormulaEditorFocused(contextService),binding: KeyCode.BACKSPACE,};diff --git a/packages/sheets-ui/src/controllers/shortcuts/utils.ts b/packages/sheets-ui/src/controllers/shortcuts/utils.tsindex 370fad04fe..55f38dad81 100644--- a/packages/sheets-ui/src/controllers/shortcuts/utils.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/utils.ts@@ -54,7 +54,7 @@ export function whenSheetEditorActivated(contextService: IContextService) {}export function whenEditorActivated(contextService: IContextService) {- return contextService.getContextValue(EDITOR_ACTIVATED);+ return contextService.getContextValue(FOCUSING_UNIVER_EDITOR) && contextService.getContextValue(EDITOR_ACTIVATED);}/**@@ -86,6 +86,7 @@ export function whenFormulaEditorActivated(contextService: IContextService) {export function whenEditorDidNotInputFormulaActivated(contextService: IContextService) {return (contextService.getContextValue(FOCUSING_SHEET) &&+ contextService.getContextValue(FOCUSING_UNIVER_EDITOR) &&contextService.getContextValue(EDITOR_ACTIVATED) &&!contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA));diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsxindex 50efbdf8ae..a3c1c7087c 100644--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx@@ -17,7 +17,6 @@import type { ICommandInfo } from '@univerjs/core';import { ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';import { Dropdown } from '@univerjs/design';-import { ITextSelectionRenderManager } from '@univerjs/engine-render';import {InsertSheetMutation,RemoveSheetMutation,@@ -120,14 +119,6 @@ export function SheetBarTabs() {onVisibleChange(true);}});-- // The 'onChangeTab' event occurs during the 'pointerDown' event.- // The triggering time is too early.- // Settimeout is required to delay resetting the focus.- setTimeout(() => {- const textSelectionRenderManager = injector.get(ITextSelectionRenderManager);- textSelectionRenderManager.focus();- }, 0);},onScroll: (state: IScrollState) => {sheetBarService.setScroll(state);diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsxindex e07b95a43a..b74ec4dd73 100644--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx@@ -17,7 +17,7 @@import { Disposable, LifecycleService, LifecycleStages, toDisposable } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import type { IDisposable } from '@wendellhu/redi';-import { Inject, Injector, Optional } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';import { connectInjector } from '@wendellhu/redi/react-bindings';import { render as createRoot, unmount } from 'rc-util/lib/React/render';import type { ComponentType } from 'react';@@ -25,8 +25,7 @@ import React from 'react';import type { Observable } from 'rxjs';import { Subject } from 'rxjs';-import { IFocusService } from '../../services/focus/focus.service';-import { LayoutService } from '../../services/layout/layout.service';+import { ILayoutService } from '../../services/layout/layout.service';import { App } from '../../views/App';import type { IWorkbenchOptions } from './ui.controller';import { IUIController } from './ui.controller';@@ -83,8 +82,7 @@ export class DesktopUIController extends Disposable implements IDesktopUIControl@Inject(Injector) private readonly _injector: Injector,@Inject(LifecycleService) private readonly _lifecycleService: LifecycleService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @IFocusService private readonly _focusService: IFocusService,- @Optional(LayoutService) private readonly _layoutService?: LayoutService+ @ILayoutService private readonly _layoutService: ILayoutService) {super();}@@ -94,10 +92,10 @@ export class DesktopUIController extends Disposable implements IDesktopUIControlbootStrap(this._injector, options, (canvasElement, containerElement) => {this._initializeEngine(canvasElement);this._lifecycleService.stage = LifecycleStages.Rendered;- this._focusService.setContainerElement(containerElement);if (this._layoutService) {- this.disposeWithMe(this._layoutService.registerContainer(containerElement));+ this.disposeWithMe(this._layoutService.registerRootContainerElement(containerElement));+ this.disposeWithMe(this._layoutService.registerCanvasElement(canvasElement as HTMLCanvasElement));}setTimeout(() => (this._lifecycleService.stage = LifecycleStages.Steady), STEADY_TIMEOUT);diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex cba4a1863f..d3fb861d7c 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -47,8 +47,7 @@ export {} from './services/contextmenu/contextmenu.service';export { DesktopDialogService } from './services/dialog/desktop-dialog.service';export { IDialogService } from './services/dialog/dialog.service';-export { IFocusService } from './services/focus/focus.service';-export { LayoutService } from './services/layout/layout.service';+export { ILayoutService } from './services/layout/layout.service';export {type ICustomComponentProps,type IDisplayMenuItem,diff --git a/packages/ui/src/services/focus/focus.service.ts b/packages/ui/src/services/focus/focus.service.tsdeleted file mode 100644index 430fea2364..0000000000--- a/packages/ui/src/services/focus/focus.service.ts+++ /dev/null@@ -1,104 +0,0 @@-/**- * 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 { ContextService, Nullable } from '@univerjs/core';-import {- Disposable,- FOCUSING_UNIVER_EDITOR,- IContextService,- ILogService,- LifecycleStages,- OnLifecycle,- toDisposable,-} from '@univerjs/core';-import { createIdentifier } from '@wendellhu/redi';-import { fromEvent } from 'rxjs';--/**- * FocusService manages focusing state of the Univer application instance.- */-export const IFocusService = createIdentifier<IFocusService>('univer.focus-service');-export interface IFocusService {- readonly isFocused: boolean;-- forceFocus(): void;- setContainerElement(container: HTMLElement): void;-}--export const FOCUSING_UNIVER = 'FOCUSING_UNIVER';--@OnLifecycle(LifecycleStages.Ready, IFocusService)-export class DesktopFocusService extends Disposable implements IFocusService {- private _containerElement: Nullable<HTMLElement> = null;-- private _isUniverFocused = true;-- get isFocused(): boolean {- return this._isUniverFocused;- }-- constructor(- @IContextService private readonly _contextService: ContextService,- @ILogService private readonly _logService: ILogService- ) {- super();-- this._initFocusListener();- this._initEditorStatus();-- // @ts-ignore- window._contextService = this;- }-- override dispose(): void {- super.dispose();-- this._containerElement = null;- }-- setContainerElement(container: HTMLElement): void {- this._containerElement = container;- }-- forceFocus(): void {}-- private _initFocusListener(): void {- this.disposeWithMe(- toDisposable(- fromEvent(window, 'focusin').subscribe((event) => {- if (event.target && this._containerElement?.contains(event.target as Node)) {- this._isUniverFocused = true;- } else {- this._isUniverFocused = false;- }-- this._contextService.setContextValue(FOCUSING_UNIVER, this._isUniverFocused);- this._contextService.setContextValue(- FOCUSING_UNIVER_EDITOR,- (event.target as HTMLElement).classList.contains('univer-editor')- );- })- )- );- }-- private _initEditorStatus(): void {- this._contextService.setContextValue(- FOCUSING_UNIVER_EDITOR,- !!document.activeElement?.classList.contains('univer-editor')- );- }-}diff --git a/packages/ui/src/services/layout/layout.service.ts b/packages/ui/src/services/layout/layout.service.tsindex a9e8af6abf..2e65c19300 100644--- a/packages/ui/src/services/layout/layout.service.ts+++ b/packages/ui/src/services/layout/layout.service.ts@@ -14,26 +14,164 @@* limitations under the License.*/-import { remove, toDisposable } from '@univerjs/core';-import type { IDisposable } from '@wendellhu/redi';+import type { ContextService, Nullable } from '@univerjs/core';+import { Disposable, DocumentDataModel, FOCUSING_UNIVER_EDITOR, IContextService, ILogService, IUniverInstanceService, LifecycleStages, OnLifecycle, remove, Slide, toDisposable, UniverInstanceType, Workbook } from '@univerjs/core';+import { createIdentifier, type IDisposable } from '@wendellhu/redi';+import { fromEvent } from 'rxjs';++type FocusHandlerFn = (unitId: string) => void;++export const FOCUSING_UNIVER = 'FOCUSING_UNIVER';++export interface ILayoutService {+ readonly isFocused: boolean;++ /** Re-focus the currently focused Univer business instance. */+ focus(): void;++ /** Register a focus handler to focus on certain type of Univer unit. */+ registerFocusHandler(type: UniverInstanceType, handler: FocusHandlerFn): IDisposable;+ /** Register the root container element. */+ registerRootContainerElement(container: HTMLElement): IDisposable;+ /** Register a canvas element. */+ registerCanvasElement(container: HTMLCanvasElement): IDisposable;+ /** Register an element as a container, especially floating components like Dialogs and Notifications. */+ registerContainerElement(container: HTMLElement): IDisposable;++ checkElementInCurrentContainers(element: HTMLElement): boolean;+ checkCanvasIsFocused(): boolean;+}+export const ILayoutService = createIdentifier<ILayoutService>('ui.layout-service');/*** This service is responsible for storing layout information of the current- * Univer application instance+ * Univer application instance.*/-export class LayoutService {- private _containers: HTMLElement[] = [];+@OnLifecycle(LifecycleStages.Ready, ILayoutService)+export class DesktopLayoutService extends Disposable implements ILayoutService {+ private _rootContainerElement: Nullable<HTMLElement> = null;+ private _isFocused = false;++ get isFocused(): boolean {+ return this._isFocused;+ }++ private readonly _focusHandlers = new Map<UniverInstanceType, FocusHandlerFn>();++ private _canvasContainers: HTMLCanvasElement[] = [];+ private _allContainers: HTMLElement[] = [];++ constructor(+ @IContextService private readonly _contextService: ContextService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @ILogService private readonly _logService: ILogService+ ) {+ super();- registerContainer(container: HTMLElement): IDisposable {- if (this._containers.indexOf(container) === -1) {- this._containers.push(container);- return toDisposable(() => remove(this._containers, container));+ this._initUniverFocusListener();+ this._initEditorStatus();+ }++ focus(): void {+ const currentFocused = this._univerInstanceService.getFocusedUniverInstance();+ if (!currentFocused) {+ return;+ }++ let handler: Nullable<FocusHandlerFn>;+ if (currentFocused instanceof Workbook) {+ handler = this._focusHandlers.get(UniverInstanceType.SHEET);+ } else if (currentFocused instanceof DocumentDataModel) {+ handler = this._focusHandlers.get(UniverInstanceType.DOC);+ } else if (currentFocused instanceof Slide) {+ handler = this._focusHandlers.get(UniverInstanceType.SLIDE);+ }++ if (!handler) {+ throw new Error('[DesktopLayoutService]: handler is not registered!');+ }++ handler(currentFocused.getUnitId());+ }++ registerFocusHandler(type: UniverInstanceType, handler: FocusHandlerFn): IDisposable {+ if (this._focusHandlers.has(type)) {+ throw new Error(`[DesktopLayoutService]: handler of type ${type} bas been registered!`);+ }++ this._focusHandlers.set(type, handler);+ return toDisposable(() => this._focusHandlers.delete(type));+ }++ registerCanvasElement(container: HTMLCanvasElement): IDisposable {+ if (this._canvasContainers.indexOf(container) === -1) {+ this._canvasContainers.push(container);+ return toDisposable(() => remove(this._canvasContainers, container));+ }++ throw new Error('[DesktopLayoutService]: canvas container already registered!');+ }++ registerRootContainerElement(container: HTMLElement): IDisposable {+ if (this._rootContainerElement) {+ throw new Error('[DesktopLayoutService]: root container already registered!');+ }++ this._rootContainerElement = container;+ const dis = this.registerContainerElement(container);++ return toDisposable(() => {+ this._rootContainerElement = null;+ dis.dispose();+ });+ }++ registerContainerElement(container: HTMLElement): IDisposable {+ if (this._allContainers.indexOf(container) === -1) {+ this._allContainers.push(container);+ return toDisposable(() => remove(this._allContainers, container));}throw new Error('[LayoutService]: container already registered!');}- checkElementInCurrentApplicationScope(element: HTMLElement): boolean {- return this._containers.some((container) => container.contains(element));+ checkElementInCurrentContainers(element: HTMLElement): boolean {+ return this._allContainers.some((container) => container.contains(element));+ }++ checkCanvasIsFocused(): boolean {+ return this._canvasContainers.some((canvas) => canvas === document.activeElement || canvas.contains(document.activeElement));}++ private _initUniverFocusListener(): void {+ this.disposeWithMe(+ fromEvent(window, 'focusin').subscribe((event) => {+ const target = event.target as HTMLElement;+ if (target.classList.contains('univer-app-layout')) {+ Promise.resolve().then(() => this.focus());+ return;+ }++ if (target && this.checkElementInCurrentContainers(target as HTMLElement)) {+ this._isFocused = true;+ } else {+ this._isFocused = false;+ }++ this._contextService.setContextValue(FOCUSING_UNIVER, this._isFocused);+ this._contextService.setContextValue(FOCUSING_UNIVER_EDITOR, getFocusingUniverEditorStatus());+ })+ );+ }++ private _initEditorStatus(): void {+ this._contextService.setContextValue(+ FOCUSING_UNIVER_EDITOR,+ getFocusingUniverEditorStatus()+ );+ }+}++function getFocusingUniverEditorStatus(): boolean {+ return !!document.activeElement?.classList.contains('univer-editor');}diff --git a/packages/ui/src/services/shortcut/shortcut.service.ts b/packages/ui/src/services/shortcut/shortcut.service.tsindex c3e29b3668..a538e14e76 100644--- a/packages/ui/src/services/shortcut/shortcut.service.ts+++ b/packages/ui/src/services/shortcut/shortcut.service.ts@@ -21,7 +21,7 @@ import type { Observable } from 'rxjs';import { Subject } from 'rxjs';import { fromDocumentEvent } from '../../common/lifecycle';-import { LayoutService } from '../layout/layout.service';+import { ILayoutService } from '../layout/layout.service';import { IPlatformService } from '../platform/platform.service';import { KeyCodeToChar, MetaKeys } from './keycode';@@ -83,7 +83,7 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi@ICommandService private readonly _commandService: ICommandService,@IPlatformService private readonly _platformService: IPlatformService,@IContextService private readonly _contextService: IContextService,- @Optional(LayoutService) private readonly _layoutService?: LayoutService+ @Optional(ILayoutService) private readonly _layoutService?: ILayoutService) {super();@@ -188,7 +188,7 @@ export class DesktopShortcutService extends Disposable implements IShortcutServiif (this._layoutService &&- !this._layoutService.checkElementInCurrentApplicationScope(e.target as HTMLElement)+ !this._layoutService.checkElementInCurrentContainers(e.target as HTMLElement)) {return;}diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.tsindex d6f0c0548e..8003a4320f 100644--- a/packages/ui/src/ui-plugin.ts+++ b/packages/ui/src/ui-plugin.ts@@ -36,8 +36,7 @@ import { DesktopConfirmService } from './services/confirm/desktop-confirm.servicimport { DesktopContextMenuService, IContextMenuService } from './services/contextmenu/contextmenu.service';import { DesktopDialogService } from './services/dialog/desktop-dialog.service';import { IDialogService } from './services/dialog/dialog.service';-import { DesktopFocusService, IFocusService } from './services/focus/focus.service';-import { LayoutService } from './services/layout/layout.service';+import { DesktopLayoutService, ILayoutService } from './services/layout/layout.service';import { DesktopLocalStorageService } from './services/local-storage/local-storage.service';import { DesktopMenuService, IMenuService } from './services/menu/menu.service';import { DesktopMessageService } from './services/message/desktop-message.service';@@ -96,7 +95,7 @@ export class UniverUIPlugin extends Plugin {// services[ShortcutPanelService],- [LayoutService],+ [ILayoutService, { useClass: DesktopLayoutService }],[IShortcutService, { useClass: DesktopShortcutService }],[IPlatformService, { useClass: DesktopPlatformService }],[IMenuService, { useClass: DesktopMenuService }],@@ -113,7 +112,6 @@ export class UniverUIPlugin extends Plugin {[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],// controllers- [IFocusService, { useClass: DesktopFocusService }],[IUIController, { useClass: DesktopUIController }],[SharedController],[ErrorController],diff --git a/packages/ui/src/views/App.tsx b/packages/ui/src/views/App.tsxindex 0c2b6eb0fd..2135027473 100644--- a/packages/ui/src/views/App.tsx+++ b/packages/ui/src/views/App.tsx@@ -95,7 +95,12 @@ export function App(props: IUniverAppProps) {return (<ConfigProvider locale={locale} mountContainer={portalContainer}>- <div className={styles.appLayout}>+ {/**+ * IMPORTANT! This `tabIndex` should not be moved. This attribute allows the element to catch+ * all focusin event merged from its descendants. The DesktopLayoutService would listen to focusin events+ * bubbled to this element and refocus the input element.+ */}+ <div className={styles.appLayout} tabIndex={-1}>{/* header */}{props.toolbar && (<header className={styles.appContainerHeader}>