Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

refactor(*): implement shortcut service & UI services (#71)

Wenzhao Hu4eff6b6fd510
diff --git a/.eslintrc.js b/.eslintrc.js
index e7425e002e..a8070d32bc 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -101,8 +101,8 @@ module.exports = {
'grouped-accessor-pairs': 'off',
'@typescript-eslint/member-ordering': 'error',
'@typescript-eslint/no-explicit-any': 'warn',
+ 'no-unsafe-optional-chaining': 'off',
'@typescript-eslint/consistent-type-assertions': 'off',
- '@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-redeclare': 'off', // dependency interface and dependency token share the same name
},
// https://www.npmjs.com/package/eslint-import-resolver-typescript
diff --git a/package.json b/package.json
index 914e7eb473..c9c662f0e9 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "univer",
"version": "1.0.0-pre-alpha",
- "description": "Univer,Luckysheet 2.0 upgrade version",
+ "description": "Univer, Luckysheet 2.0 upgrade version",
"private": true,
"scripts": {
"test": "node scripts/test",
@@ -85,4 +85,4 @@
"dependencies": {
"pnpm": "^8.6.4"
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
index 149354aaaf..5a474806e0 100644
--- a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
+++ b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
@@ -25,4 +25,4 @@ export class BasicWorksheetController extends Disposable implements IDisposable
async clearSelectionContent(): Promise<boolean> {
return this._commandService.executeCommand(ClearSelectionContentCommand.id);
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-sheets/src/Controller/ToolbarController.ts b/packages/base-sheets/src/Controller/ToolbarController.ts
index 73cfb5f740..a0b62b88ac 100644
--- a/packages/base-sheets/src/Controller/ToolbarController.ts
+++ b/packages/base-sheets/src/Controller/ToolbarController.ts
@@ -6,7 +6,6 @@ import {
WrapStrategy,
ObserverManager,
ICurrentUniverService,
- CommandManager,
ICommandService,
UndoCommand,
RedoCommand,
@@ -240,4 +239,4 @@ export class ToolbarController {
});
}
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-ui/package.json b/packages/base-ui/package.json
index 15fe5b8e5f..5ebf9f907f 100644
--- a/packages/base-ui/package.json
+++ b/packages/base-ui/package.json
@@ -10,7 +10,6 @@
"license": "MIT",
"main": "./src/index.ts",
"module": "./src/index.ts",
- "types": "./src/Types/index.d.ts",
"publishConfig": {
"main": "./lib/univer-base-ui.cjs.js",
"module": "./lib/univer-base-ui.js",
@@ -69,6 +68,7 @@
"@univerjs/core": "workspace:^0.0.1",
"@wendellhu/redi": "^0.12.6",
"preact": "^10.12.1",
- "react-colorful": "^5.3.0"
+ "react-colorful": "^5.3.0",
+ "rxjs": "^7.8.1"
}
}
\ No newline at end of file
diff --git a/packages/base-ui/src/Common/lifecycle.ts b/packages/base-ui/src/Common/lifecycle.ts
new file mode 100644
index 0000000000..4aee5a8767
--- /dev/null
+++ b/packages/base-ui/src/Common/lifecycle.ts
@@ -0,0 +1,23 @@
+import { toDisposable } from '@univerjs/core';
+import { IDisposable } from '@wendellhu/redi';
+
+export function fromDocumentEvent<K extends keyof DocumentEventMap>(
+ type: K,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ listener: (this: Document, ev: DocumentEventMap[K]) => any,
+ options?: boolean | AddEventListenerOptions
+): IDisposable {
+ document.addEventListener(type, listener, options);
+ return toDisposable(() => document.removeEventListener(type, listener, options));
+}
+
+export function fromEvent<K extends keyof HTMLElementEventMap>(
+ target: HTMLElement,
+ type: K,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any,
+ options?: boolean | AddEventListenerOptions
+): IDisposable {
+ target.addEventListener(type, listener, options);
+ return toDisposable(() => target.removeEventListener(type, listener, options));
+}
diff --git a/packages/base-ui/src/Components/Button/Button.tsx b/packages/base-ui/src/Components/Button/Button.tsx
index fecdd5bac5..c19ce0108a 100644
--- a/packages/base-ui/src/Components/Button/Button.tsx
+++ b/packages/base-ui/src/Components/Button/Button.tsx
@@ -1,120 +1,121 @@
-import { BaseButtonProps } from '../../BaseComponent';
-import { Component } from '../../Framework';
-import { joinClassNames } from '../../Utils';
-import { LoadingIcon } from '../Icon';
-import styles from './Style/index.module.less';
-
-// const ButtonTypes: string[] = ['default', 'primary'];
-// export type ButtonType = typeof ButtonTypes[number];
-// const ButtonShapes: string[] = ['circle', 'round'];
-// export type ButtonShape = typeof ButtonShapes[number];
-// const SizeTypes: string[] = ['small', 'middle', 'large'];
-// export type SizeType = typeof SizeTypes[number];
-// const ButtonHTMLTypes: string[] = ['submit', 'rest', 'button'];
-// export type ButtonHTMLType = typeof ButtonHTMLTypes[number];
-
-// export interface BaseButtonProps extends BaseComponentProps {
-// type?: ButtonType;
-// shape?: ButtonShape;
-// size?: SizeType;
-// danger?: boolean;
-// disabled?: boolean;
-// block?: boolean;
-// loading?: boolean;
-// htmlType?: ButtonHTMLType;
-// onClick?: Function;
-// children?: any;
-// className?: string;
-// style?: JSX.CSSProperties;
-// isActive?: true;
-// }
-
-interface IState {
- isActive: boolean;
-}
-
-class Button extends Component<BaseButtonProps, IState> {
- constructor(props: BaseButtonProps) {
- super();
- this.state = {
- isActive: props.active ?? false,
- };
- }
-
- getSizeCls() {
- const { size } = this.props;
- let sizeCls = '';
- switch (size) {
- case 'large':
- sizeCls = 'lg';
- break;
- case 'small':
- sizeCls = 'sm';
- break;
- default:
- break;
- }
- return sizeCls;
- }
-
- getClass() {
- const { isActive } = this.state;
- const { type, shape, danger, block, loading, size, className } = this.props;
- return joinClassNames(
- styles.btn,
- {
- [`${styles.btn}-${type}`]: type,
- [`${styles.btn}-${shape}`]: shape,
- [`${styles.btn}-${this.getSizeCls()}`]: size,
- [`${styles.btn}-danger`]: !!danger,
- [`${styles.btn}-block`]: block,
- [`${styles.btn}-loading`]: loading,
- [`${styles.btn}-active`]: isActive,
- },
- className
- );
- }
-
- handleClick = (e: MouseEvent) => {
- const { disabled, onClick, unActive = true } = this.props;
-
- if (disabled) {
- e.preventDefault();
- return;
- }
-
- if (unActive) {
- onClick?.(e);
- return;
- }
-
- this.setState(
- {
- isActive: !this.state.isActive,
- },
- () => {
- if (onClick) {
- onClick.call(null, e, this.state.isActive);
- }
- }
- );
- };
-
- componentWillReceiveProps(props: BaseButtonProps) {
- this.setState({
- isActive: props.active,
- });
- }
-
- render() {
- const { htmlType, disabled, style, loading, children } = this.props;
- return (
- <button type={htmlType} onClick={this.handleClick} className={this.getClass()} disabled={disabled} style={style}>
- {loading ? <LoadingIcon /> : ''}
- {children}
- </button>
- );
- }
-}
-
-export default Button;
+import { BaseButtonProps } from '../../BaseComponent';
+import { Component } from '../../Framework';
+import { joinClassNames } from '../../Utils';
+import { LoadingIcon } from '../Icon';
+
+import styles from './Style/index.module.less';
+
+// const ButtonTypes: string[] = ['default', 'primary'];
+// export type ButtonType = typeof ButtonTypes[number];
+// const ButtonShapes: string[] = ['circle', 'round'];
+// export type ButtonShape = typeof ButtonShapes[number];
+// const SizeTypes: string[] = ['small', 'middle', 'large'];
+// export type SizeType = typeof SizeTypes[number];
+// const ButtonHTMLTypes: string[] = ['submit', 'rest', 'button'];
+// export type ButtonHTMLType = typeof ButtonHTMLTypes[number];
+
+// export interface BaseButtonProps extends BaseComponentProps {
+// type?: ButtonType;
+// shape?: ButtonShape;
+// size?: SizeType;
+// danger?: boolean;
+// disabled?: boolean;
+// block?: boolean;
+// loading?: boolean;
+// htmlType?: ButtonHTMLType;
+// onClick?: Function;
+// children?: any;
+// className?: string;
+// style?: JSX.CSSProperties;
+// isActive?: true;
+// }
+
+interface IState {
+ isActive: boolean;
+}
+
+class Button extends Component<BaseButtonProps, IState> {
+ constructor(props: BaseButtonProps) {
+ super();
+ this.state = {
+ isActive: props.active ?? false,
+ };
+ }
+
+ getSizeCls() {
+ const { size } = this.props;
+ let sizeCls = '';
+ switch (size) {
+ case 'large':
+ sizeCls = 'lg';
+ break;
+ case 'small':
+ sizeCls = 'sm';
+ break;
+ default:
+ break;
+ }
+ return sizeCls;
+ }
+
+ getClass() {
+ const { isActive } = this.state;
+ const { type, shape, danger, block, loading, size, className } = this.props;
+ return joinClassNames(
+ styles.btn,
+ {
+ [`${styles.btn}-${type}`]: type,
+ [`${styles.btn}-${shape}`]: shape,
+ [`${styles.btn}-${this.getSizeCls()}`]: size,
+ [`${styles.btn}-danger`]: !!danger,
+ [`${styles.btn}-block`]: block,
+ [`${styles.btn}-loading`]: loading,
+ [`${styles.btn}-active`]: isActive,
+ },
+ className
+ );
+ }
+
+ handleClick = (e: MouseEvent) => {
+ const { disabled, onClick, unActive = true } = this.props;
+
+ if (disabled) {
+ e.preventDefault();
+ return;
+ }
+
+ if (unActive) {
+ onClick?.(e);
+ return;
+ }
+
+ this.setState(
+ {
+ isActive: !this.state.isActive,
+ },
+ () => {
+ if (onClick) {
+ onClick.call(null, e, this.state.isActive);
+ }
+ }
+ );
+ };
+
+ componentWillReceiveProps(props: BaseButtonProps) {
+ this.setState({
+ isActive: props.active,
+ });
+ }
+
+ render() {
+ const { htmlType, disabled, style, loading, children } = this.props;
+ return (
+ <button type={htmlType} onClick={this.handleClick} className={this.getClass()} disabled={disabled} style={style}>
+ {loading ? <LoadingIcon /> : ''}
+ {children}
+ </button>
+ );
+ }
+}
+
+export default Button;
\ No newline at end of file
diff --git a/packages/base-ui/src/Components/Tooltip/Tooltip.tsx b/packages/base-ui/src/Components/Tooltip/Tooltip.tsx
index a4cd25c9c7..6977756d9b 100644
--- a/packages/base-ui/src/Components/Tooltip/Tooltip.tsx
+++ b/packages/base-ui/src/Components/Tooltip/Tooltip.tsx
@@ -1,8 +1,9 @@
import { Component, createRef } from '../../Framework';
import { BaseTooltipProps } from '../../Interfaces';
-import style from './index.module.less';
import { joinClassNames } from '../../Utils';
+import style from './index.module.less';
+
// interface TooltipProps {
// title: string;
// children: ComponentChildren;
@@ -30,7 +31,7 @@ const placementClassNames: { [index: string]: string } = {
export class Tooltip extends Component<BaseTooltipProps, TooltipState> {
tooltip = createRef<HTMLDivElement>();
- initialize(props: BaseTooltipProps) {
+ override initialize(props: BaseTooltipProps) {
this.state = {
placement: props.placement || 'top',
placementClassName: joinClassNames(style.tooltipTitle, placementClassNames[props.placement || 'top']),
@@ -42,9 +43,9 @@ export class Tooltip extends Component<BaseTooltipProps, TooltipState> {
handleMouseOver() {
if (this.tooltip && this.tooltip.current) {
- let tooltipInfo = this.tooltip.current.getBoundingClientRect();
- let top = tooltipInfo.height;
- let left = tooltipInfo.width;
+ const tooltipInfo = this.tooltip.current.getBoundingClientRect();
+ const top = tooltipInfo.height;
+ const left = tooltipInfo.width;
if (this.state.placement === 'bottom') {
this.setState({
diff --git a/packages/base-ui/src/Services/Toolbar/toolbar.service.ts b/packages/base-ui/src/Services/Toolbar/toolbar.service.ts
deleted file mode 100644
index 66f8efeb69..0000000000
--- a/packages/base-ui/src/Services/Toolbar/toolbar.service.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { createIdentifier } from '@wendellhu/redi';
-
-export interface IToolbarItem {}
-
-export interface IToolbarService {}
-
-export const IToolbarService = createIdentifier<IToolbarService>('univer.toolbar-service');
-
-export class DesktopToolbarService implements IToolbarService {
-
-}
diff --git a/packages/base-ui/src/Types/index.d.ts b/packages/base-ui/src/Types/index.d.ts
deleted file mode 100644
index a221989805..0000000000
--- a/packages/base-ui/src/Types/index.d.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/// <reference types="vite/client" />
-
-export * from '../index';
-declare module '@univerjs/base-ui' {}
-
-// use css module
-declare module '*.less' {
- const resource: { [key: string]: string };
- export = resource;
-}
diff --git a/packages/base-ui/src/Types/preact.d.ts b/packages/base-ui/src/Types/preact.d.ts
deleted file mode 100644
index 0d092b3751..0000000000
--- a/packages/base-ui/src/Types/preact.d.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-/// <reference types="enzyme-adapter-preact-pure" />
-import JSX = preact.JSX;
-
-declare module 'enzyme';
diff --git a/packages/base-ui/src/controllers/shared.controller.ts b/packages/base-ui/src/controllers/shared.controller.ts
new file mode 100644
index 0000000000..f7315afb7e
--- /dev/null
+++ b/packages/base-ui/src/controllers/shared.controller.ts
@@ -0,0 +1,37 @@
+import { Disposable, ICommandService, RedoCommand, UndoCommand } from '@univerjs/core';
+
+import { IShortcutItem, IShortcutService } from '../services/shortcut/shorcut.service';
+import { KeyCode, MetaKeys } from '../services/shortcut/keycode';
+
+export const UndoShortcutItem: IShortcutItem = {
+ id: UndoCommand.id,
+ binding: KeyCode.Z | MetaKeys.CTRL_COMMAND,
+};
+
+export const RedoShortcutItem: IShortcutItem = {
+ id: RedoCommand.id,
+ binding: KeyCode.Y | MetaKeys.CTRL_COMMAND,
+};
+
+/**
+ * Define shared UI behavior across Univer business.
+ */
+export class SharedController extends Disposable {
+ constructor(@IShortcutService private readonly _shortcutService: IShortcutService, @ICommandService private readonly _commandService: ICommandService) {
+ super();
+
+ this.registerShortcuts();
+ }
+
+ private registerToolbarItem(): void {}
+
+ private registerContextMenuItem(): void {}
+
+ private registerFooterItem(): void {}
+
+ private registerShortcuts(): void {
+ [UndoShortcutItem, RedoShortcutItem].forEach((shortcut) => {
+ this.disposeWithMe(this._shortcutService.registerShortcut(shortcut));
+ });
+ }
+}
diff --git a/packages/base-ui/src/Services/Clipboard/clipboard.service.ts b/packages/base-ui/src/hooks/use-dependency.ts
similarity index 100%
rename from packages/base-ui/src/Services/Clipboard/clipboard.service.ts
rename to packages/base-ui/src/hooks/use-dependency.ts
diff --git a/packages/base-ui/src/index.ts b/packages/base-ui/src/index.ts
index 31d1e405a0..b4aa35e848 100644
--- a/packages/base-ui/src/index.ts
+++ b/packages/base-ui/src/index.ts
@@ -8,3 +8,10 @@ export * from './Components';
export * from './BaseComponent';
export * from './Framework';
export * from './UIPlugin';
+
+export { IMenuService, IMenuItem, MenuPosition, DesktopMenuService } from './services/menu/menu.service';
+export { KeyCode, MetaKeys } from './services/shortcut/keycode';
+export { IShortcutService, IShortcutItem, DesktopShortcutService } from './services/shortcut/shorcut.service';
+export { IPlatformService, DesktopPlatformService } from './services/platform/platform.service';
+
+export { SharedController } from './controllers/shared.controller';
diff --git a/packages/base-ui/src/Services/ContextMenu/contextMenu.service.ts b/packages/base-ui/src/services/clipboard/clipboard.service.ts
similarity index 100%
rename from packages/base-ui/src/Services/ContextMenu/contextMenu.service.ts
rename to packages/base-ui/src/services/clipboard/clipboard.service.ts
diff --git a/packages/base-ui/src/services/menu/menu.service.ts b/packages/base-ui/src/services/menu/menu.service.ts
new file mode 100644
index 0000000000..86ba3d93ad
--- /dev/null
+++ b/packages/base-ui/src/services/menu/menu.service.ts
@@ -0,0 +1,105 @@
+import { Disposable, toDisposable } from '@univerjs/core';
+import { createIdentifier, IDisposable } from '@wendellhu/redi';
+import { Observable } from 'rxjs';
+
+export type OneOrMany<T> = T | T[];
+
+export const enum MenuPosition {
+ TOOLBAR,
+ CONTEXT_MENU,
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export interface IMenuItemState {
+ id: string;
+
+ disabled?: boolean;
+ hidden?: boolean;
+ checked?: boolean;
+}
+
+export interface IMenuItem {
+ id: string;
+ menu: OneOrMany<MenuPosition>;
+ title: string;
+
+ icon?: string;
+ tooltip?: string;
+ description?: string;
+
+ disabled$?: Observable<boolean>;
+ hidden?: Observable<boolean>;
+ checked?: Observable<boolean>; // TODO: @wzhudev: maybe we should add a `data` property here instead of `checked` property?
+
+ handler?: () => void;
+}
+
+export const IMenuService = createIdentifier<IMenuService>('univer.menu-service');
+
+export interface IMenuService {
+ addMenuItem(item: IMenuItem): IDisposable;
+ /** Get menu items at a given position. */
+ getMenuItems(position: MenuPosition): IMenuItem[];
+ getMenuItem(id: string): IMenuItem | null;
+}
+
+export class DesktopMenuService extends Disposable implements IMenuService {
+ private readonly _menuItemMap = new Map<string, IMenuItem>();
+
+ private readonly _menuByPositions = new Map<MenuPosition, Map<string, IMenuItem>>();
+
+ override dispose(): void {
+ this._menuItemMap.clear();
+ }
+
+ addMenuItem(item: IMenuItem): IDisposable {
+ if (this._menuItemMap.has(item.id)) {
+ throw new Error(`Menu item with the same id ${item.id} has already been added!`);
+ }
+
+ this._menuItemMap.set(item.id, item);
+ if (Array.isArray(item.menu)) {
+ item.menu.forEach((menu) => this.appendMenuToPosition(item, menu));
+ } else {
+ this.appendMenuToPosition(item, item.menu);
+ }
+
+ return toDisposable(() => {
+ this._menuItemMap.delete(item.id);
+ if (Array.isArray(item.menu)) {
+ item.menu.forEach((menu) => this._menuByPositions.get(menu)?.delete(item.id));
+ } else {
+ this._menuByPositions.get(item.menu)?.delete(item.id);
+ }
+ });
+ }
+
+ getMenuItems(positions: MenuPosition): IMenuItem[] {
+ if (this._menuByPositions.has(positions)) {
+ return [...this._menuByPositions.get(positions)!.values()];
+ }
+
+ return [] as IMenuItem[];
+ }
+
+ getMenuItem(id: string): IMenuItem | null {
+ if (this._menuItemMap.has(id)) {
+ return this._menuItemMap.get(id)!;
+ }
+
+ return null;
+ }
+
+ private appendMenuToPosition(menu: IMenuItem, position: MenuPosition) {
+ if (!this._menuByPositions.has(position)) {
+ this._menuByPositions.set(position, new Map<string, IMenuItem>());
+ }
+
+ const menuSet = this._menuByPositions.get(position)!;
+ if (menuSet.has(menu.id)) {
+ throw new Error(`Menu item with the same id ${menu.id} has already been added!`);
+ }
+
+ menuSet.set(menu.id, menu);
+ }
+}
\ No newline at end of file
diff --git a/packages/base-ui/src/services/platform/platform.service.ts b/packages/base-ui/src/services/platform/platform.service.ts
new file mode 100644
index 0000000000..afe860b307
--- /dev/null
+++ b/packages/base-ui/src/services/platform/platform.service.ts
@@ -0,0 +1,26 @@
+import { createIdentifier } from '@wendellhu/redi';
+
+/**
+ * A service to provide context info of the host service.
+ */
+export interface IPlatformService {
+ readonly isMac: boolean;
+ readonly isWindows: boolean;
+ readonly isLinux: boolean;
+}
+
+export const IPlatformService = createIdentifier<IPlatformService>('univer.platform-service');
+
+export class DesktopPlatformService implements IPlatformService {
+ get isMac(): boolean {
+ return /Mac/.test(navigator.appVersion);
+ }
+
+ get isWindows(): boolean {
+ return /Windows/.test(navigator.appVersion);
+ }
+
+ get isLinux(): boolean {
+ return /Linux/.test(navigator.appVersion);
+ }
+}
\ No newline at end of file
diff --git a/packages/base-ui/src/services/shortcut/keycode.ts b/packages/base-ui/src/services/shortcut/keycode.ts
new file mode 100644
index 0000000000..3974331a16
--- /dev/null
+++ b/packages/base-ui/src/services/shortcut/keycode.ts
@@ -0,0 +1,83 @@
+// Useful keyboard event inspection tool https://www.toptal.com/developers/keycode
+
+/** KeyCode that maps to browser standard keycode. */
+export const enum KeyCode {
+ UNKNOWN = 0,
+
+ BACKSPACE = 8,
+ DELETE = 12,
+ ENTER = 13,
+ TAB = 17,
+ ESC = 27,
+ SPACE = 32,
+ LEFT = 37,
+ UP = 38,
+ RIGHT = 39,
+ DOWN = 40,
+ INSERT = 45,
+
+ Digit0 = 48,
+ Digit1,
+ Digit2,
+ Digit3,
+ Digit4,
+ Digit5,
+ Digit6,
+ Digit7,
+ Digit8,
+ Digit9,
+
+ A = 65,
+ B,
+ C,
+ D,
+ E,
+ F,
+ G,
+ H,
+ I,
+ J,
+ K,
+ L,
+ M,
+ N,
+ O,
+ P,
+ Q,
+ R,
+ S,
+ T,
+ U,
+ V,
+ W,
+ X,
+ Y,
+ Z,
+
+ F1 = 112,
+ F2 = 113,
+ F3 = 114,
+ F4 = 115,
+ F5 = 116,
+ F6 = 117,
+ F7 = 118,
+ F8 = 119,
+ F9 = 120,
+ F10 = 121,
+ F11 = 122,
+ F12 = 123,
+ NUM_LOCK = 144,
+ SCROLL_LOCK = 145,
+
+ MINUS = 189,
+ EQUAL = 187,
+}
+
+export const enum MetaKeys {
+ SHIFT = 1 << 10,
+ /** Option key on MacOS. Alt key on other systems. */
+ ALT = 1 << 11,
+ /** Command key on MacOS. Ctrl key on other systems. */
+ CTRL_COMMAND = 1 << 12,
+ MAC_CTRL = 1 << 13,
+}
diff --git a/packages/base-ui/src/services/shortcut/shorcut.service.ts b/packages/base-ui/src/services/shortcut/shorcut.service.ts
new file mode 100644
index 0000000000..ab61d40bab
--- /dev/null
+++ b/packages/base-ui/src/services/shortcut/shorcut.service.ts
@@ -0,0 +1,118 @@
+import { Disposable, ICommandService, toDisposable } from '@univerjs/core';
+import { createIdentifier, IDisposable } from '@wendellhu/redi';
+
+import { fromDocumentEvent } from '../../Common/lifecycle';
+import { IPlatformService } from '../platform/platform.service';
+import { MetaKeys } from './keycode';
+
+export interface IShortcutItem {
+ /** This should reuse the corresponding command's id. */
+ id: string;
+
+ binding: number;
+
+ mac?: number;
+ win?: number;
+ linux?: number;
+}
+
+export interface IShortcutService {
+ registerShortcut(shortcut: IShortcutItem): IDisposable;
+
+ getCommandShortcut(id: string): string;
+}
+
+export const IShortcutService = createIdentifier<IShortcutService>('univer.shortcut');
+
+export class DesktopShortcutService extends Disposable implements IShortcutService {
+ // TODO: @wzhudev: this should be a linked list to resolve different shortcut mapping to the same keybinding
+
+ private readonly _shortCutMapping = new Map<number, IShortcutItem>();
+
+ constructor(@ICommandService private readonly _commandService: ICommandService, @IPlatformService private readonly _platformService: IPlatformService) {
+ super();
+
+ this.disposeWithMe(
+ fromDocumentEvent('keydown', (e: KeyboardEvent) => {
+ this.resolveMouseEvent(e);
+ })
+ );
+ }
+
+ registerShortcut(shortcut: IShortcutItem): IDisposable {
+ // first map shortcut to a number, so it could be converted and fetched quickly
+ const binding = this.getBindingFromItem(shortcut);
+ this._shortCutMapping.set(binding, shortcut);
+
+ return toDisposable(() => {
+ this._shortCutMapping.delete(binding);
+ });
+ }
+
+ getCommandShortcut(id: string): string {
+ return '';
+ }
+
+ private resolveMouseEvent(e: KeyboardEvent): void {
+ const shouldPreventDefault = this.dispatch(e);
+ if (shouldPreventDefault) {
+ e.preventDefault();
+ }
+ }
+
+ private dispatch(e: KeyboardEvent): boolean {
+ const binding = this.deriveBindingFromEvent(e);
+ if (binding === null) {
+ return false;
+ }
+
+ const shortcut = this._shortCutMapping.get(binding);
+ if (shortcut === undefined) {
+ return false;
+ }
+
+ this._commandService.executeCommand(shortcut.id);
+ return true;
+ }
+
+ private getBindingFromItem(item: IShortcutItem): number {
+ if (this._platformService.isMac && item.mac) {
+ return item.mac;
+ }
+
+ if (this._platformService.isWindows && item.win) {
+ return item.win;
+ }
+
+ if (this._platformService.isLinux && item.linux) {
+ return item.linux;
+ }
+
+ return item.binding;
+ }
+
+ private deriveBindingFromEvent(e: KeyboardEvent): number | null {
+ const { shiftKey, metaKey, altKey, keyCode } = e;
+
+ let binding = keyCode;
+
+ if (shiftKey) {
+ binding |= MetaKeys.SHIFT;
+ }
+
+ if (altKey) {
+ binding |= MetaKeys.ALT;
+ }
+
+ const ctrlKey = this._platformService.isMac ? metaKey : e.ctrlKey;
+ if (ctrlKey) {
+ binding |= MetaKeys.CTRL_COMMAND;
+ }
+
+ if (this._platformService.isMac && e.ctrlKey) {
+ binding |= MetaKeys.MAC_CTRL;
+ }
+
+ return binding;
+ }
+}
\ No newline at end of file
diff --git a/packages/core/package.json b/packages/core/package.json
index 390023c858..b90496ca35 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -60,7 +60,8 @@
"dayjs": "^1.11.5",
"es6-proxy-polyfill": "^2.1.1",
"nanoid": "4.0.0",
- "numeral": "^2.0.6"
+ "numeral": "^2.0.6",
+ "rxjs": "^7.8.1"
},
"devDependencies": {
"@types/jest": "^28.1.8",
diff --git a/packages/core/src/Basics/UniverObserverImpl.ts b/packages/core/src/Basics/UniverObserverImpl.ts
index 50c319a3e1..3642643445 100644
--- a/packages/core/src/Basics/UniverObserverImpl.ts
+++ b/packages/core/src/Basics/UniverObserverImpl.ts
@@ -1,31 +1,23 @@
-import { Observable, ObserverManager } from '../Observer';
-
-export class UniverObserverImpl {
- install(manager: ObserverManager) {
- // Event = > UIChange
- manager.addObserver('onUIChangeObservable', 'core', new Observable());
- manager.addObserver('onUIDidMountObservable', 'core', new Observable());
- manager.addObserver(
- 'onAfterChangeUISkinObservable',
- 'core',
- new Observable()
- );
- manager.addObserver(
- 'onAfterChangeUILocaleObservable',
- 'core',
- new Observable()
- );
- manager.addObserver('onViewComponentFocusChange', 'core', new Observable());
-
- // SheetBar
- manager.addObserver('onAddSheet', 'core', new Observable());
- manager.addObserver('onDeleteSheet', 'core', new Observable());
- manager.addObserver('onHideSheet', 'core', new Observable());
- manager.addObserver('onUnHideSheet', 'core', new Observable());
- manager.addObserver('onToLeftSheet', 'core', new Observable());
- manager.addObserver('onToRightSheet', 'core', new Observable());
- manager.addObserver('onCopySheet', 'core', new Observable());
- manager.addObserver('onRemoveSheet', 'core', new Observable());
- manager.addObserver('onSheetColor', 'core', new Observable());
- }
-}
+import { Observable, ObserverManager } from '../Observer';
+
+export class UniverObserverImpl {
+ install(manager: ObserverManager) {
+ // Event = > UIChange
+ manager.addObserver('onUIChangeObservable', 'core', new Observable());
+ manager.addObserver('onUIDidMountObservable', 'core', new Observable());
+ manager.addObserver('onAfterChangeUISkinObservable', 'core', new Observable());
+ manager.addObserver('onAfterChangeUILocaleObservable', 'core', new Observable());
+ manager.addObserver('onViewComponentFocusChange', 'core', new Observable());
+
+ // SheetBar
+ manager.addObserver('onAddSheet', 'core', new Observable());
+ manager.addObserver('onDeleteSheet', 'core', new Observable());
+ manager.addObserver('onHideSheet', 'core', new Observable());
+ manager.addObserver('onUnHideSheet', 'core', new Observable());
+ manager.addObserver('onToLeftSheet', 'core', new Observable());
+ manager.addObserver('onToRightSheet', 'core', new Observable());
+ manager.addObserver('onCopySheet', 'core', new Observable());
+ manager.addObserver('onRemoveSheet', 'core', new Observable());
+ manager.addObserver('onSheetColor', 'core', new Observable());
+ }
+}
\ No newline at end of file
diff --git a/packages/core/src/Observer/ObservableHooks.ts b/packages/core/src/Observer/ObservableHooks.ts
index 851a9a1cfe..043db24c4f 100644
--- a/packages/core/src/Observer/ObservableHooks.ts
+++ b/packages/core/src/Observer/ObservableHooks.ts
@@ -12,9 +12,7 @@ export class ObservableHooks<T> extends Observable<T> {
* @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
* @returns the new observer created for the callback
*/
- override add(
- callback: (eventData: T, eventState: EventState) => void
- ): Nullable<Observer<T>> {
+ override add(callback: (eventData: T, eventState: EventState) => void): Nullable<Observer<T>> {
if (!callback) {
return null;
}
@@ -36,4 +34,4 @@ export class ObservableHooks<T> extends Observable<T> {
override makeObserverBottomPriority() {
/** cancel * */
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/Service/Command/Command.service.ts b/packages/core/src/Service/Command/Command.service.ts
index f6b52bcdde..ae2997c804 100644
--- a/packages/core/src/Service/Command/Command.service.ts
+++ b/packages/core/src/Service/Command/Command.service.ts
@@ -165,7 +165,7 @@ export class CommandService implements ICommandService {
return [];
}
- // TODO: @wzhudev: it may be better to wrapp all undo & redos.
+ // TODO: @wzhudev: it may be better to wrap all undo & redos.
return Array.from(this._commandWillExecuteRegistry.get(id)!)
.map((interceptor) => interceptor(params))
.flat();
diff --git a/packages/core/src/Service/UndoRedo/undoRedo.service.ts b/packages/core/src/Service/UndoRedo/undoRedo.service.ts
index 27b64b3455..755a1b31c0 100644
--- a/packages/core/src/Service/UndoRedo/undoRedo.service.ts
+++ b/packages/core/src/Service/UndoRedo/undoRedo.service.ts
@@ -1,6 +1,7 @@
import { createIdentifier, IAccessor, IDisposable } from '@wendellhu/redi';
-import { Disposable } from '../../Shared/Lifecycle';
+import { BehaviorSubject, Observable } from 'rxjs';
+import { Disposable, toDisposable } from '../../Shared/Lifecycle';
import { CommandService, CommandType, ICommand, ICommandService } from '../Command/Command.service';
// TODO:: an undo redo element may be mergable to another undo redo element
@@ -14,6 +15,8 @@ interface IUndoRedoItem {
}
export interface IUndoRedoService {
+ undoRedoStatus$: Observable<IUndoRedoStatus>;
+
pushUndoRedo(item: IUndoRedoItem): void;
pitchTopUndoElement(): IUndoRedoItem | null;
@@ -25,10 +28,19 @@ export interface IUndoRedoService {
export const IUndoRedoService = createIdentifier<IUndoRedoService>('univer.undo-redo.service');
+export interface IUndoRedoStatus {
+ undos: number;
+ redos: number;
+}
+
/**
* This UndoRedoService is local.
*/
export class LocalUndoRedoService extends Disposable implements IUndoRedoService {
+ readonly undoRedoStatus$: Observable<IUndoRedoStatus>;
+
+ private readonly _undoRedoStatus$ = new BehaviorSubject<{ undos: number; redos: number }>({ undos: 0, redos: 0 });
+
private readonly _undoStack: IUndoRedoItem[] = [];
private readonly _redoStack: IUndoRedoItem[] = [];
@@ -36,8 +48,15 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
constructor(@ICommandService private readonly _commandService: CommandService) {
super();
+ this.undoRedoStatus$ = this._undoRedoStatus$.asObservable();
+
this.disposeWithMe(this._commandService.registerCommand(UndoCommand));
this.disposeWithMe(this._commandService.registerCommand(RedoCommand));
+ this.disposeWithMe(
+ toDisposable(() => {
+ this._undoRedoStatus$.complete();
+ })
+ );
}
pushUndoRedo(item: IUndoRedoItem): void {
@@ -50,6 +69,8 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
if (this._undoStack.length > 20) {
this._undoStack.splice(0, 1);
}
+
+ this.updateStatus();
}
pitchTopUndoElement(): IUndoRedoItem | null {
@@ -72,6 +93,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
const element = this._undoStack.pop();
if (element) {
this._redoStack.push(element);
+ this.updateStatus();
}
}
@@ -79,8 +101,16 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
const element = this._redoStack.pop();
if (element) {
this._undoStack.push(element);
+ this.updateStatus();
}
}
+
+ private updateStatus(): void {
+ this._undoRedoStatus$.next({
+ undos: this._undoStack.length,
+ redos: this._redoStack.length,
+ });
+ }
}
abstract class MultiImplementationCommand implements IDisposable {
@@ -135,4 +165,4 @@ export const RedoCommand = new (class extends MultiImplementationCommand impleme
return false;
}
-})();
+})();
\ No newline at end of file
diff --git a/packages/core/src/Service/log/log.service.ts b/packages/core/src/Service/log/log.service.ts
new file mode 100644
index 0000000000..9d45683ca0
--- /dev/null
+++ b/packages/core/src/Service/log/log.service.ts
@@ -0,0 +1,7 @@
+import { createIdentifier } from "@wendellhu/redi";
+
+export interface ILogService {
+
+}
+
+export const ILogService = createIdentifier<ILogService>('univer.log');
diff --git a/packages/base-ui/src/Services/Menu/menu.service.ts b/packages/core/src/Service/telementry/telementry.service.ts
similarity index 100%
rename from packages/base-ui/src/Services/Menu/menu.service.ts
rename to packages/core/src/Service/telementry/telementry.service.ts
diff --git a/packages/core/src/Types/Enum/index.ts b/packages/core/src/Types/Enum/index.ts
index 4eb7e451e7..b19f344a4c 100644
--- a/packages/core/src/Types/Enum/index.ts
+++ b/packages/core/src/Types/Enum/index.ts
@@ -10,7 +10,6 @@ export * from './Dimension';
export * from './Direction';
export * from './FormatType';
export * from './InterpolationPointType';
-export * from './KeyCode';
export * from './LocaleType';
export * from './ProtectionType';
export * from './RelativeDate';
@@ -18,4 +17,4 @@ export * from './SheetTypes';
export * from './TextStyle';
export * from './ThemeColorType';
export * from './ShapeType';
-// @endindex
+// @endindex
\ No newline at end of file
diff --git a/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts b/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts
index 8afe0d6047..cafc6ff004 100644
--- a/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts
+++ b/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts
@@ -1,186 +1,187 @@
-import { $$, ComponentManager, SlotManager, getRefElement } from '@univerjs/base-ui';
-import { KeyCode, ObserverManager } from '@univerjs/core';
-import { SheetContainerUIController } from '@univerjs/ui-plugin-sheets';
-import { Inject } from '@wendellhu/redi';
-import { FORMULA_PLUGIN_NAME, FunList } from '../Basics';
-import { HelpFunction, SearchFunction } from '../View/UI/FormulaPrompt';
-import { CellInputHandler } from './CellInputHandler';
-
-export class FormulaPromptController {
- cellInputHandler: CellInputHandler;
-
- richTextEle: HTMLElement;
-
- richTextEditEle: HTMLElement;
-
- private _searchFunction: SearchFunction;
-
- private _helpFunction: HelpFunction;
-
- constructor(
- @Inject(SheetContainerUIController) private readonly _sheetContainerUIController: SheetContainerUIController,
- @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
- @Inject(ComponentManager) private _componentManager: ComponentManager,
- @Inject(SlotManager) private readonly _slotManager: SlotManager
- ) {
- this._initialize();
- }
-
- getSearchComponent(ref: SearchFunction) {
- this._searchFunction = ref;
- }
-
- getHelpComponent(ref: HelpFunction) {
- this._helpFunction = ref;
- }
-
- private _initialize() {
- this._initRegisterComponent();
- this._mount();
- this._onRichTextKeyDownObservable();
- this._onRichTextKeyUpObservable();
- }
-
- private _initRegisterComponent() {
- this._componentManager.register(SearchFunction.name, SearchFunction);
- this._slotManager.setSlotComponent('main', {
- name: FORMULA_PLUGIN_NAME + SearchFunction.name,
- component: {
- name: SearchFunction.name,
- props: {
- getComponent: this.getSearchComponent.bind(this),
- },
- },
- });
- this._componentManager.register(HelpFunction.name, HelpFunction);
- this._slotManager.setSlotComponent('main', {
- name: FORMULA_PLUGIN_NAME + HelpFunction.name,
- component: {
- name: HelpFunction.name,
- props: {
- getComponent: this.getHelpComponent.bind(this),
- },
- },
- });
- }
-
- private _mount() {
- this._sheetContainerUIController.UIDidMount(() => {
- const richTextEle = this._sheetContainerUIController.getCellEditorUIController()._richTextEle;
-
- this.richTextEle = richTextEle;
- this.richTextEditEle = $$('div', this.richTextEle);
-
- // Register cell input formula support
- this.cellInputHandler = new CellInputHandler(this.richTextEditEle);
- });
- }
-
- private _onRichTextKeyDownObservable() {
- this._observerManager.getObserver<KeyboardEvent>('onRichTextKeyDownObservable')?.add((event: KeyboardEvent) => {
- const ctrlKey = event.ctrlKey;
- const altKey = event.altKey;
- const shiftKey = event.shiftKey;
- const kcode = event.keyCode;
- if (
- !(
- (kcode >= 112 && kcode <= 123) ||
- kcode <= 46 ||
- kcode === 144 ||
- kcode === 108 ||
- event.ctrlKey ||
- event.altKey ||
- (event.shiftKey && (kcode === 37 || kcode === 38 || kcode === 39 || kcode === 40 || kcode === KeyCode.WIN || kcode === KeyCode.WIN_R || kcode === KeyCode.MENU))
- ) ||
- kcode === 8 ||
- kcode === 32 ||
- kcode === 46 ||
- (event.ctrlKey && kcode === 86)
- ) {
- // handle input
- this.cellInputHandler.functionInputHandler(this.richTextEditEle, kcode);
- }
- });
- }
-
- private _onRichTextKeyUpObservable() {
- this._observerManager.getObserver<KeyboardEvent>('onRichTextKeyUpObservable')?.add((event: KeyboardEvent) => {
- const kcode = event.keyCode;
- if (kcode === KeyCode.ENTER) {
- this._searchFunction.updateState(false);
- this._helpFunction.updateState(false);
- } else if (
- !(
- (kcode >= 112 && kcode <= 123) ||
- kcode <= 46 ||
- kcode === 144 ||
- kcode === 108 ||
- event.ctrlKey ||
- event.altKey ||
- (event.shiftKey && (kcode === 37 || kcode === 38 || kcode === 39 || kcode === 40 || kcode === KeyCode.WIN || kcode === KeyCode.WIN_R || kcode === KeyCode.MENU))
- ) ||
- kcode === 8 ||
- kcode === 32 ||
- kcode === 46 ||
- (event.ctrlKey && kcode === 86)
- ) {
- this.cellInputHandler.searchFunction(this.richTextEditEle);
- const formula = this.cellInputHandler.getFormula();
- const helpFormula = this.cellInputHandler.getHelpFormula();
- const height = parseInt(this.richTextEle.style.minHeight);
- const width = parseInt(this.richTextEle.style.minWidth);
- let left = parseInt(this.richTextEle.style.left);
- let top = parseInt(this.richTextEle.style.top) + height;
- const sheetContainer = getRefElement(this._sheetContainerUIController.getContentRef());
- const screenW = sheetContainer.offsetWidth;
- const screenH = sheetContainer.offsetHeight;
- const position = { left, top };
- const getPosition = (component: SearchFunction | HelpFunction) => {
- const searchFunctionEle = getRefElement(component.getContentRef());
- const rootW = searchFunctionEle.offsetWidth;
- const rootH = searchFunctionEle.offsetHeight;
- const right = screenW - left > rootW;
- const bottom = screenH - top > rootH;
- if (!right) {
- left -= rootW - width;
- }
- if (!bottom) {
- top -= rootH + height;
- }
- return { left, top };
- };
-
- if (formula[0]) {
- this._searchFunction.updateState(true, formula, 0, position, () => {
- const position = getPosition(this._searchFunction);
- this._searchFunction.updateState(true, formula, 0, position);
- });
- this._helpFunction.updateState(false);
- } else if (helpFormula[0]) {
- const functionName = (helpFormula[0] as string).toUpperCase();
- const functionInfo = FunList.find((item: any) => item.n === functionName) || {};
- this._helpFunction.updateState(true, helpFormula[1] as number, functionInfo, position, () => {
- const position = getPosition(this._helpFunction);
- this._helpFunction.updateState(true, helpFormula[1] as number, functionInfo, position);
- });
- this._searchFunction.updateState(false);
- } else {
- this._searchFunction.updateState(false, formula);
- this._helpFunction.updateState(false);
- }
- }
- const value = this.cellInputHandler.getInputValue();
- if (value.length > 0 && value.substr(0, 1) === '=' && (kcode !== 229 || value.length === 1)) {
- if (kcode === 13) {
- event.preventDefault();
- event.stopPropagation();
- const searchFunctionState = this._searchFunction.getState();
- if (searchFunctionState.searchActive) {
- const func = searchFunctionState.formula[searchFunctionState.selectIndex] as any;
- this.cellInputHandler.searchFunctionEnter(func.n);
- }
- }
- }
- });
- }
-}
+import { $$, ComponentManager, SlotManager, getRefElement } from '@univerjs/base-ui';
+import { ObserverManager } from '@univerjs/core';
+import { SheetContainerUIController } from '@univerjs/ui-plugin-sheets';
+import { Inject } from '@wendellhu/redi';
+import { FORMULA_PLUGIN_NAME, FunList } from '../Basics';
+import { HelpFunction, SearchFunction } from '../View/UI/FormulaPrompt';
+import { CellInputHandler } from './CellInputHandler';
+import { KeyCode } from './keyCode';
+
+export class FormulaPromptController {
+ cellInputHandler: CellInputHandler;
+
+ richTextEle: HTMLElement;
+
+ richTextEditEle: HTMLElement;
+
+ private _searchFunction: SearchFunction;
+
+ private _helpFunction: HelpFunction;
+
+ constructor(
+ @Inject(SheetContainerUIController) private readonly _sheetContainerUIController: SheetContainerUIController,
+ @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
+ @Inject(ComponentManager) private _componentManager: ComponentManager,
+ @Inject(SlotManager) private readonly _slotManager: SlotManager
+ ) {
+ this._initialize();
+ }
+
+ getSearchComponent(ref: SearchFunction) {
+ this._searchFunction = ref;
+ }
+
+ getHelpComponent(ref: HelpFunction) {
+ this._helpFunction = ref;
+ }
+
+ private _initialize() {
+ this._initRegisterComponent();
+ this._mount();
+ this._onRichTextKeyDownObservable();
+ this._onRichTextKeyUpObservable();
+ }
+
+ private _initRegisterComponent() {
+ this._componentManager.register(SearchFunction.name, SearchFunction);
+ this._slotManager.setSlotComponent('main', {
+ name: FORMULA_PLUGIN_NAME + SearchFunction.name,
+ component: {
+ name: SearchFunction.name,
+ props: {
+ getComponent: this.getSearchComponent.bind(this),
+ },
+ },
+ });
+ this._componentManager.register(HelpFunction.name, HelpFunction);
+ this._slotManager.setSlotComponent('main', {
+ name: FORMULA_PLUGIN_NAME + HelpFunction.name,
+ component: {
+ name: HelpFunction.name,
+ props: {
+ getComponent: this.getHelpComponent.bind(this),
+ },
+ },
+ });
+ }
+
+ private _mount() {
+ this._sheetContainerUIController.UIDidMount(() => {
+ const richTextEle = this._sheetContainerUIController.getCellEditorUIController()._richTextEle;
+
+ this.richTextEle = richTextEle;
+ this.richTextEditEle = $$('div', this.richTextEle);
+
+ // Register cell input formula support
+ this.cellInputHandler = new CellInputHandler(this.richTextEditEle);
+ });
+ }
+
+ private _onRichTextKeyDownObservable() {
+ this._observerManager.getObserver<KeyboardEvent>('onRichTextKeyDownObservable')?.add((event: KeyboardEvent) => {
+ const ctrlKey = event.ctrlKey;
+ const altKey = event.altKey;
+ const shiftKey = event.shiftKey;
+ const kcode = event.keyCode;
+ if (
+ !(
+ (kcode >= 112 && kcode <= 123) ||
+ kcode <= 46 ||
+ kcode === 144 ||
+ kcode === 108 ||
+ event.ctrlKey ||
+ event.altKey ||
+ (event.shiftKey && (kcode === 37 || kcode === 38 || kcode === 39 || kcode === 40 || kcode === KeyCode.WIN || kcode === KeyCode.WIN_R || kcode === KeyCode.MENU))
+ ) ||
+ kcode === 8 ||
+ kcode === 32 ||
+ kcode === 46 ||
+ (event.ctrlKey && kcode === 86)
+ ) {
+ // handle input
+ this.cellInputHandler.functionInputHandler(this.richTextEditEle, kcode);
+ }
+ });
+ }
+
+ private _onRichTextKeyUpObservable() {
+ this._observerManager.getObserver<KeyboardEvent>('onRichTextKeyUpObservable')?.add((event: KeyboardEvent) => {
+ const kcode = event.keyCode;
+ if (kcode === KeyCode.ENTER) {
+ this._searchFunction.updateState(false);
+ this._helpFunction.updateState(false);
+ } else if (
+ !(
+ (kcode >= 112 && kcode <= 123) ||
+ kcode <= 46 ||
+ kcode === 144 ||
+ kcode === 108 ||
+ event.ctrlKey ||
+ event.altKey ||
+ (event.shiftKey && (kcode === 37 || kcode === 38 || kcode === 39 || kcode === 40 || kcode === KeyCode.WIN || kcode === KeyCode.WIN_R || kcode === KeyCode.MENU))
+ ) ||
+ kcode === 8 ||
+ kcode === 32 ||
+ kcode === 46 ||
+ (event.ctrlKey && kcode === 86)
+ ) {
+ this.cellInputHandler.searchFunction(this.richTextEditEle);
+ const formula = this.cellInputHandler.getFormula();
+ const helpFormula = this.cellInputHandler.getHelpFormula();
+ const height = parseInt(this.richTextEle.style.minHeight);
+ const width = parseInt(this.richTextEle.style.minWidth);
+ let left = parseInt(this.richTextEle.style.left);
+ let top = parseInt(this.richTextEle.style.top) + height;
+ const sheetContainer = getRefElement(this._sheetContainerUIController.getContentRef());
+ const screenW = sheetContainer.offsetWidth;
+ const screenH = sheetContainer.offsetHeight;
+ const position = { left, top };
+ const getPosition = (component: SearchFunction | HelpFunction) => {
+ const searchFunctionEle = getRefElement(component.getContentRef());
+ const rootW = searchFunctionEle.offsetWidth;
+ const rootH = searchFunctionEle.offsetHeight;
+ const right = screenW - left > rootW;
+ const bottom = screenH - top > rootH;
+ if (!right) {
+ left -= rootW - width;
+ }
+ if (!bottom) {
+ top -= rootH + height;
+ }
+ return { left, top };
+ };
+
+ if (formula[0]) {
+ this._searchFunction.updateState(true, formula, 0, position, () => {
+ const position = getPosition(this._searchFunction);
+ this._searchFunction.updateState(true, formula, 0, position);
+ });
+ this._helpFunction.updateState(false);
+ } else if (helpFormula[0]) {
+ const functionName = (helpFormula[0] as string).toUpperCase();
+ const functionInfo = FunList.find((item: any) => item.n === functionName) || {};
+ this._helpFunction.updateState(true, helpFormula[1] as number, functionInfo, position, () => {
+ const position = getPosition(this._helpFunction);
+ this._helpFunction.updateState(true, helpFormula[1] as number, functionInfo, position);
+ });
+ this._searchFunction.updateState(false);
+ } else {
+ this._searchFunction.updateState(false, formula);
+ this._helpFunction.updateState(false);
+ }
+ }
+ const value = this.cellInputHandler.getInputValue();
+ if (value.length > 0 && value.substr(0, 1) === '=' && (kcode !== 229 || value.length === 1)) {
+ if (kcode === 13) {
+ event.preventDefault();
+ event.stopPropagation();
+ const searchFunctionState = this._searchFunction.getState();
+ if (searchFunctionState.searchActive) {
+ const func = searchFunctionState.formula[searchFunctionState.selectIndex] as any;
+ this.cellInputHandler.searchFunctionEnter(func.n);
+ }
+ }
+ }
+ });
+ }
+}
diff --git a/packages/core/src/Types/Enum/KeyCode.ts b/packages/sheets-plugin-formula/src/Controller/keyCode.ts
similarity index 100%
rename from packages/core/src/Types/Enum/KeyCode.ts
rename to packages/sheets-plugin-formula/src/Controller/keyCode.ts
diff --git a/packages/sheets-plugin-image/package.json b/packages/sheets-plugin-image/package.json
index 712d185dcc..1a8dc236be 100644
--- a/packages/sheets-plugin-image/package.json
+++ b/packages/sheets-plugin-image/package.json
@@ -63,7 +63,7 @@
"@univerjs/common-plugin-data": "workspace:^0.0.1",
"@univerjs/ui-plugin-sheets": "workspace:^0.0.1",
"@univerjs/core": "workspace:^0.0.1",
- "@wendellhu/redi": "^0.10.0",
+ "@wendellhu/redi": "^0.12.6",
"preact": "^10.12.1"
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/package.json b/packages/ui-plugin-sheets/package.json
index 0059500fa5..f445390c81 100644
--- a/packages/ui-plugin-sheets/package.json
+++ b/packages/ui-plugin-sheets/package.json
@@ -64,6 +64,7 @@
"@univerjs/core": "workspace:^0.0.1",
"@wendellhu/redi": "^0.12.6",
"css-vars-ponyfill": "^2.4.6",
- "preact": "^10.12.1"
+ "preact": "^10.12.1",
+ "rxjs": "^7.8.1"
}
}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts b/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts
index a2a90a837e..bacdace6c5 100644
--- a/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts
@@ -1,6 +1,6 @@
-import { Inject, SkipSelf } from '@wendellhu/redi';
+import { Inject, Injector, SkipSelf } from '@wendellhu/redi';
import { BorderInfo, ISelectionManager, SelectionManager } from '@univerjs/base-sheets';
-import { BaseSelectChildrenProps, BaseSelectProps, ColorPicker, ComponentChildren, ComponentManager, CustomComponent } from '@univerjs/base-ui';
+import { BaseSelectChildrenProps, BaseSelectProps, ColorPicker, ComponentChildren, ComponentManager, CustomComponent, IMenuService, MenuPosition } from '@univerjs/base-ui';
import {
BorderType,
CommandManager,
@@ -19,6 +19,7 @@ import {
ITextRotation,
ICurrentUniverService,
ObserverManager,
+ Disposable,
} from '@univerjs/core';
import { DefaultToolbarConfig, SheetToolbarConfig, SHEET_UI_PLUGIN_NAME } from '../Basics';
import { ColorSelect, LineBold, LineColor, Toolbar } from '../View';
@@ -35,6 +36,7 @@ import {
} from '../View/Toolbar/Const';
import styles from '../View/Toolbar/index.module.less';
+import { RedoMenuItemFactory, UndoMenuItemFactory } from './menu';
export interface BaseToolbarSelectProps extends BaseSelectProps {
children?: BaseSelectChildrenProps[];
@@ -55,9 +57,12 @@ export interface IToolbarItemProps extends BaseToolbarSelectProps {
suffix?: ComponentChildren;
}
-export class ToolbarUIController {
+export class ToolbarUIController extends Disposable {
private _toolbar: Toolbar;
+ /**
+ * @deprecated
+ */
private _toolList: IToolbarItemProps[];
private _config: SheetToolbarConfig;
@@ -83,42 +88,19 @@ export class ToolbarUIController {
// eslint-disable-next-line max-lines-per-function
constructor(
config: SheetToolbarConfig | undefined,
+ @Inject(Injector) private readonly _injector: Injector,
@ISelectionManager private readonly _selectionManager: SelectionManager,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager,
- @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
- @Inject(ComponentManager) private readonly _componentManager: ComponentManager
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @IMenuService private readonly _menuService: IMenuService
) {
+ super();
+
this._config = Tools.deepMerge({}, DefaultToolbarConfig, config);
// TODO: @wzhudev: toolbar configurations should be moved to command system
this._toolList = [
- {
- toolbarType: 1,
- tooltip: 'toolbar.undo',
- name: 'undo',
- label: {
- name: 'ForwardIcon',
- },
- show: this._config.undo,
- onClick: () => {
- this.setUndo();
- this.hideTooltip();
- },
- },
- {
- toolbarType: 1,
- tooltip: 'toolbar.redo',
- label: {
- name: 'BackIcon',
- },
- name: 'redo',
- show: this._config.redo,
- onClick: () => {
- this.setRedo();
- this.hideTooltip();
- },
- },
{
type: 0,
tooltip: 'toolbar.font',
@@ -454,10 +436,15 @@ export class ToolbarUIController {
// 获取Toolbar组件
getComponent = (ref: Toolbar) => {
this._toolbar = ref;
+
+ this._initializeToolbar();
this.setToolbar();
};
// 增加toolbar配置
+ /**
+ * @deprecated
+ */
addToolbarConfig(config: IToolbarItemProps) {
const index = this._toolList.findIndex((item) => item.name === config.name);
if (index > -1) return;
@@ -465,6 +452,9 @@ export class ToolbarUIController {
}
// 删除toolbar配置
+ /**
+ * @deprecated
+ */
deleteToolbarConfig(name: string) {
const index = this._toolList.findIndex((item) => item.name === name);
if (index > -1) {
@@ -472,9 +462,10 @@ export class ToolbarUIController {
}
}
- // 刷新toolbar
+ // 刷新 toolbar 数据从 controller 层移动到 view 层
setToolbar() {
this._toolbar?.setToolbar(this._toolList);
+ this._toolbar?.setToolbarNeo(this._menuService.getMenuItems(MenuPosition.TOOLBAR));
}
setUIObserve<T>(msg: UIObserver<T>) {
@@ -731,6 +722,12 @@ export class ToolbarUIController {
}
}
+ private _initializeToolbar(): void {
+ [UndoMenuItemFactory, RedoMenuItemFactory].forEach((factory) => {
+ this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
+ });
+ }
+
private _initialize() {
const componentManager = this._componentManager;
componentManager.register(SHEET_UI_PLUGIN_NAME + ColorSelect.name, ColorSelect);
diff --git a/packages/ui-plugin-sheets/src/Controller/menu.ts b/packages/ui-plugin-sheets/src/Controller/menu.ts
new file mode 100644
index 0000000000..b3857cdd2a
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/Controller/menu.ts
@@ -0,0 +1,32 @@
+import { IMenuItem, MenuPosition } from '@univerjs/base-ui';
+import { IUndoRedoService, RedoCommand, UndoCommand } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { map } from 'rxjs/operators';
+
+export function UndoMenuItemFactory(accessor: IAccessor): IMenuItem {
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ return {
+ id: UndoCommand.id,
+ icon: 'ForwardIcon',
+ title: 'Undo',
+ menu: [MenuPosition.TOOLBAR, MenuPosition.CONTEXT_MENU],
+ disabled$: undoRedoService.undoRedoStatus$.pipe(map((v) => v.undos <= 0)),
+ };
+}
+
+export function RedoMenuItemFactory(accessor: IAccessor): IMenuItem {
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ return {
+ id: RedoCommand.id,
+ icon: 'BackIcon',
+ title: 'Redo',
+ menu: [MenuPosition.TOOLBAR],
+ disabled$: undoRedoService.undoRedoStatus$.pipe(map((v) => v.redos <= 0)),
+ }
+}
+
+// export function FontSelectorMenuItemFactory(accessor: IAccessor): IMenuItem {
+//
+// }
diff --git a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts b/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
index a4974b77d5..123afb7151 100644
--- a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
+++ b/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
@@ -1,6 +1,22 @@
-import { Inject, Injector } from '@wendellhu/redi';
-import { Plugin, Tools, Univer, PluginType, LocaleService } from '@univerjs/core';
-import { ComponentManager, getRefElement, RegisterManager, KeyboardManager, SlotComponent, ZIndexManager, SlotManager, DragManager } from '@univerjs/base-ui';
+import { Dependency, Inject, Injector } from '@wendellhu/redi';
+import { Plugin, Tools, PluginType, LocaleService, IUndoRedoService } from '@univerjs/core';
+import {
+ ComponentManager,
+ getRefElement,
+ RegisterManager,
+ KeyboardManager,
+ SlotComponent,
+ ZIndexManager,
+ SlotManager,
+ DragManager,
+ IShortcutService,
+ DesktopShortcutService,
+ SharedController,
+ IPlatformService,
+ DesktopPlatformService,
+ IMenuService,
+ DesktopMenuService,
+} from '@univerjs/base-ui';
import { IRenderingEngine } from '@univerjs/base-render';
import { DefaultSheetUIConfig, installObserver, ISheetUIPluginConfig, SheetUIPluginObserve, SHEET_UI_PLUGIN_NAME } from './Basics';
import { AppUIController } from './Controller/AppUIController';
@@ -32,12 +48,9 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
this._config = Tools.deepMerge({}, DefaultSheetUIConfig, config);
}
- installTo(univerInstance: Univer) {
- univerInstance.install(this);
- }
-
initialize(): void {
installObserver(this);
+
/**
* load more Locale object
*
@@ -151,14 +164,20 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
}
private initializeDependencies(): void {
- this._injector.add([DragManager]);
- this._injector.add([KeyboardManager]);
- this._injector.add([RegisterManager]);
- this._injector.add([ComponentManager]);
- this._injector.add([ZIndexManager]);
- this._injector.add([SlotManager]);
-
- // TODO: maybe we don't have to instantiate these dependencies manually
+ const dependencies: Dependency[] = [
+ [DragManager],
+ [KeyboardManager],
+ [RegisterManager],
+ [ComponentManager],
+ [ZIndexManager],
+ [SlotManager],
+ [IShortcutService, { useClass: DesktopShortcutService }],
+ [IPlatformService, { useClass: DesktopPlatformService }],
+ [SharedController],
+ [IMenuService, { useClass: DesktopMenuService }],
+ ];
+ dependencies.forEach((d) => this._injector.add(d));
+
this._dragManager = this._injector.get(DragManager);
this._componentManager = this._injector.get(ComponentManager);
this._keyboardManager = this._injector.get(KeyboardManager);
@@ -167,5 +186,8 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
this._appUIController = this._injector.createInstance(AppUIController, this._config);
this._injector.add([AppUIController, { useValue: this._appUIController }]);
+
+ this._injector.get(IUndoRedoService);
+ this._injector.get(SharedController);
}
-}
\ No newline at end of file
+}
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx b/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx
index 8f4942f809..b16f3fa939 100644
--- a/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx
+++ b/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx
@@ -1,7 +1,7 @@
-import { AppContext, AppContextValues, BaseComponentProps, Button, Component, Container, createRef, debounce, PreactContext, Select, Tooltip } from '@univerjs/base-ui';
+import { AppContext, AppContextValues, BaseComponentProps, Button, Component, Container, createRef, debounce, IMenuItem, PreactContext, Select, Tooltip } from '@univerjs/base-ui';
import { IToolbarItemProps, SheetContainerUIController } from '../../Controller';
import styles from './index.module.less';
-import { AppUIController } from '../../Controller/AppUIController';
+import { ToolbarItem } from './ToolbarItem';
interface IProps extends BaseComponentProps {
style?: JSX.CSSProperties;
@@ -14,6 +14,7 @@ interface IState {
defaultToolList: IToolbarItemProps[];
showMore: boolean;
toolbarListWidths: number[];
+ menuItems: IMenuItem[];
}
export class Toolbar extends Component<IProps, IState> {
@@ -44,6 +45,7 @@ export class Toolbar extends Component<IProps, IState> {
defaultToolList: [],
moreToolList: [],
toolbarListWidths: [],
+ menuItems: [],
};
}
@@ -53,7 +55,7 @@ export class Toolbar extends Component<IProps, IState> {
* TODO : 点击其他地方需要隐藏more buttons
*/
showMore = () => {
- let showMore = this.state.showMore;
+ const showMore = this.state.showMore;
this.setState({ showMore: !showMore });
if (!showMore) {
@@ -142,6 +144,18 @@ export class Toolbar extends Component<IProps, IState> {
}
};
+ setToolbarNeo = (menuItems: IMenuItem[]) => {
+ this.setState(
+ {
+ menuItems,
+ },
+ () => {
+ this.setToolbarListWidth();
+ }
+ );
+ };
+
+ /** @deprecated */
setToolbar = (toolList: any[]) => {
this.setState(
{
@@ -164,7 +178,7 @@ export class Toolbar extends Component<IProps, IState> {
};
override componentDidMount() {
- this.props.getComponent?.(this);
+ this.props.getComponent?.(this); // pass the UI to the controller, which is not good...
window.addEventListener('resize', this.debounceSetToolbarListWidth);
}
@@ -172,8 +186,15 @@ export class Toolbar extends Component<IProps, IState> {
window.removeEventListener('resize', this.debounceSetToolbarListWidth);
}
- // 渲染dom
- getToolbarList(list: IToolbarItemProps[]) {
+ neoRenderToolbarList() {
+ return this.state.menuItems.map((item) => <ToolbarItem key={item.id} {...item} />);
+ }
+
+ // 渲染 dom
+ /**
+ * @deprecated
+ */
+ renderToolbarList(list: IToolbarItemProps[]) {
return list.map((item) => {
if (item.toolbarType) {
if (item.show) {
@@ -215,7 +236,8 @@ export class Toolbar extends Component<IProps, IState> {
return (
<Container style={{ position: 'relative' }}>
<div className={`${styles.toolbarWarp} ${styles.toolbar}`} ref={this.toolbarRef}>
- {this.getToolbarList(defaultToolList)}
+ {this.neoRenderToolbarList()}
+ {this.renderToolbarList(defaultToolList)}
<div ref={this.moreBtnRef} className={styles.moreButton} style={{ visibility: moreToolList.length ? 'visible' : 'hidden' }}>
<Tooltip title={'toolbar.toolMoreTip'} placement={'bottom'}>
@@ -226,9 +248,10 @@ export class Toolbar extends Component<IProps, IState> {
</div>
</div>
+ {/* FIXME: moreToolList will become unnecessary after we implemented new architecture. */}
{moreToolList.length ? (
<div style={{ visibility: showMore ? 'visible' : 'hidden' }} className={`${styles.moreTool} ${styles.toolbar}`} ref={this.moreToolRef}>
- {this.getToolbarList(moreToolList)}
+ {this.renderToolbarList(moreToolList)}
</div>
) : (
''
@@ -236,4 +259,4 @@ export class Toolbar extends Component<IProps, IState> {
</Container>
);
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx b/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
new file mode 100644
index 0000000000..ca6e721924
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
@@ -0,0 +1,64 @@
+import { ComponentChild, ComponentChildren, isValidElement } from 'preact';
+import { Subscription } from 'rxjs';
+
+import { IMenuItem, Button, Tooltip, Component, CustomComponent } from '@univerjs/base-ui';
+import { ICommandService } from '@univerjs/core';
+
+import styles from './index.module.less';
+
+export interface IToolbarItemStatus {
+ disabled: boolean;
+}
+
+export class ToolbarItem extends Component<IMenuItem, IToolbarItemStatus> {
+ private disabledSubscription: Subscription | undefined;
+
+ constructor() {
+ super();
+
+ this.state = {
+ disabled: true,
+ };
+ }
+
+ override componentDidMount() {
+ this.disabledSubscription = this.props.disabled$?.subscribe((disabled) => {
+ this.setState({ disabled });
+ });
+ }
+
+ override componentWillMount() {
+ this.disabledSubscription?.unsubscribe();
+ }
+
+ render(): ComponentChild {
+ const { props, context } = this;
+ const commandService: ICommandService = context.injector.get(ICommandService);
+ const { disabled } = this.state;
+
+ return (
+ <Tooltip title={props.title} placement="bottom">
+ <Button className={styles.textButton} type="text" disabled={disabled} onClick={() => commandService.executeCommand(props.id)}>
+ {this.getLabel({ name: props.icon })}
+ </Button>
+ </Tooltip>
+ );
+ }
+
+ override getLabel(label: string | CustomComponent | ComponentChildren) {
+ if (typeof label === 'string') {
+ return this.getLocale(label);
+ }
+ if (isValidElement(label)) {
+ return label;
+ }
+ if (label) {
+ const Label = this.context.componentManager.get((label as CustomComponent).name);
+ if (Label) {
+ const props = (label as CustomComponent).props ?? {};
+ return <Label {...props}></Label>;
+ }
+ }
+ return null;
+ }
+}
\ No newline at end of file