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.

feat: implement shortcut panel (#529)

Wenzhao Hu0df769c84585
diff --git a/packages/base-ui/src/Common/index.ts b/packages/base-ui/src/Common/index.ts
deleted file mode 100644
index 932bb4dee0..0000000000
--- a/packages/base-ui/src/Common/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from './ComponentManager';
-export * from './ZIndexManager';
diff --git a/packages/base-ui/src/base-ui-plugin.ts b/packages/base-ui/src/base-ui-plugin.ts
index de57ad7a03..63a1a3ab1e 100644
--- a/packages/base-ui/src/base-ui-plugin.ts
+++ b/packages/base-ui/src/base-ui-plugin.ts
@@ -1,10 +1,11 @@
import { ILocalStorageService, LocaleService, Plugin, PLUGIN_NAMES, PluginType } from '@univerjs/core';
import { Dependency, Inject, Injector } from '@wendellhu/redi';
-import { ComponentManager } from './Common/ComponentManager';
-import { ZIndexManager } from './Common/ZIndexManager';
+import { ComponentManager } from './common/component-manager';
+import { ZIndexManager } from './common/z-index-manager';
import { ErrorController } from './controllers/error/error.controller';
import { SharedController } from './controllers/shared-shortcut.controller';
+import { ShortcutPanelController } from './controllers/shortcut-display/shortcut-panel.controller';
import { IUIController, IWorkbenchOptions } from './controllers/ui/ui.controller';
import { DesktopUIController } from './controllers/ui/ui-desktop.controller';
import { enUS } from './locale';
@@ -25,6 +26,7 @@ import { INotificationService } from './services/notification/notification.servi
import { DesktopPlatformService, IPlatformService } from './services/platform/platform.service';
import { DesktopShortcutService, IShortcutService } from './services/shortcut/shortcut.service';
import { ShortcutExperienceService } from './services/shortcut/shortcut-experience.service';
+import { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';
import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';
import { ISidebarService } from './services/sidebar/sidebar.service';
@@ -67,8 +69,10 @@ export class UIPlugin extends Plugin {
// legacy managers - deprecated
[ComponentManager],
[ZIndexManager],
+
// services
[ShortcutExperienceService],
+ [ShortcutPanelService],
[IShortcutService, { useClass: DesktopShortcutService }],
[IPlatformService, { useClass: DesktopPlatformService }],
[IMenuService, { useClass: DesktopMenuService }],
@@ -81,11 +85,13 @@ export class UIPlugin extends Plugin {
[IMessageService, { useClass: DesktopMessageService, lazy: true }],
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
+
// controllers
[IFocusService, { useClass: DesktopFocusService }],
[IUIController, { useClass: DesktopUIController }],
[SharedController],
[ErrorController],
+ [ShortcutPanelController],
];
dependencies.forEach((dependency) => injector.add(dependency));
diff --git a/packages/base-ui/src/commands/operations/toggle-shortcut-panel.operation.ts b/packages/base-ui/src/commands/operations/toggle-shortcut-panel.operation.ts
new file mode 100644
index 0000000000..e4578475cd
--- /dev/null
+++ b/packages/base-ui/src/commands/operations/toggle-shortcut-panel.operation.ts
@@ -0,0 +1,31 @@
+import { CommandType, IOperation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import { ShortcutPanelService } from '../../services/shortcut/shortcut-panel.service';
+import { ISidebarService } from '../../services/sidebar/sidebar.service';
+
+export const ShortcutPanelComponentName = 'ShortcutPanel';
+
+export const ToggleShortcutPanelOperation: IOperation = {
+ id: 'base-ui.operation.toggle-shortcut-panel',
+ type: CommandType.OPERATION,
+ handler: (accessor: IAccessor) => {
+ const shortcutPanelStatusService = accessor.get(ShortcutPanelService);
+ const sidebarService = accessor.get(ISidebarService);
+
+ const isOpen = shortcutPanelStatusService.isOpen;
+
+ if (isOpen) {
+ shortcutPanelStatusService.close();
+ sidebarService.close();
+ } else {
+ shortcutPanelStatusService.open();
+ sidebarService.open({
+ header: { title: 'shortcut-panel.title' },
+ children: { label: ShortcutPanelComponentName },
+ });
+ }
+
+ return true;
+ },
+};
diff --git a/packages/base-ui/src/Common/ComponentManager.ts b/packages/base-ui/src/common/component-manager.ts
similarity index 89%
rename from packages/base-ui/src/Common/ComponentManager.ts
rename to packages/base-ui/src/common/component-manager.ts
index f68d9951aa..66044b587b 100644
--- a/packages/base-ui/src/Common/ComponentManager.ts
+++ b/packages/base-ui/src/common/component-manager.ts
@@ -1,3 +1,4 @@
+import { toDisposable } from '@univerjs/core';
import {
AdjustHeight,
AdjustWidth,
@@ -65,6 +66,7 @@ import {
VerticalIntegrationSingle,
VerticalTextSingle,
} from '@univerjs/icons';
+import { IDisposable } from '@wendellhu/redi';
export interface ICustomComponent {
name: string;
@@ -74,7 +76,7 @@ export interface ICustomComponent {
export type ComponentList = Map<string, React.ForwardRefExoticComponent<any>>;
export class ComponentManager {
- private _componentList: ComponentList = new Map();
+ private _components: ComponentList = new Map();
constructor() {
const iconList: Record<string, React.ForwardRefExoticComponent<any>> = {
@@ -150,18 +152,20 @@ export class ComponentManager {
}
}
- register(name: string, component: any) {
- if (this._componentList.has(name)) {
+ register(name: string, component: any): IDisposable {
+ if (this._components.has(name)) {
console.warn(`Component ${name} already exists.`);
}
- this._componentList.set(name, component);
+
+ this._components.set(name, component);
+ return toDisposable(() => this._components.delete(name));
}
get(name: string) {
- return this._componentList.get(name);
+ return this._components.get(name);
}
delete(name: string) {
- this._componentList.delete(name);
+ this._components.delete(name);
}
}
diff --git a/packages/base-ui/src/common/index.ts b/packages/base-ui/src/common/index.ts
new file mode 100644
index 0000000000..d4df12b99c
--- /dev/null
+++ b/packages/base-ui/src/common/index.ts
@@ -0,0 +1,2 @@
+export * from './component-manager';
+export * from './z-index-manager';
diff --git a/packages/base-ui/src/Common/lifecycle.ts b/packages/base-ui/src/common/lifecycle.ts
similarity index 100%
rename from packages/base-ui/src/Common/lifecycle.ts
rename to packages/base-ui/src/common/lifecycle.ts
diff --git a/packages/base-ui/src/Common/ZIndexManager.ts b/packages/base-ui/src/common/z-index-manager.ts
similarity index 100%
rename from packages/base-ui/src/Common/ZIndexManager.ts
rename to packages/base-ui/src/common/z-index-manager.ts
diff --git a/packages/base-ui/src/components/custom-label/CustomLabel.tsx b/packages/base-ui/src/components/custom-label/CustomLabel.tsx
index 8c2e2362f0..b953d7dc1f 100644
--- a/packages/base-ui/src/components/custom-label/CustomLabel.tsx
+++ b/packages/base-ui/src/components/custom-label/CustomLabel.tsx
@@ -2,7 +2,7 @@ import { LocaleService } from '@univerjs/core';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React from 'react';
-import { ComponentManager } from '../../Common';
+import { ComponentManager } from '../../common/component-manager';
import { IMenuSelectorItem } from '../../services/menu/menu';
export type ICustomLabelProps = {
diff --git a/packages/base-ui/src/controllers/menus/menu.ts b/packages/base-ui/src/controllers/menus/menus.ts
similarity index 100%
rename from packages/base-ui/src/controllers/menus/menu.ts
rename to packages/base-ui/src/controllers/menus/menus.ts
diff --git a/packages/base-ui/src/controllers/shared-shortcut.controller.ts b/packages/base-ui/src/controllers/shared-shortcut.controller.ts
index 77822283b4..cc1cbdad82 100644
--- a/packages/base-ui/src/controllers/shared-shortcut.controller.ts
+++ b/packages/base-ui/src/controllers/shared-shortcut.controller.ts
@@ -2,19 +2,43 @@ import { Disposable, ICommandService, LifecycleStages, OnLifecycle, RedoCommand,
import { Inject, Injector } from '@wendellhu/redi';
import { CopyCommand, CutCommand, PasteCommand } from '../services/clipboard/clipboard.command';
-import { CopyShortcutItem, CutShortcutItem, PasteShortcutItem } from '../services/clipboard/clipboard.shortcut';
import { IMenuService } from '../services/menu/menu.service';
import { KeyCode, MetaKeys } from '../services/shortcut/keycode';
import { IShortcutItem, IShortcutService } from '../services/shortcut/shortcut.service';
-import { RedoMenuItemFactory, UndoMenuItemFactory } from './menus/menu';
+import { RedoMenuItemFactory, UndoMenuItemFactory } from './menus/menus';
+
+export const CopyShortcutItem: IShortcutItem = {
+ id: CopyCommand.id,
+ description: 'shortcut.copy',
+ group: '1_common-edit',
+ binding: KeyCode.C | MetaKeys.CTRL_COMMAND,
+};
+
+export const CutShortcutItem: IShortcutItem = {
+ id: CutCommand.id,
+ description: 'shortcut.cut',
+ group: '1_common-edit',
+ binding: KeyCode.X | MetaKeys.CTRL_COMMAND,
+};
+
+export const PasteShortcutItem: IShortcutItem = {
+ id: PasteCommand.id,
+ description: 'shortcut.paste',
+ group: '1_common-edit',
+ binding: KeyCode.V | MetaKeys.CTRL_COMMAND,
+};
export const UndoShortcutItem: IShortcutItem = {
id: UndoCommand.id,
+ description: 'shortcut.undo',
+ group: '1_common-edit',
binding: KeyCode.Z | MetaKeys.CTRL_COMMAND,
};
export const RedoShortcutItem: IShortcutItem = {
id: RedoCommand.id,
+ description: 'shortcut.redo',
+ group: '1_common-edit',
binding: KeyCode.Y | MetaKeys.CTRL_COMMAND,
};
diff --git a/packages/base-ui/src/controllers/shortcut-display/menu.ts b/packages/base-ui/src/controllers/shortcut-display/menu.ts
new file mode 100644
index 0000000000..708c1eb0fb
--- /dev/null
+++ b/packages/base-ui/src/controllers/shortcut-display/menu.ts
@@ -0,0 +1,13 @@
+import { ToggleShortcutPanelOperation } from '../../commands/operations/toggle-shortcut-panel.operation';
+import { IMenuButtonItem, MenuItemType, MenuPosition } from '../../services/menu/menu';
+
+export function ShortcutPanelMenuItemFactory(): IMenuButtonItem {
+ return {
+ id: ToggleShortcutPanelOperation.id,
+ title: 'toggle-shortcut-panel',
+ tooltip: 'toggle-shortcut-panel',
+ icon: 'KeyboardSingle',
+ type: MenuItemType.BUTTON,
+ positions: [MenuPosition.TOOLBAR_OTHERS],
+ };
+}
diff --git a/packages/base-ui/src/controllers/shortcut-display/shortcut-panel.controller.ts b/packages/base-ui/src/controllers/shortcut-display/shortcut-panel.controller.ts
new file mode 100644
index 0000000000..67b4d9e9ba
--- /dev/null
+++ b/packages/base-ui/src/controllers/shortcut-display/shortcut-panel.controller.ts
@@ -0,0 +1,31 @@
+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import {
+ ShortcutPanelComponentName,
+ ToggleShortcutPanelOperation,
+} from '../../commands/operations/toggle-shortcut-panel.operation';
+import { ComponentManager } from '../../common/component-manager';
+import { IMenuService } from '../../services/menu/menu.service';
+import { ShortcutPanel } from '../../views/components/shortcut-panel/ShortcutPanel';
+import { ShortcutPanelMenuItemFactory } from './menu';
+
+/**
+ * This controller add a side panel to the application to display the shortcuts.
+ */
+@OnLifecycle(LifecycleStages.Steady, ShortcutPanelController)
+export class ShortcutPanelController extends Disposable {
+ constructor(
+ @IMenuService menuService: IMenuService,
+ @ICommandService commandService: ICommandService,
+ @Inject(ComponentManager) componentManager: ComponentManager
+ ) {
+ super();
+
+ // Register the menu item.
+ this.disposeWithMe(menuService.addMenuItem(ShortcutPanelMenuItemFactory()));
+ // Register the panel.
+ this.disposeWithMe(componentManager.register(ShortcutPanelComponentName, ShortcutPanel));
+ this.disposeWithMe(commandService.registerCommand(ToggleShortcutPanelOperation));
+ }
+}
diff --git a/packages/base-ui/src/helpers/index.ts b/packages/base-ui/src/helpers/index.ts
deleted file mode 100644
index 5778c7c08c..0000000000
--- a/packages/base-ui/src/helpers/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './cell';
diff --git a/packages/base-ui/src/index.ts b/packages/base-ui/src/index.ts
index 4cf8f0998c..d8cccad6c1 100644
--- a/packages/base-ui/src/index.ts
+++ b/packages/base-ui/src/index.ts
@@ -1,15 +1,20 @@
export { UIPlugin } from './base-ui-plugin';
export * from './BaseComponent';
-export * from './Common';
+export * from './common';
export * from './components';
export { useObservable } from './components/hooks/observable';
-export { SharedController } from './controllers/shared-shortcut.controller';
+export {
+ CopyShortcutItem,
+ CutShortcutItem,
+ PasteShortcutItem,
+ RedoShortcutItem,
+ SharedController,
+ UndoShortcutItem,
+} from './controllers/shared-shortcut.controller';
export { IUIController } from './controllers/ui/ui.controller';
export { DesktopUIPart, type IDesktopUIController } from './controllers/ui/ui-desktop.controller';
-export * from './helpers';
export { DesktopBeforeCloseService, IBeforeCloseService } from './services/before-close/before-close.service';
export { CopyCommand, CutCommand, PasteCommand } from './services/clipboard/clipboard.command';
-export { CopyShortcutItem, CutShortcutItem, PasteShortcutItem } from './services/clipboard/clipboard.shortcut';
export {
BrowserClipboardService,
HTML_CLIPBOARD_MIME_TYPE,
@@ -48,4 +53,4 @@ export { DesktopShortcutService, type IShortcutItem, IShortcutService } from './
export { ShortcutExperienceService } from './services/shortcut/shortcut-experience.service';
export { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';
export { ISidebarService } from './services/sidebar/sidebar.service';
-export * from './Utils';
+export * from './utils';
diff --git a/packages/base-ui/src/locale/en-US.ts b/packages/base-ui/src/locale/en-US.ts
index 28b1ef6aab..ea496335ba 100644
--- a/packages/base-ui/src/locale/en-US.ts
+++ b/packages/base-ui/src/locale/en-US.ts
@@ -7,4 +7,15 @@ export default {
view: 'View',
others: 'Others',
},
+ 'shortcut-panel': {
+ title: 'Shortcuts',
+ },
+ shortcut: {
+ undo: 'Undo',
+ redo: 'Redo',
+ cut: 'Cut',
+ copy: 'Copy',
+ paste: 'Paste',
+ },
+ 'common-edit': 'Common Editing Shortcuts',
};
diff --git a/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts b/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts
deleted file mode 100644
index 1ef4951e96..0000000000
--- a/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { KeyCode, MetaKeys } from '../shortcut/keycode';
-import { IShortcutItem } from '../shortcut/shortcut.service';
-import { CopyCommand, CutCommand, PasteCommand } from './clipboard.command';
-
-export const CopyShortcutItem: IShortcutItem = {
- id: CopyCommand.id,
- binding: KeyCode.C | MetaKeys.CTRL_COMMAND,
-};
-
-export const CutShortcutItem: IShortcutItem = {
- id: CutCommand.id,
- binding: KeyCode.X | MetaKeys.CTRL_COMMAND,
-};
-
-export const PasteShortcutItem: IShortcutItem = {
- id: PasteCommand.id,
- binding: KeyCode.V | MetaKeys.CTRL_COMMAND,
-};
diff --git a/packages/base-ui/src/services/menu/menu.service.ts b/packages/base-ui/src/services/menu/menu.service.ts
index fff7a527e7..3b0faa1c45 100644
--- a/packages/base-ui/src/services/menu/menu.service.ts
+++ b/packages/base-ui/src/services/menu/menu.service.ts
@@ -118,7 +118,7 @@ export class DesktopMenuService extends Disposable implements IMenuService {
}
private getDisplayMenuItems(menuItem: IMenuItem): IDisplayMenuItem<IMenuItem> {
- const shortcut = this._shortcutService.getCommandShortcut(menuItem.id);
+ const shortcut = this._shortcutService.getShortcutDisplay(menuItem.id);
if (!shortcut) {
return menuItem;
}
diff --git a/packages/base-ui/src/services/shortcut/keycode.ts b/packages/base-ui/src/services/shortcut/keycode.ts
index 2832efea3b..2cd7cc1404 100644
--- a/packages/base-ui/src/services/shortcut/keycode.ts
+++ b/packages/base-ui/src/services/shortcut/keycode.ts
@@ -1,6 +1,57 @@
/* eslint-disable no-magic-numbers */
// Useful keyboard event inspection tool https://www.toptal.com/developers/keycode
+export const KeyCodeToChar: { [key: number]: string } = {
+ [KeyCode.BACKSPACE]: 'Backspace',
+ [KeyCode.TAB]: 'Tab',
+ [KeyCode.ENTER]: 'Enter',
+ [KeyCode.DELETE]: 'Del',
+ [KeyCode.ESC]: 'Esc',
+ [KeyCode.SPACE]: 'Space',
+ [KeyCode.ARROW_LEFT]: '←',
+ [KeyCode.ARROW_RIGHT]: '→',
+ [KeyCode.ARROW_UP]: '↑',
+ [KeyCode.ARROW_DOWN]: '↓',
+
+ [KeyCode.Digit0]: '0',
+ [KeyCode.Digit1]: '1',
+ [KeyCode.Digit2]: '2',
+ [KeyCode.Digit3]: '3',
+ [KeyCode.Digit4]: '4',
+ [KeyCode.Digit5]: '5',
+ [KeyCode.Digit6]: '6',
+ [KeyCode.Digit7]: '7',
+ [KeyCode.Digit8]: '8',
+ [KeyCode.Digit9]: '9',
+
+ [KeyCode.A]: 'A',
+ [KeyCode.B]: 'B',
+ [KeyCode.C]: 'C',
+ [KeyCode.D]: 'D',
+ [KeyCode.E]: 'E',
+ [KeyCode.F]: 'F',
+ [KeyCode.G]: 'G',
+ [KeyCode.H]: 'H',
+ [KeyCode.I]: 'I',
+ [KeyCode.J]: 'J',
+ [KeyCode.K]: 'K',
+ [KeyCode.L]: 'L',
+ [KeyCode.M]: 'M',
+ [KeyCode.N]: 'N',
+ [KeyCode.O]: 'O',
+ [KeyCode.P]: 'P',
+ [KeyCode.Q]: 'Q',
+ [KeyCode.R]: 'R',
+ [KeyCode.S]: 'S',
+ [KeyCode.T]: 'T',
+ [KeyCode.U]: 'U',
+ [KeyCode.V]: 'V',
+ [KeyCode.W]: 'W',
+ [KeyCode.X]: 'X',
+ [KeyCode.Y]: 'Y',
+ [KeyCode.Z]: 'Z',
+};
+
/** KeyCode that maps to browser standard keycode. */
export const enum KeyCode {
UNKNOWN = 0,
diff --git a/packages/base-ui/src/services/shortcut/shortcut-panel.service.ts b/packages/base-ui/src/services/shortcut/shortcut-panel.service.ts
new file mode 100644
index 0000000000..2a028627ef
--- /dev/null
+++ b/packages/base-ui/src/services/shortcut/shortcut-panel.service.ts
@@ -0,0 +1,23 @@
+import { Disposable } from '@univerjs/core';
+import { BehaviorSubject, distinctUntilChanged } from 'rxjs';
+
+export class ShortcutPanelService extends Disposable {
+ private _open$ = new BehaviorSubject<boolean>(false);
+ open$ = this._open$.pipe(distinctUntilChanged());
+ get isOpen(): boolean {
+ return this._open$.getValue();
+ }
+
+ override dispose(): void {
+ this._open$.next(false);
+ this._open$.complete();
+ }
+
+ open(): void {
+ this._open$.next(true);
+ }
+
+ close(): void {
+ this._open$.next(false);
+ }
+}
diff --git a/packages/base-ui/src/services/shortcut/shortcut.service.ts b/packages/base-ui/src/services/shortcut/shortcut.service.ts
index 7241c9cce0..fbf4a8133d 100644
--- a/packages/base-ui/src/services/shortcut/shortcut.service.ts
+++ b/packages/base-ui/src/services/shortcut/shortcut.service.ts
@@ -1,10 +1,11 @@
import { Disposable, ICommandService, IContextService, toDisposable } from '@univerjs/core';
import { createIdentifier, IDisposable } from '@wendellhu/redi';
+import { Observable, Subject } from 'rxjs';
-import { fromDocumentEvent } from '../../Common/lifecycle';
+import { fromDocumentEvent } from '../../common/lifecycle';
import { IFocusService } from '../focus/focus.service';
import { IPlatformService } from '../platform/platform.service';
-import { MetaKeys } from './keycode';
+import { KeyCodeToChar, MetaKeys } from './keycode';
export interface IShortcutItem<P extends object = object> {
/** This should reuse the corresponding command's id. */
@@ -21,14 +22,22 @@ export interface IShortcutItem<P extends object = object> {
win?: number;
linux?: number;
+ /**
+ * The group of the menu item should belong to. The shortcut item would be rendered in the
+ * panel if this is set.
+ */
+ group?: string;
+
/** Static parameters of this shortcut. Would be send to `CommandService.executeCommand`. */
staticParameters?: P;
}
export interface IShortcutService {
- registerShortcut(shortcut: IShortcutItem): IDisposable;
+ shortcutChanged$: Observable<void>;
- getCommandShortcut(id: string): string | null;
+ registerShortcut(shortcut: IShortcutItem): IDisposable;
+ getShortcutDisplay(id: string): string | null;
+ getAllShortcuts(): IShortcutItem[];
}
export const IShortcutService = createIdentifier<IShortcutService>('univer.shortcut');
@@ -38,6 +47,9 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
private readonly _idToShortcut = new Map<string, number>();
+ private readonly _shortcutChanged$ = new Subject<void>();
+ readonly shortcutChanged$ = this._shortcutChanged$.asObservable();
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IPlatformService private readonly _platformService: IPlatformService,
@@ -46,18 +58,23 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
) {
super();
+ // Register native keydown event handler to trigger shortcuts.
this.disposeWithMe(
fromDocumentEvent('keydown', (e: KeyboardEvent) => {
- // if (this._focusService.isFocused) {
- this.resolveMouseEvent(e);
- // }
+ this._resolveMouseEvent(e);
})
);
}
+ getAllShortcuts(): IShortcutItem[] {
+ return Array.from(this._shortCutMapping.values())
+ .map((v) => Array.from(v.values()))
+ .flat();
+ }
+
registerShortcut(shortcut: IShortcutItem): IDisposable {
// first map shortcut to a number, so it could be converted and fetched quickly
- const binding = this.getBindingFromItem(shortcut);
+ const binding = this._getBindingFromItem(shortcut);
const existing = this._shortCutMapping.get(binding);
if (existing) {
@@ -67,14 +84,16 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
}
this._idToShortcut.set(shortcut.id, binding);
+ this._emitShortcutChanged();
return toDisposable(() => {
+ this._emitShortcutChanged();
this._idToShortcut.delete(shortcut.id);
this._shortCutMapping.delete(binding);
});
}
- getCommandShortcut(id: string): string | null {
+ getShortcutDisplay(id: string): string | null {
const binding = this._idToShortcut.get(id);
if (!binding) {
return null;
@@ -85,25 +104,27 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
const altKey = binding & MetaKeys.ALT;
const macCtrl = binding & MetaKeys.MAC_CTRL;
+ const body = KeyCodeToChar[binding & 0xff] ?? '<->';
+
if (this._platformService.isMac) {
- return `${ctrlKey ? '⌘' : ''}${shiftKey ? '⇧' : ''}${altKey ? '⌥' : ''}${
- macCtrl ? '⌃' : ''
- }${String.fromCharCode(binding & 0xff)}`;
+ return `${ctrlKey ? '⌘' : ''}${shiftKey ? '⇧' : ''}${altKey ? '⌥' : ''}${macCtrl ? '⌃' : ''}${body}`;
}
- return `${ctrlKey ? 'Ctrl+' : ''}${shiftKey ? 'Shift+' : ''}${altKey ? 'Alt+' : ''}${String.fromCharCode(
- binding & 0xff
- )}`;
+ return `${ctrlKey ? 'Ctrl+' : ''}${shiftKey ? 'Shift+' : ''}${altKey ? 'Alt+' : ''}${body}`;
+ }
+
+ private _emitShortcutChanged(): void {
+ this._shortcutChanged$.next();
}
- private resolveMouseEvent(e: KeyboardEvent): void {
- const shouldPreventDefault = this.dispatch(e);
+ private _resolveMouseEvent(e: KeyboardEvent): void {
+ const shouldPreventDefault = this._dispatch(e);
if (shouldPreventDefault) {
e.preventDefault();
}
}
- private dispatch(e: KeyboardEvent): boolean {
- const binding = this.deriveBindingFromEvent(e);
+ private _dispatch(e: KeyboardEvent): boolean {
+ const binding = this._deriveBindingFromEvent(e);
if (binding === null) {
return false;
}
@@ -125,7 +146,7 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
return false;
}
- private getBindingFromItem(item: IShortcutItem): number {
+ private _getBindingFromItem(item: IShortcutItem): number {
if (this._platformService.isMac && item.mac) {
return item.mac;
}
@@ -141,7 +162,7 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
return item.binding;
}
- private deriveBindingFromEvent(e: KeyboardEvent): number | null {
+ private _deriveBindingFromEvent(e: KeyboardEvent): number | null {
const { shiftKey, metaKey, altKey, keyCode } = e;
let binding = keyCode;
diff --git a/packages/base-ui/src/helpers/cell.ts b/packages/base-ui/src/utils/cell.ts
similarity index 96%
rename from packages/base-ui/src/helpers/cell.ts
rename to packages/base-ui/src/utils/cell.ts
index ba6d25cb7b..32758a80eb 100644
--- a/packages/base-ui/src/helpers/cell.ts
+++ b/packages/base-ui/src/utils/cell.ts
@@ -1,852 +1,852 @@
-import { ptToPx, pxToPt } from '@univerjs/base-render';
-import {
- getBorderStyleType,
- IBorderData,
- ICellData,
- IDocumentData,
- IKeyValue,
- IRange,
- IStyleData,
- ITextDecoration,
- ITextRun,
- Tools,
-} from '@univerjs/core';
-
-import { textTrim } from '../Utils';
-
-// TODO: move to Utils
-/**
- * The entire list of DOM spans is parsed into a rich-text JSON style sheet
- * @param $dom
- * @returns
- */
-export function handleDomToJson($dom: HTMLElement): IDocumentData | string {
- let nodeList = $dom.childNodes; // skip container itself
-
- // no node list
- if (nodeList.length === 0) {
- return $dom.textContent as string;
- }
-
- // skip first div
- if (nodeList[0].nodeName === 'DIV') {
- nodeList = nodeList[0].childNodes;
- }
-
- // 普通单元格,非富文本
- if (nodeList.length === 1 && nodeList[0].nodeName === '#text') {
- return nodeList[0].textContent as string;
- }
- const textRuns: ITextRun[] = [];
- let st = 0;
- let ed = 0;
- let dataStream = $dom.textContent || '';
- dataStream += '\r\n';
-
- for (let i = 0; i < nodeList.length; i++) {
- let span = nodeList[`${i}`] as HTMLElement;
- let str: string;
- if (span.nodeName === '#text') {
- str = span.textContent ?? '';
- span = span.parentElement!;
- } else {
- str = span.innerText;
- }
- const textStyle = handleStringToStyle(span);
-
- // let str = span.innerText;
- const spanTexts = splitSpanText(str);
-
- spanTexts.forEach((item) => {
- const length = item.length;
- ed += length;
- st = ed - length;
- const sId = Tools.generateRandomId(6);
-
- textRuns.push({
- sId,
- st,
- ed: ed - 1,
- ts: textStyle,
- });
- // // 如果有 \n 说明有换行,另起一段
- // if (item.includes('\n')) {
- // const pStart = cot.length > 0 ? cot[cot.length].ed : 0;
- // block = {
- // st: pStart,
- // ed: pStart + ele[ele.length - 1].ed,
- // blockType: BlockType.CUSTOM,
- // paragraph: {
- // elements: ele,
- // },
- // };
- // cot.push(block);
- // } else if (cot.length > 0) {
- // cot[cot.length - 1].ed = paragraphElement.ed;
- // } else {
- // const pStart = cot.length > 0 ? cot[cot.length].ed : 0;
- // block = {
- // st: pStart,
- // ed: paragraphElement.ed,
- // blockType: BlockType.CUSTOM,
- // paragraph: {
- // elements: ele,
- // },
- // };
-
- // cot.push(block);
- // }
- });
- }
-
- const blockId = Tools.generateRandomId(6);
- const p: IDocumentData = {
- id: Tools.generateRandomId(6),
- body: {
- dataStream,
- textRuns,
- },
- documentStyle: {},
- };
-
- return p;
-}
-
-/**
- * A single span parses out the ITextStyle style sheet
- * @param $dom
- * @returns
- */
-export function handleStringToStyle($dom?: HTMLElement, cssStyle: string = '') {
- let cssText = $dom?.style?.cssText ?? '';
- cssText += cssStyle;
- if (cssText.length === 0) {
- return {};
- }
- const cssTextArray = cssText.split(';');
- const styleList: IStyleData = {};
-
- const borderInfo = {
- t: '',
- r: '',
- b: '',
- l: '',
- };
-
- cssTextArray.forEach((s) => {
- s = s.toLowerCase();
- const key = textTrim(s.substr(0, s.indexOf(':')));
- const value = textTrim(s.substr(s.indexOf(':') + 1));
-
- // bold
- if (key === 'font-weight') {
- if (value === 'bold') {
- styleList.bl = 1;
- } else {
- styleList.bl = 0;
- }
- }
- // italic
- else if (key === 'font-style') {
- if (value === 'italic') {
- styleList.it = 1;
- } else {
- styleList.it = 0;
- }
- }
- // font family
- else if (key === 'font-family') {
- styleList.ff = value;
- }
- // font size
- else if (key === 'font-size') {
- let fs = parseInt(value);
-
- // Double the font size for superscripts and subscripts
- if (
- cssText.indexOf('vertical-align') > -1 &&
- (cssText.indexOf('sub') > -1 || cssText.indexOf('sup') > -1)
- ) {
- fs *= 2;
- }
-
- // px to pt TODO@Dushusir: px or pt?
- if (value.indexOf('px') !== -1) {
- fs = pxToPt(parseInt(value));
- }
-
- styleList.fs = fs;
- }
- // font color
- else if (key === 'color') {
- styleList.cl = {
- rgb: value,
- };
- }
- // fill color / background
- else if (key === 'background' || key === 'background-color') {
- styleList.bg = {
- rgb: value,
- };
- }
-
- // text line type
- else if (key === 'text-decoration-line') {
- // underline
- if (value === 'underline') {
- if (!styleList.ul) {
- styleList.ul = { s: 1 };
- }
- styleList.ul.s = 1;
- }
-
- // line through
- else if (value === 'line-through') {
- if (!styleList.st) {
- styleList.st = { s: 1 };
- }
- styleList.st.s = 1;
- }
- // overline
- else if (value === 'overline') {
- if (!styleList.ol) {
- styleList.ol = { s: 1 };
- }
- styleList.ol.s = 1;
- }
- }
-
- // text line color
- else if (key === 'text-decoration-color') {
- if (styleList.hasOwnProperty('ul')) {
- if (!styleList.ul) {
- styleList.ul = { s: 1, cl: { rgb: value } };
- }
- (styleList.ul as ITextDecoration).cl = {
- rgb: value,
- };
- }
- if (styleList.hasOwnProperty('st')) {
- if (!styleList.st) {
- styleList.st = { s: 1, cl: { rgb: value } };
- }
- (styleList.st as ITextDecoration).cl = {
- rgb: value,
- };
- }
- if (styleList.hasOwnProperty('ol')) {
- if (!styleList.ol) {
- styleList.ol = { s: 1, cl: { rgb: value } };
- }
- (styleList.ol as ITextDecoration).cl = {
- rgb: value,
- };
- }
- }
-
- // text line style
- else if (key === 'text-decoration-style') {
- if (styleList.hasOwnProperty('ul')) {
- if (!styleList.ul) {
- styleList.ul = { s: 1, t: Number(value) };
- }
- (styleList.ul as ITextDecoration).t = Number(value);
- }
- if (styleList.hasOwnProperty('st')) {
- if (!styleList.st) {
- styleList.st = { s: 1, t: Number(value) };
- }
- (styleList.st as ITextDecoration).t = Number(value);
- }
- if (styleList.hasOwnProperty('ol')) {
- if (!styleList.ol) {
- styleList.ol = { s: 1, t: Number(value) };
- }
- (styleList.ol as ITextDecoration).t = Number(value);
- }
- }
-
- // line through
- else if (key === 'text-decoration' || key === 'univer-strike') {
- styleList.st = {
- s: 1,
- };
- }
- // underline
- if (key === 'univer-underline') {
- styleList.ul = {
- s: 1,
- };
- }
-
- if (key === 'vertical-align') {
- if (value === 'sub') {
- styleList.va = 1;
- } else if (value === 'super') {
- styleList.va = 2;
- } else if (value === 'top') {
- styleList.vt = 1;
- } else if (value === 'middle') {
- styleList.vt = 2;
- } else if (value === 'bottom') {
- styleList.vt = 3;
- } else {
- styleList.va = 0;
- }
- }
-
- if (key === 'transform') {
- const values = value.split(')');
- const index = values.findIndex((item) => item.includes('rotate'));
- if (index > -1) {
- const match = values[index].match(/\d+/g);
- let angle = 0;
- let ver = 0;
- if (match?.length) {
- angle = +match[0];
- }
- // 竖排文字
- if ($dom?.dataset.vertical) {
- ver = +$dom.dataset.vertical;
- }
- styleList.tr = {
- a: angle,
- v: ver,
- };
- }
- }
-
- if (key === 'text-align') {
- if (value === 'left') {
- styleList.ht = 1;
- } else if (value === 'center') {
- styleList.ht = 2;
- } else if (value === 'right') {
- styleList.ht = 3;
- } else if (value === 'justify') {
- styleList.ht = 4;
- } else {
- styleList.ht = 0;
- }
- }
-
- // wrap text
- if (key === 'overflow-wrap' || key === 'word-wrap') {
- if (value === 'break-word') {
- styleList.tb = 3;
- }
- } else if (key === 'text-overflow') {
- if (value === 'clip') {
- styleList.tb = 2;
- }
- } else if (key === 'text-break') {
- if (value === 'overflow') {
- styleList.tb = 1;
- }
- }
-
- if (key === 'border-color') {
- const colors = handleBorder(value, ')');
- if (!styleList.bd) {
- styleList.bd = {
- b: {
- cl: {
- rgb: '#000',
- },
- s: 0,
- },
- t: {
- cl: {
- rgb: '#000',
- },
- s: 0,
- },
- l: {
- cl: {
- rgb: '#000',
- },
- s: 0,
- },
- r: {
- cl: {
- rgb: '#000',
- },
- s: 0,
- },
- };
- for (const k in colors) {
- (styleList.bd as IKeyValue)[k].cl.rgb = colors[k as keyof IBorderData];
- }
- } else {
- for (const k in colors) {
- (styleList.bd as IKeyValue)[k].cl.rgb = colors[k as keyof IBorderData];
- }
- }
- }
-
- if (key === 'border-width' || key === 'border-style') {
- const width = handleBorder(value, ' ');
- for (const k in width) {
- (borderInfo as IKeyValue)[k] += ` ${width[k as keyof IBorderData]}`;
- }
- if (!styleList.bd) {
- styleList.bd = {
- b: {
- cl: {
- rgb: '#000',
- },
- s: getBorderStyleType(borderInfo.b),
- },
- t: {
- cl: {
- rgb: '#000',
- },
- s: getBorderStyleType(borderInfo.t),
- },
- l: {
- cl: {
- rgb: '#000',
- },
- s: getBorderStyleType(borderInfo.l),
- },
- r: {
- cl: {
- rgb: '#000',
- },
- s: getBorderStyleType(borderInfo.r),
- },
- };
- } else {
- styleList.bd.b!.s = getBorderStyleType(borderInfo.b);
- styleList.bd.t!.s = getBorderStyleType(borderInfo.t);
- styleList.bd.l!.s = getBorderStyleType(borderInfo.l);
- styleList.bd.r!.s = getBorderStyleType(borderInfo.r);
- }
- }
-
- if (
- key === 'border-bottom' ||
- key === 'border-top' ||
- key === 'border-left' ||
- key === 'border-right' ||
- key === 'border'
- ) {
- if (!styleList.bd) {
- styleList.bd = {};
- }
- const arr = value.split(' ');
- const type = `${arr[0]} ${arr[1]}`;
- arr.splice(0, 2);
- const color = arr.join('');
- const obj = {
- cl: {
- rgb: color,
- },
- s: getBorderStyleType(type),
- };
- if (key === 'border-bottom') {
- styleList.bd.b = value === 'none' ? null : obj;
- } else if (key === 'border-top') {
- styleList.bd.t = value === 'none' ? null : obj;
- } else if (key === 'border-left') {
- styleList.bd.l = value === 'none' ? null : obj;
- } else if (key === 'border-right') {
- styleList.bd.r = value === 'none' ? null : obj;
- } else if (key === 'border') {
- styleList.bd = {
- r: value === 'none' ? null : obj,
- t: value === 'none' ? null : obj,
- b: value === 'none' ? null : obj,
- l: value === 'none' ? null : obj,
- };
- }
- }
-
- // if (style.tb === WrapStrategy.CLIP) {
- // str += `text-overflow: clip; `;
- // } else if (style.tb === WrapStrategy.OVERFLOW) {
- // str += `text-break: overflow; `;
- // } else if (style.tb === WrapStrategy.WRAP) {
- // str += `word-wrap: break-word; word-break: normal; `;
- // }
- });
-
- return styleList;
-}
-
-function handleBorder(border: string, param: string): IBorderData {
- let arr;
- if (param === ' ') {
- arr = border.trim().split(param);
- } else {
- arr = border.trim().split(param).slice(0, -1);
- }
- arr.forEach((item) => `${item.trim()})`);
- let obj = {};
-
- if (arr.length === 1) {
- obj = {
- t: arr[0],
- r: arr[0],
- b: arr[0],
- l: arr[0],
- };
- } else if (arr.length === 2) {
- obj = {
- t: arr[0],
- r: arr[1],
- b: arr[0],
- l: arr[1],
- };
- } else if (arr.length === 3) {
- obj = {
- t: arr[0],
- r: arr[1],
- b: arr[2],
- l: arr[1],
- };
- } else if (arr.length === 4) {
- obj = {
- t: arr[0],
- r: arr[1],
- b: arr[2],
- l: arr[3],
- };
- }
-
- return obj;
-}
-
-/**
- * split span text
- * @param text
- * @returns
- */
-export function splitSpanText(text: string) {
- if (text === '') return [text];
- const regex = /(?:(\n+.+)|(.+))/g;
- const arr = text.match(regex)!;
- const arr1 = arr.map((item) => item.replace(/\n/g, '\r\n'));
- return arr1;
-}
-
-export function handleTableColgroup(table: string) {
- const content = document.createElement('DIV');
- const data: any[] = [];
- content.innerHTML = table;
- const colgroup = content.querySelectorAll('table col');
- if (!colgroup.length) return [];
- for (let i = 0; i < colgroup.length; i++) {
- const col = colgroup[i];
- const colSpan = col.getAttribute('span');
- if (colSpan && +colSpan > 1) {
- for (let j = 0; j < +colSpan; j++) {
- const width = getTdHeight(col.getAttribute('width'), 72);
- data.push(width);
- }
- } else {
- const width = getTdHeight(col.getAttribute('width'), 72);
- data.push(width);
- }
- }
- return data;
-}
-
-function getTdHeight(height: string | null, defaultHeight: number) {
- if (!height) return defaultHeight;
- let firstHeight;
- if (height.includes('pt')) {
- firstHeight = ptToPx(parseFloat(height));
- } else if (height.includes('px')) {
- firstHeight = parseFloat(height);
- } else {
- firstHeight = (parseFloat(height) * 72) / 96;
- }
- return firstHeight;
-}
-
-export function handleTableRowGroup(table: string) {
- const content = document.createElement('DIV');
- const data: any[] = [];
- content.innerHTML = table;
- const rowGroup = content.querySelectorAll('table tr');
- if (!rowGroup.length) return [];
- for (let i = 0; i < rowGroup.length; i++) {
- const row = rowGroup[i];
- const tds = row.querySelectorAll('td');
- let firstHeight = getTdHeight(tds[0].style.height, 19);
-
- for (let k = 0; k < tds.length; k++) {
- const rowSpan = tds[k].getAttribute('rowSpan');
- // const height = getTdHeight(tds[k].style.height);
- if (rowSpan && +rowSpan > 1) {
- // for (let j = 0; j < +rowSpan; j++) {
- // data.push(height);
- // }
- // i = i + +rowSpan - 1;
- continue;
- }
- firstHeight = getTdHeight(tds[k].style.height, 19);
- break;
- }
- data.push(firstHeight);
- }
- return data;
-}
-
-// 将table数据转为sheet数据
-export function handelTableToJson(table: string) {
- let data: any[] = [];
- const content = document.createElement('DIV');
- content.innerHTML = table;
- data = new Array(content.querySelectorAll('table tr').length);
- if (!data.length) return [];
- let colLen = 0;
- const trs = content.querySelectorAll('table tr');
- const firstTds = trs[0].querySelectorAll('td');
- firstTds.forEach((item: HTMLTableCellElement) => {
- let colSpan = 0;
- const attr = item.getAttribute('colSpan');
- if (attr !== null) {
- colSpan = +attr;
- } else {
- colSpan = 1;
- }
- colLen += colSpan;
- });
- for (let i = 0; i < data.length; i++) {
- data[i] = new Array(colLen);
- }
- let r = 0;
- trs.forEach((item: any) => {
- let c = 0;
- item.querySelectorAll('td').forEach((td: HTMLTableCellElement) => {
- const cell: ICellData = {};
- if (td.querySelectorAll('span').length || td.querySelectorAll('font').length) {
- const spanStyle = handleDomToJson(td);
- if (typeof spanStyle !== 'string') {
- cell.p = spanStyle;
- }
- }
- const txt = td.innerText;
- if (txt.trim().length === 0) {
- cell.v = '';
- cell.m = '';
- } else {
- // Todo,处理格式
- cell.v = txt;
- cell.m = txt;
- }
- const style = handleStringToStyle(td);
- if (Tools.isPlainObject(style)) {
- cell.s = style;
- }
- while (c < colLen && data[r][c] != null) {
- c++;
- }
- if (c === colLen) {
- return;
- }
- if (data[r][c] == null) {
- data[r][c] = cell;
- const rowSpan = Number(td.getAttribute('rowSpan')) ?? 1;
- const colSpan = Number(td.getAttribute('colSpan')) ?? 1;
- if (rowSpan > 1 || colSpan > 1) {
- const first = { rs: +rowSpan - 1, cs: +colSpan - 1, r, c };
- data[r][c].mc = first;
- for (let rp = 0; rp < rowSpan; rp++) {
- for (let cp = 0; cp < colSpan; cp++) {
- if (rp === 0 && cp === 0) {
- continue;
- }
- data[r + rp][c + cp] = { mc: null };
- }
- }
- }
- }
- c++;
- });
- r++;
- });
-
- return data;
-}
-
-// 将文本格式数据转为sheet数据
-export function handlePlainToJson(plain: string) {
- const data: any[] = [];
- const content = document.createElement('DIV');
- content.innerHTML = plain;
- const dataChe = plain.replace(/\r/g, '');
- const che = dataChe.split('\n');
- const colCheLen = che[0].split('\t').length;
- for (let i = 0; i < che.length; i++) {
- if (che[i].split('\t').length < colCheLen) {
- continue;
- }
- data.push(che[i].split('\t'));
- }
- for (let i = 0; i < data.length; i++) {
- for (let j = 0; j < data[i].length; j++) {
- if (data[i][j].length) {
- data[i][j] = {
- v: data[i][j] || '',
- m: data[i][j] || '',
- };
- } else {
- data[i][j] = null;
- }
- }
- }
-
- return data;
-}
-
-// 获取最终sheet数据
-export function handleTableMergeData(data: any[], selection?: IRange) {
- const copyH = data.length;
- const copyC = data[0].length;
- let minH = 0; //应用范围首尾行
- let maxH = minH + copyH - 1;
- let minC = 0; //应用范围首尾列
- let maxC = minC + copyC - 1;
- if (selection) {
- minH = selection.startRow; //应用范围首尾行
- maxH = minH + copyH - 1;
- minC = selection.startColumn; //应用范围首尾列
- maxC = minC + copyC - 1;
- }
-
- const mergeData = [];
-
- for (let i = 0; i < data.length; i++) {
- for (let j = 0; j < data[i].length; j++) {
- if (data[i][j] && typeof data[i][j] === 'object' && 'mc' in data[i][j]) {
- if (data[i][j].mc) {
- const mc = data[i][j].mc;
- const startRow = mc.r + minH;
- const endRow = startRow + mc.rs;
- const startColumn = mc.c + minC;
- const endColumn = startColumn + mc.cs;
-
- mergeData.push({ startRow, endRow, startColumn, endColumn });
- delete data[i][j].mc;
- } else {
- data[i][j] = null;
- }
- }
- }
- }
-
- return {
- data,
- mergeData,
- };
-}
-
-export function handelExcelToJson(html: string) {
- let data: any[] = [];
- const content = document.createElement('html');
- content.innerHTML = html;
- const styleText = content.querySelector('style')?.innerText;
- if (!styleText) return;
- const excelStyle = getStyles(styleText);
-
- data = new Array(content.querySelectorAll('table tr').length);
- if (!data.length) return [];
- let colLen = 0;
- const trs = content.querySelectorAll('table tr');
- const firstTds = trs[0].querySelectorAll('td');
- firstTds.forEach((item: HTMLTableCellElement) => {
- let colSpan = 0;
- const attr = item.getAttribute('colSpan');
- if (attr !== null) {
- colSpan = +attr;
- } else {
- colSpan = 1;
- }
- colLen += colSpan;
- });
- for (let i = 0; i < data.length; i++) {
- data[i] = new Array(colLen);
- }
- let r = 0;
- trs.forEach((item: any) => {
- let c = 0;
- item.querySelectorAll('td').forEach((td: HTMLTableCellElement) => {
- const cell: ICellData = {};
- if (td.querySelectorAll('span').length || td.querySelectorAll('font').length) {
- const spanStyle = handleDomToJson(td);
- if (typeof spanStyle !== 'string') {
- cell.p = spanStyle;
- }
- }
- const txt = td.innerText;
- if (txt.trim().length === 0) {
- cell.v = '';
- cell.m = '';
- } else {
- // Todo,处理格式
- cell.v = txt;
- cell.m = txt;
- }
-
- let cssText = '';
- for (const attr in excelStyle) {
- if (td.classList.contains(attr)) {
- cssText += excelStyle[attr];
- }
- }
- const style = handleStringToStyle(td, cssText);
-
- if (Tools.isPlainObject(style)) {
- cell.s = style;
- }
- while (c < colLen && data[r][c] != null) {
- c++;
- }
- if (c === colLen) {
- return;
- }
- if (data[r][c] == null) {
- data[r][c] = cell;
- const rowSpan = Number(td.getAttribute('rowSpan')) ?? 1;
- const colSpan = Number(td.getAttribute('colSpan')) ?? 1;
-
- if (rowSpan > 1 || colSpan > 1) {
- const first = { rs: +rowSpan - 1, cs: +colSpan - 1, r, c };
- data[r][c].mc = first;
- for (let rp = 0; rp < rowSpan; rp++) {
- for (let cp = 0; cp < colSpan; cp++) {
- if (rp === 0 && cp === 0) {
- continue;
- }
- data[r + rp][c + cp] = { mc: null };
- }
- }
- }
- }
- c++;
- });
- r++;
- });
-
- return data;
-}
-
-function getStyles(styleText: string): IKeyValue {
- const output: IKeyValue = {};
- const string = styleText.replaceAll('<!--', '').replaceAll('-->', '').trim();
- const style = string?.replaceAll('\t', '').replaceAll('\n', '').split('}');
- for (let i = 0; i < style.length; i++) {
- if (!style[i]) continue;
- let attr = style[i].split('{')[0].trim();
- if (attr.includes('.')) {
- attr = attr.slice(1);
- }
- const value = style[i].split('{')[1].trim();
- output[attr] = value;
- }
-
- return output;
-}
+import { ptToPx, pxToPt } from '@univerjs/base-render';
+import {
+ getBorderStyleType,
+ IBorderData,
+ ICellData,
+ IDocumentData,
+ IKeyValue,
+ IRange,
+ IStyleData,
+ ITextDecoration,
+ ITextRun,
+ Tools,
+} from '@univerjs/core';
+
+import { textTrim } from './util';
+
+// TODO: move to Utils
+/**
+ * The entire list of DOM spans is parsed into a rich-text JSON style sheet
+ * @param $dom
+ * @returns
+ */
+export function handleDomToJson($dom: HTMLElement): IDocumentData | string {
+ let nodeList = $dom.childNodes; // skip container itself
+
+ // no node list
+ if (nodeList.length === 0) {
+ return $dom.textContent as string;
+ }
+
+ // skip first div
+ if (nodeList[0].nodeName === 'DIV') {
+ nodeList = nodeList[0].childNodes;
+ }
+
+ // 普通单元格,非富文本
+ if (nodeList.length === 1 && nodeList[0].nodeName === '#text') {
+ return nodeList[0].textContent as string;
+ }
+ const textRuns: ITextRun[] = [];
+ let st = 0;
+ let ed = 0;
+ let dataStream = $dom.textContent || '';
+ dataStream += '\r\n';
+
+ for (let i = 0; i < nodeList.length; i++) {
+ let span = nodeList[`${i}`] as HTMLElement;
+ let str: string;
+ if (span.nodeName === '#text') {
+ str = span.textContent ?? '';
+ span = span.parentElement!;
+ } else {
+ str = span.innerText;
+ }
+ const textStyle = handleStringToStyle(span);
+
+ // let str = span.innerText;
+ const spanTexts = splitSpanText(str);
+
+ spanTexts.forEach((item) => {
+ const length = item.length;
+ ed += length;
+ st = ed - length;
+ const sId = Tools.generateRandomId(6);
+
+ textRuns.push({
+ sId,
+ st,
+ ed: ed - 1,
+ ts: textStyle,
+ });
+ // // 如果有 \n 说明有换行,另起一段
+ // if (item.includes('\n')) {
+ // const pStart = cot.length > 0 ? cot[cot.length].ed : 0;
+ // block = {
+ // st: pStart,
+ // ed: pStart + ele[ele.length - 1].ed,
+ // blockType: BlockType.CUSTOM,
+ // paragraph: {
+ // elements: ele,
+ // },
+ // };
+ // cot.push(block);
+ // } else if (cot.length > 0) {
+ // cot[cot.length - 1].ed = paragraphElement.ed;
+ // } else {
+ // const pStart = cot.length > 0 ? cot[cot.length].ed : 0;
+ // block = {
+ // st: pStart,
+ // ed: paragraphElement.ed,
+ // blockType: BlockType.CUSTOM,
+ // paragraph: {
+ // elements: ele,
+ // },
+ // };
+
+ // cot.push(block);
+ // }
+ });
+ }
+
+ const blockId = Tools.generateRandomId(6);
+ const p: IDocumentData = {
+ id: Tools.generateRandomId(6),
+ body: {
+ dataStream,
+ textRuns,
+ },
+ documentStyle: {},
+ };
+
+ return p;
+}
+
+/**
+ * A single span parses out the ITextStyle style sheet
+ * @param $dom
+ * @returns
+ */
+export function handleStringToStyle($dom?: HTMLElement, cssStyle: string = '') {
+ let cssText = $dom?.style?.cssText ?? '';
+ cssText += cssStyle;
+ if (cssText.length === 0) {
+ return {};
+ }
+ const cssTextArray = cssText.split(';');
+ const styleList: IStyleData = {};
+
+ const borderInfo = {
+ t: '',
+ r: '',
+ b: '',
+ l: '',
+ };
+
+ cssTextArray.forEach((s) => {
+ s = s.toLowerCase();
+ const key = textTrim(s.substr(0, s.indexOf(':')));
+ const value = textTrim(s.substr(s.indexOf(':') + 1));
+
+ // bold
+ if (key === 'font-weight') {
+ if (value === 'bold') {
+ styleList.bl = 1;
+ } else {
+ styleList.bl = 0;
+ }
+ }
+ // italic
+ else if (key === 'font-style') {
+ if (value === 'italic') {
+ styleList.it = 1;
+ } else {
+ styleList.it = 0;
+ }
+ }
+ // font family
+ else if (key === 'font-family') {
+ styleList.ff = value;
+ }
+ // font size
+ else if (key === 'font-size') {
+ let fs = parseInt(value);
+
+ // Double the font size for superscripts and subscripts
+ if (
+ cssText.indexOf('vertical-align') > -1 &&
+ (cssText.indexOf('sub') > -1 || cssText.indexOf('sup') > -1)
+ ) {
+ fs *= 2;
+ }
+
+ // px to pt TODO@Dushusir: px or pt?
+ if (value.indexOf('px') !== -1) {
+ fs = pxToPt(parseInt(value));
+ }
+
+ styleList.fs = fs;
+ }
+ // font color
+ else if (key === 'color') {
+ styleList.cl = {
+ rgb: value,
+ };
+ }
+ // fill color / background
+ else if (key === 'background' || key === 'background-color') {
+ styleList.bg = {
+ rgb: value,
+ };
+ }
+
+ // text line type
+ else if (key === 'text-decoration-line') {
+ // underline
+ if (value === 'underline') {
+ if (!styleList.ul) {
+ styleList.ul = { s: 1 };
+ }
+ styleList.ul.s = 1;
+ }
+
+ // line through
+ else if (value === 'line-through') {
+ if (!styleList.st) {
+ styleList.st = { s: 1 };
+ }
+ styleList.st.s = 1;
+ }
+ // overline
+ else if (value === 'overline') {
+ if (!styleList.ol) {
+ styleList.ol = { s: 1 };
+ }
+ styleList.ol.s = 1;
+ }
+ }
+
+ // text line color
+ else if (key === 'text-decoration-color') {
+ if (styleList.hasOwnProperty('ul')) {
+ if (!styleList.ul) {
+ styleList.ul = { s: 1, cl: { rgb: value } };
+ }
+ (styleList.ul as ITextDecoration).cl = {
+ rgb: value,
+ };
+ }
+ if (styleList.hasOwnProperty('st')) {
+ if (!styleList.st) {
+ styleList.st = { s: 1, cl: { rgb: value } };
+ }
+ (styleList.st as ITextDecoration).cl = {
+ rgb: value,
+ };
+ }
+ if (styleList.hasOwnProperty('ol')) {
+ if (!styleList.ol) {
+ styleList.ol = { s: 1, cl: { rgb: value } };
+ }
+ (styleList.ol as ITextDecoration).cl = {
+ rgb: value,
+ };
+ }
+ }
+
+ // text line style
+ else if (key === 'text-decoration-style') {
+ if (styleList.hasOwnProperty('ul')) {
+ if (!styleList.ul) {
+ styleList.ul = { s: 1, t: Number(value) };
+ }
+ (styleList.ul as ITextDecoration).t = Number(value);
+ }
+ if (styleList.hasOwnProperty('st')) {
+ if (!styleList.st) {
+ styleList.st = { s: 1, t: Number(value) };
+ }
+ (styleList.st as ITextDecoration).t = Number(value);
+ }
+ if (styleList.hasOwnProperty('ol')) {
+ if (!styleList.ol) {
+ styleList.ol = { s: 1, t: Number(value) };
+ }
+ (styleList.ol as ITextDecoration).t = Number(value);
+ }
+ }
+
+ // line through
+ else if (key === 'text-decoration' || key === 'univer-strike') {
+ styleList.st = {
+ s: 1,
+ };
+ }
+ // underline
+ if (key === 'univer-underline') {
+ styleList.ul = {
+ s: 1,
+ };
+ }
+
+ if (key === 'vertical-align') {
+ if (value === 'sub') {
+ styleList.va = 1;
+ } else if (value === 'super') {
+ styleList.va = 2;
+ } else if (value === 'top') {
+ styleList.vt = 1;
+ } else if (value === 'middle') {
+ styleList.vt = 2;
+ } else if (value === 'bottom') {
+ styleList.vt = 3;
+ } else {
+ styleList.va = 0;
+ }
+ }
+
+ if (key === 'transform') {
+ const values = value.split(')');
+ const index = values.findIndex((item) => item.includes('rotate'));
+ if (index > -1) {
+ const match = values[index].match(/\d+/g);
+ let angle = 0;
+ let ver = 0;
+ if (match?.length) {
+ angle = +match[0];
+ }
+ // 竖排文字
+ if ($dom?.dataset.vertical) {
+ ver = +$dom.dataset.vertical;
+ }
+ styleList.tr = {
+ a: angle,
+ v: ver,
+ };
+ }
+ }
+
+ if (key === 'text-align') {
+ if (value === 'left') {
+ styleList.ht = 1;
+ } else if (value === 'center') {
+ styleList.ht = 2;
+ } else if (value === 'right') {
+ styleList.ht = 3;
+ } else if (value === 'justify') {
+ styleList.ht = 4;
+ } else {
+ styleList.ht = 0;
+ }
+ }
+
+ // wrap text
+ if (key === 'overflow-wrap' || key === 'word-wrap') {
+ if (value === 'break-word') {
+ styleList.tb = 3;
+ }
+ } else if (key === 'text-overflow') {
+ if (value === 'clip') {
+ styleList.tb = 2;
+ }
+ } else if (key === 'text-break') {
+ if (value === 'overflow') {
+ styleList.tb = 1;
+ }
+ }
+
+ if (key === 'border-color') {
+ const colors = handleBorder(value, ')');
+ if (!styleList.bd) {
+ styleList.bd = {
+ b: {
+ cl: {
+ rgb: '#000',
+ },
+ s: 0,
+ },
+ t: {
+ cl: {
+ rgb: '#000',
+ },
+ s: 0,
+ },
+ l: {
+ cl: {
+ rgb: '#000',
+ },
+ s: 0,
+ },
+ r: {
+ cl: {
+ rgb: '#000',
+ },
+ s: 0,
+ },
+ };
+ for (const k in colors) {
+ (styleList.bd as IKeyValue)[k].cl.rgb = colors[k as keyof IBorderData];
+ }
+ } else {
+ for (const k in colors) {
+ (styleList.bd as IKeyValue)[k].cl.rgb = colors[k as keyof IBorderData];
+ }
+ }
+ }
+
+ if (key === 'border-width' || key === 'border-style') {
+ const width = handleBorder(value, ' ');
+ for (const k in width) {
+ (borderInfo as IKeyValue)[k] += ` ${width[k as keyof IBorderData]}`;
+ }
+ if (!styleList.bd) {
+ styleList.bd = {
+ b: {
+ cl: {
+ rgb: '#000',
+ },
+ s: getBorderStyleType(borderInfo.b),
+ },
+ t: {
+ cl: {
+ rgb: '#000',
+ },
+ s: getBorderStyleType(borderInfo.t),
+ },
+ l: {
+ cl: {
+ rgb: '#000',
+ },
+ s: getBorderStyleType(borderInfo.l),
+ },
+ r: {
+ cl: {
+ rgb: '#000',
+ },
+ s: getBorderStyleType(borderInfo.r),
+ },
+ };
+ } else {
+ styleList.bd.b!.s = getBorderStyleType(borderInfo.b);
+ styleList.bd.t!.s = getBorderStyleType(borderInfo.t);
+ styleList.bd.l!.s = getBorderStyleType(borderInfo.l);
+ styleList.bd.r!.s = getBorderStyleType(borderInfo.r);
+ }
+ }
+
+ if (
+ key === 'border-bottom' ||
+ key === 'border-top' ||
+ key === 'border-left' ||
+ key === 'border-right' ||
+ key === 'border'
+ ) {
+ if (!styleList.bd) {
+ styleList.bd = {};
+ }
+ const arr = value.split(' ');
+ const type = `${arr[0]} ${arr[1]}`;
+ arr.splice(0, 2);
+ const color = arr.join('');
+ const obj = {
+ cl: {
+ rgb: color,
+ },
+ s: getBorderStyleType(type),
+ };
+ if (key === 'border-bottom') {
+ styleList.bd.b = value === 'none' ? null : obj;
+ } else if (key === 'border-top') {
+ styleList.bd.t = value === 'none' ? null : obj;
+ } else if (key === 'border-left') {
+ styleList.bd.l = value === 'none' ? null : obj;
+ } else if (key === 'border-right') {
+ styleList.bd.r = value === 'none' ? null : obj;
+ } else if (key === 'border') {
+ styleList.bd = {
+ r: value === 'none' ? null : obj,
+ t: value === 'none' ? null : obj,
+ b: value === 'none' ? null : obj,
+ l: value === 'none' ? null : obj,
+ };
+ }
+ }
+
+ // if (style.tb === WrapStrategy.CLIP) {
+ // str += `text-overflow: clip; `;
+ // } else if (style.tb === WrapStrategy.OVERFLOW) {
+ // str += `text-break: overflow; `;
+ // } else if (style.tb === WrapStrategy.WRAP) {
+ // str += `word-wrap: break-word; word-break: normal; `;
+ // }
+ });
+
+ return styleList;
+}
+
+function handleBorder(border: string, param: string): IBorderData {
+ let arr;
+ if (param === ' ') {
+ arr = border.trim().split(param);
+ } else {
+ arr = border.trim().split(param).slice(0, -1);
+ }
+ arr.forEach((item) => `${item.trim()})`);
+ let obj = {};
+
+ if (arr.length === 1) {
+ obj = {
+ t: arr[0],
+ r: arr[0],
+ b: arr[0],
+ l: arr[0],
+ };
+ } else if (arr.length === 2) {
+ obj = {
+ t: arr[0],
+ r: arr[1],
+ b: arr[0],
+ l: arr[1],
+ };
+ } else if (arr.length === 3) {
+ obj = {
+ t: arr[0],
+ r: arr[1],
+ b: arr[2],
+ l: arr[1],
+ };
+ } else if (arr.length === 4) {
+ obj = {
+ t: arr[0],
+ r: arr[1],
+ b: arr[2],
+ l: arr[3],
+ };
+ }
+
+ return obj;
+}
+
+/**
+ * split span text
+ * @param text
+ * @returns
+ */
+export function splitSpanText(text: string) {
+ if (text === '') return [text];
+ const regex = /(?:(\n+.+)|(.+))/g;
+ const arr = text.match(regex)!;
+ const arr1 = arr.map((item) => item.replace(/\n/g, '\r\n'));
+ return arr1;
+}
+
+export function handleTableColgroup(table: string) {
+ const content = document.createElement('DIV');
+ const data: any[] = [];
+ content.innerHTML = table;
+ const colgroup = content.querySelectorAll('table col');
+ if (!colgroup.length) return [];
+ for (let i = 0; i < colgroup.length; i++) {
+ const col = colgroup[i];
+ const colSpan = col.getAttribute('span');
+ if (colSpan && +colSpan > 1) {
+ for (let j = 0; j < +colSpan; j++) {
+ const width = getTdHeight(col.getAttribute('width'), 72);
+ data.push(width);
+ }
+ } else {
+ const width = getTdHeight(col.getAttribute('width'), 72);
+ data.push(width);
+ }
+ }
+ return data;
+}
+
+function getTdHeight(height: string | null, defaultHeight: number) {
+ if (!height) return defaultHeight;
+ let firstHeight;
+ if (height.includes('pt')) {
+ firstHeight = ptToPx(parseFloat(height));
+ } else if (height.includes('px')) {
+ firstHeight = parseFloat(height);
+ } else {
+ firstHeight = (parseFloat(height) * 72) / 96;
+ }
+ return firstHeight;
+}
+
+export function handleTableRowGroup(table: string) {
+ const content = document.createElement('DIV');
+ const data: any[] = [];
+ content.innerHTML = table;
+ const rowGroup = content.querySelectorAll('table tr');
+ if (!rowGroup.length) return [];
+ for (let i = 0; i < rowGroup.length; i++) {
+ const row = rowGroup[i];
+ const tds = row.querySelectorAll('td');
+ let firstHeight = getTdHeight(tds[0].style.height, 19);
+
+ for (let k = 0; k < tds.length; k++) {
+ const rowSpan = tds[k].getAttribute('rowSpan');
+ // const height = getTdHeight(tds[k].style.height);
+ if (rowSpan && +rowSpan > 1) {
+ // for (let j = 0; j < +rowSpan; j++) {
+ // data.push(height);
+ // }
+ // i = i + +rowSpan - 1;
+ continue;
+ }
+ firstHeight = getTdHeight(tds[k].style.height, 19);
+ break;
+ }
+ data.push(firstHeight);
+ }
+ return data;
+}
+
+// 将table数据转为sheet数据
+export function handelTableToJson(table: string) {
+ let data: any[] = [];
+ const content = document.createElement('DIV');
+ content.innerHTML = table;
+ data = new Array(content.querySelectorAll('table tr').length);
+ if (!data.length) return [];
+ let colLen = 0;
+ const trs = content.querySelectorAll('table tr');
+ const firstTds = trs[0].querySelectorAll('td');
+ firstTds.forEach((item: HTMLTableCellElement) => {
+ let colSpan = 0;
+ const attr = item.getAttribute('colSpan');
+ if (attr !== null) {
+ colSpan = +attr;
+ } else {
+ colSpan = 1;
+ }
+ colLen += colSpan;
+ });
+ for (let i = 0; i < data.length; i++) {
+ data[i] = new Array(colLen);
+ }
+ let r = 0;
+ trs.forEach((item: any) => {
+ let c = 0;
+ item.querySelectorAll('td').forEach((td: HTMLTableCellElement) => {
+ const cell: ICellData = {};
+ if (td.querySelectorAll('span').length || td.querySelectorAll('font').length) {
+ const spanStyle = handleDomToJson(td);
+ if (typeof spanStyle !== 'string') {
+ cell.p = spanStyle;
+ }
+ }
+ const txt = td.innerText;
+ if (txt.trim().length === 0) {
+ cell.v = '';
+ cell.m = '';
+ } else {
+ // Todo,处理格式
+ cell.v = txt;
+ cell.m = txt;
+ }
+ const style = handleStringToStyle(td);
+ if (Tools.isPlainObject(style)) {
+ cell.s = style;
+ }
+ while (c < colLen && data[r][c] != null) {
+ c++;
+ }
+ if (c === colLen) {
+ return;
+ }
+ if (data[r][c] == null) {
+ data[r][c] = cell;
+ const rowSpan = Number(td.getAttribute('rowSpan')) ?? 1;
+ const colSpan = Number(td.getAttribute('colSpan')) ?? 1;
+ if (rowSpan > 1 || colSpan > 1) {
+ const first = { rs: +rowSpan - 1, cs: +colSpan - 1, r, c };
+ data[r][c].mc = first;
+ for (let rp = 0; rp < rowSpan; rp++) {
+ for (let cp = 0; cp < colSpan; cp++) {
+ if (rp === 0 && cp === 0) {
+ continue;
+ }
+ data[r + rp][c + cp] = { mc: null };
+ }
+ }
+ }
+ }
+ c++;
+ });
+ r++;
+ });
+
+ return data;
+}
+
+// 将文本格式数据转为sheet数据
+export function handlePlainToJson(plain: string) {
+ const data: any[] = [];
+ const content = document.createElement('DIV');
+ content.innerHTML = plain;
+ const dataChe = plain.replace(/\r/g, '');
+ const che = dataChe.split('\n');
+ const colCheLen = che[0].split('\t').length;
+ for (let i = 0; i < che.length; i++) {
+ if (che[i].split('\t').length < colCheLen) {
+ continue;
+ }
+ data.push(che[i].split('\t'));
+ }
+ for (let i = 0; i < data.length; i++) {
+ for (let j = 0; j < data[i].length; j++) {
+ if (data[i][j].length) {
+ data[i][j] = {
+ v: data[i][j] || '',
+ m: data[i][j] || '',
+ };
+ } else {
+ data[i][j] = null;
+ }
+ }
+ }
+
+ return data;
+}
+
+// 获取最终sheet数据
+export function handleTableMergeData(data: any[], selection?: IRange) {
+ const copyH = data.length;
+ const copyC = data[0].length;
+ let minH = 0; //应用范围首尾行
+ let maxH = minH + copyH - 1;
+ let minC = 0; //应用范围首尾列
+ let maxC = minC + copyC - 1;
+ if (selection) {
+ minH = selection.startRow; //应用范围首尾行
+ maxH = minH + copyH - 1;
+ minC = selection.startColumn; //应用范围首尾列
+ maxC = minC + copyC - 1;
+ }
+
+ const mergeData = [];
+
+ for (let i = 0; i < data.length; i++) {
+ for (let j = 0; j < data[i].length; j++) {
+ if (data[i][j] && typeof data[i][j] === 'object' && 'mc' in data[i][j]) {
+ if (data[i][j].mc) {
+ const mc = data[i][j].mc;
+ const startRow = mc.r + minH;
+ const endRow = startRow + mc.rs;
+ const startColumn = mc.c + minC;
+ const endColumn = startColumn + mc.cs;
+
+ mergeData.push({ startRow, endRow, startColumn, endColumn });
+ delete data[i][j].mc;
+ } else {
+ data[i][j] = null;
+ }
+ }
+ }
+ }
+
+ return {
+ data,
+ mergeData,
+ };
+}
+
+export function handelExcelToJson(html: string) {
+ let data: any[] = [];
+ const content = document.createElement('html');
+ content.innerHTML = html;
+ const styleText = content.querySelector('style')?.innerText;
+ if (!styleText) return;
+ const excelStyle = getStyles(styleText);
+
+ data = new Array(content.querySelectorAll('table tr').length);
+ if (!data.length) return [];
+ let colLen = 0;
+ const trs = content.querySelectorAll('table tr');
+ const firstTds = trs[0].querySelectorAll('td');
+ firstTds.forEach((item: HTMLTableCellElement) => {
+ let colSpan = 0;
+ const attr = item.getAttribute('colSpan');
+ if (attr !== null) {
+ colSpan = +attr;
+ } else {
+ colSpan = 1;
+ }
+ colLen += colSpan;
+ });
+ for (let i = 0; i < data.length; i++) {
+ data[i] = new Array(colLen);
+ }
+ let r = 0;
+ trs.forEach((item: any) => {
+ let c = 0;
+ item.querySelectorAll('td').forEach((td: HTMLTableCellElement) => {
+ const cell: ICellData = {};
+ if (td.querySelectorAll('span').length || td.querySelectorAll('font').length) {
+ const spanStyle = handleDomToJson(td);
+ if (typeof spanStyle !== 'string') {
+ cell.p = spanStyle;
+ }
+ }
+ const txt = td.innerText;
+ if (txt.trim().length === 0) {
+ cell.v = '';
+ cell.m = '';
+ } else {
+ // Todo,处理格式
+ cell.v = txt;
+ cell.m = txt;
+ }
+
+ let cssText = '';
+ for (const attr in excelStyle) {
+ if (td.classList.contains(attr)) {
+ cssText += excelStyle[attr];
+ }
+ }
+ const style = handleStringToStyle(td, cssText);
+
+ if (Tools.isPlainObject(style)) {
+ cell.s = style;
+ }
+ while (c < colLen && data[r][c] != null) {
+ c++;
+ }
+ if (c === colLen) {
+ return;
+ }
+ if (data[r][c] == null) {
+ data[r][c] = cell;
+ const rowSpan = Number(td.getAttribute('rowSpan')) ?? 1;
+ const colSpan = Number(td.getAttribute('colSpan')) ?? 1;
+
+ if (rowSpan > 1 || colSpan > 1) {
+ const first = { rs: +rowSpan - 1, cs: +colSpan - 1, r, c };
+ data[r][c].mc = first;
+ for (let rp = 0; rp < rowSpan; rp++) {
+ for (let cp = 0; cp < colSpan; cp++) {
+ if (rp === 0 && cp === 0) {
+ continue;
+ }
+ data[r + rp][c + cp] = { mc: null };
+ }
+ }
+ }
+ }
+ c++;
+ });
+ r++;
+ });
+
+ return data;
+}
+
+function getStyles(styleText: string): IKeyValue {
+ const output: IKeyValue = {};
+ const string = styleText.replaceAll('<!--', '').replaceAll('-->', '').trim();
+ const style = string?.replaceAll('\t', '').replaceAll('\n', '').split('}');
+ for (let i = 0; i < style.length; i++) {
+ if (!style[i]) continue;
+ let attr = style[i].split('{')[0].trim();
+ if (attr.includes('.')) {
+ attr = attr.slice(1);
+ }
+ const value = style[i].split('{')[1].trim();
+ output[attr] = value;
+ }
+
+ return output;
+}
diff --git a/packages/base-ui/src/Utils/index.ts b/packages/base-ui/src/utils/index.ts
similarity index 50%
rename from packages/base-ui/src/Utils/index.ts
rename to packages/base-ui/src/utils/index.ts
index bbebd88eb4..cd5f681250 100644
--- a/packages/base-ui/src/Utils/index.ts
+++ b/packages/base-ui/src/utils/index.ts
@@ -1 +1,2 @@
+export * from './cell';
export * from './util';
diff --git a/packages/base-ui/src/Utils/util.ts b/packages/base-ui/src/utils/util.ts
similarity index 100%
rename from packages/base-ui/src/Utils/util.ts
rename to packages/base-ui/src/utils/util.ts
diff --git a/packages/base-ui/src/views/components/shortcut-panel/ShortcutPanel.tsx b/packages/base-ui/src/views/components/shortcut-panel/ShortcutPanel.tsx
new file mode 100644
index 0000000000..831199947f
--- /dev/null
+++ b/packages/base-ui/src/views/components/shortcut-panel/ShortcutPanel.tsx
@@ -0,0 +1,88 @@
+import { LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useCallback, useEffect } from 'react';
+
+import { IShortcutService } from '../../../services/shortcut/shortcut.service';
+import styles from './index.module.less';
+
+interface IRenderShortcutItem {
+ title: string;
+ shortcut: string;
+}
+
+interface IShortcutGroup {
+ items: IRenderShortcutItem[];
+ sequence: number;
+ name: string;
+}
+
+/**
+ * This component is responsible for rendering the shortcut panel on the desktop version of the app.
+ */
+export function ShortcutPanel() {
+ const shortcutService = useDependency(IShortcutService);
+ const localeService = useDependency(LocaleService);
+
+ const [shortcutItems, setShortcutItems] = React.useState<IShortcutGroup[]>([]);
+
+ const updateShortcuts = useCallback(() => {
+ const shortcutGroups = new Map<string, IRenderShortcutItem[]>();
+
+ const shortcuts = shortcutService.getAllShortcuts().filter((item) => !!item.group);
+ for (const shortcut of shortcuts) {
+ const group = shortcut.group!;
+ const shortcutItem: IRenderShortcutItem = {
+ title: localeService.t(shortcut.description ?? shortcut.id),
+ shortcut: shortcutService.getShortcutDisplay(shortcut.id)!,
+ };
+
+ if (!/\d+_[a-zA-Z0-9]/.test(group)) {
+ throw new Error(`[ShortcutPanel]: Invalid shortcut group: ${group}!`);
+ }
+
+ if (!shortcutGroups.has(group)) {
+ shortcutGroups.set(group, []);
+ }
+ shortcutGroups.get(group)!.push(shortcutItem);
+ }
+
+ const toRender = Array.from(shortcutGroups.entries())
+ .map(([name, items]) => {
+ const groupSequence = name.split('_')[0];
+ const groupName = name.slice(groupSequence.length + 1);
+ return {
+ sequence: +groupSequence,
+ name: localeService.t(groupName),
+ items,
+ };
+ })
+ .sort((a, b) => a.sequence - b.sequence);
+
+ setShortcutItems(toRender);
+ }, [shortcutService, localeService]);
+
+ useEffect(() => {
+ // first update
+ updateShortcuts();
+
+ // subscribe to shortcut changes and re-render
+ const subscription = shortcutService.shortcutChanged$.subscribe(() => updateShortcuts());
+ return () => subscription.unsubscribe();
+ }, [shortcutService]);
+
+ return (
+ <div className={styles.shortcutPanel}>
+ {shortcutItems.map((group) => (
+ <div className={styles.shortcutPanelGroup} key={group.name}>
+ <div className={styles.shortcutPanelGroupTitle}>{group.name}</div>
+ {group.items.map((item, index) => (
+ <div className={styles.shortcutPanelItem} key={index}>
+ <span className={styles.shortcutPanelItemTitle}>{item.title}</span>
+ <span className={styles.shortcutPanelItemShortcut}>{item.shortcut}</span>
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/packages/base-ui/src/views/components/shortcut-panel/index.module.less b/packages/base-ui/src/views/components/shortcut-panel/index.module.less
new file mode 100644
index 0000000000..604c5e64b8
--- /dev/null
+++ b/packages/base-ui/src/views/components/shortcut-panel/index.module.less
@@ -0,0 +1,37 @@
+.shortcut-panel {
+ &-group-title {
+ height: 40px;
+ font-size: 13px;
+ line-height: 40px;
+ }
+
+ &-item {
+ display: flex;
+ justify-content: space-between;
+
+ height: 40px;
+
+ font-size: 13px;
+ line-height: 40px;
+
+ &-title {
+ overflow: hidden;
+ flex-grow: 1;
+ flex-shrink: 1;
+
+ max-width: 200px;
+
+ text-overflow: ellipsis;
+ text-wrap: nowrap;
+ }
+
+ &-shortcut {
+ flex-grow: 0;
+ flex-shrink: 0;
+ }
+
+ &:not(:last-of-type) {
+ border-bottom: 1px solid rgb(var(--grey-200));
+ }
+ }
+}